users.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "context"
  7. "database/sql"
  8. "fmt"
  9. "os"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. "github.com/go-macaron/binding"
  14. api "github.com/gogs/go-gogs-client"
  15. "github.com/pkg/errors"
  16. "gorm.io/gorm"
  17. log "unknwon.dev/clog/v2"
  18. "gogs.io/gogs/internal/auth"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/cryptoutil"
  21. "gogs.io/gogs/internal/dbutil"
  22. "gogs.io/gogs/internal/errutil"
  23. "gogs.io/gogs/internal/markup"
  24. "gogs.io/gogs/internal/osutil"
  25. "gogs.io/gogs/internal/repoutil"
  26. "gogs.io/gogs/internal/strutil"
  27. "gogs.io/gogs/internal/tool"
  28. "gogs.io/gogs/internal/userutil"
  29. )
  30. // UsersStore is the persistent interface for users.
  31. type UsersStore interface {
  32. // Authenticate validates username and password via given login source ID. It
  33. // returns ErrUserNotExist when the user was not found.
  34. //
  35. // When the "loginSourceID" is negative, it aborts the process and returns
  36. // ErrUserNotExist if the user was not found in the database.
  37. //
  38. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  39. // if the user has different login source ID than the "loginSourceID".
  40. //
  41. // When the "loginSourceID" is positive, it tries to authenticate via given
  42. // login source and creates a new user when not yet exists in the database.
  43. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  44. // Create creates a new user and persists to database. It returns
  45. // ErrNameNotAllowed if the given name or pattern of the name is not allowed as
  46. // a username, or ErrUserAlreadyExist when a user with same name already exists,
  47. // or ErrEmailAlreadyUsed if the email has been verified by another user.
  48. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
  49. // GetByEmail returns the user (not organization) with given email. It ignores
  50. // records with unverified emails and returns ErrUserNotExist when not found.
  51. GetByEmail(ctx context.Context, email string) (*User, error)
  52. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  53. // found.
  54. GetByID(ctx context.Context, id int64) (*User, error)
  55. // GetByUsername returns the user with given username. It returns
  56. // ErrUserNotExist when not found.
  57. GetByUsername(ctx context.Context, username string) (*User, error)
  58. // GetByKeyID returns the owner of given public key ID. It returns
  59. // ErrUserNotExist when not found.
  60. GetByKeyID(ctx context.Context, keyID int64) (*User, error)
  61. // GetMailableEmailsByUsernames returns a list of verified primary email
  62. // addresses (where email notifications are sent to) of users with given list of
  63. // usernames. Non-existing usernames are ignored.
  64. GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error)
  65. // SearchByName returns a list of users whose username or full name matches the
  66. // given keyword case-insensitively. Results are paginated by given page and
  67. // page size, and sorted by the given order (e.g. "id DESC"). A total count of
  68. // all results is also returned. If the order is not given, it's up to the
  69. // database to decide.
  70. SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error)
  71. // IsUsernameUsed returns true if the given username has been used other than
  72. // the excluded user (a non-positive ID effectively meaning check against all
  73. // users).
  74. IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool
  75. // ChangeUsername changes the username of the given user and updates all
  76. // references to the old username. It returns ErrNameNotAllowed if the given
  77. // name or pattern of the name is not allowed as a username, or
  78. // ErrUserAlreadyExist when another user with same name already exists.
  79. ChangeUsername(ctx context.Context, userID int64, newUsername string) error
  80. // Update updates fields for the given user.
  81. Update(ctx context.Context, userID int64, opts UpdateUserOptions) error
  82. // UseCustomAvatar uses the given avatar as the user custom avatar.
  83. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  84. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  85. // use look up avatar by email.
  86. DeleteCustomAvatar(ctx context.Context, userID int64) error
  87. // DeleteByID deletes the given user and all their resources. It returns
  88. // ErrUserOwnRepos when the user still has repository ownership, or returns
  89. // ErrUserHasOrgs when the user still has organization membership. It is more
  90. // performant to skip rewriting the "authorized_keys" file for individual
  91. // deletion in a batch operation.
  92. DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error
  93. // DeleteInactivated deletes all inactivated users.
  94. DeleteInactivated() error
  95. // AddEmail adds a new email address to given user. It returns
  96. // ErrEmailAlreadyUsed if the email has been verified by another user.
  97. AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error
  98. // GetEmail returns the email address of the given user. If `needsActivated` is
  99. // true, only activated email will be returned, otherwise, it may return
  100. // inactivated email addresses. It returns ErrEmailNotExist when no qualified
  101. // email is not found.
  102. GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error)
  103. // ListEmails returns all email addresses of the given user. It always includes
  104. // a primary email address.
  105. ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error)
  106. // MarkEmailActivated marks the email address of the given user as activated,
  107. // and new rands are generated for the user.
  108. MarkEmailActivated(ctx context.Context, userID int64, email string) error
  109. // MarkEmailPrimary marks the email address of the given user as primary. It
  110. // returns ErrEmailNotExist when the email is not found for the user, and
  111. // ErrEmailNotActivated when the email is not activated.
  112. MarkEmailPrimary(ctx context.Context, userID int64, email string) error
  113. // DeleteEmail deletes the email address of the given user.
  114. DeleteEmail(ctx context.Context, userID int64, email string) error
  115. // Follow marks the user to follow the other user.
  116. Follow(ctx context.Context, userID, followID int64) error
  117. // Unfollow removes the mark the user to follow the other user.
  118. Unfollow(ctx context.Context, userID, followID int64) error
  119. // IsFollowing returns true if the user is following the other user.
  120. IsFollowing(ctx context.Context, userID, followID int64) bool
  121. // ListFollowers returns a list of users that are following the given user.
  122. // Results are paginated by given page and page size, and sorted by the time of
  123. // follow in descending order.
  124. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  125. // ListFollowings returns a list of users that are followed by the given user.
  126. // Results are paginated by given page and page size, and sorted by the time of
  127. // follow in descending order.
  128. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  129. // List returns a list of users. Results are paginated by given page and page
  130. // size, and sorted by primary key (id) in ascending order.
  131. List(ctx context.Context, page, pageSize int) ([]*User, error)
  132. // Count returns the total number of users.
  133. Count(ctx context.Context) int64
  134. }
  135. var Users UsersStore
  136. var _ UsersStore = (*users)(nil)
  137. type users struct {
  138. *gorm.DB
  139. }
  140. // NewUsersStore returns a persistent interface for users with given database
  141. // connection.
  142. func NewUsersStore(db *gorm.DB) UsersStore {
  143. return &users{DB: db}
  144. }
  145. type ErrLoginSourceMismatch struct {
  146. args errutil.Args
  147. }
  148. // IsErrLoginSourceMismatch returns true if the underlying error has the type
  149. // ErrLoginSourceMismatch.
  150. func IsErrLoginSourceMismatch(err error) bool {
  151. _, ok := errors.Cause(err).(ErrLoginSourceMismatch)
  152. return ok
  153. }
  154. func (err ErrLoginSourceMismatch) Error() string {
  155. return fmt.Sprintf("login source mismatch: %v", err.args)
  156. }
  157. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  158. login = strings.ToLower(login)
  159. query := db.WithContext(ctx)
  160. if strings.Contains(login, "@") {
  161. query = query.Where("email = ?", login)
  162. } else {
  163. query = query.Where("lower_name = ?", login)
  164. }
  165. user := new(User)
  166. err := query.First(user).Error
  167. if err != nil && err != gorm.ErrRecordNotFound {
  168. return nil, errors.Wrap(err, "get user")
  169. }
  170. var authSourceID int64 // The login source ID will be used to authenticate the user
  171. createNewUser := false // Whether to create a new user after successful authentication
  172. // User found in the database
  173. if err == nil {
  174. // Note: This check is unnecessary but to reduce user confusion at login page
  175. // and make it more consistent from user's perspective.
  176. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  177. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  178. }
  179. // Validate password hash fetched from database for local accounts.
  180. if user.IsLocal() {
  181. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  182. return user, nil
  183. }
  184. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
  185. }
  186. authSourceID = user.LoginSource
  187. } else {
  188. // Non-local login source is always greater than 0.
  189. if loginSourceID <= 0 {
  190. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
  191. }
  192. authSourceID = loginSourceID
  193. createNewUser = true
  194. }
  195. source, err := LoginSources.GetByID(ctx, authSourceID)
  196. if err != nil {
  197. return nil, errors.Wrap(err, "get login source")
  198. }
  199. if !source.IsActived {
  200. return nil, errors.Errorf("login source %d is not activated", source.ID)
  201. }
  202. extAccount, err := source.Provider.Authenticate(login, password)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if !createNewUser {
  207. return user, nil
  208. }
  209. // Validate username make sure it satisfies requirement.
  210. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  211. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  212. }
  213. return db.Create(ctx, extAccount.Name, extAccount.Email,
  214. CreateUserOptions{
  215. FullName: extAccount.FullName,
  216. LoginSource: authSourceID,
  217. LoginName: extAccount.Login,
  218. Location: extAccount.Location,
  219. Website: extAccount.Website,
  220. Activated: true,
  221. Admin: extAccount.Admin,
  222. },
  223. )
  224. }
  225. func (db *users) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
  226. err := isUsernameAllowed(newUsername)
  227. if err != nil {
  228. return err
  229. }
  230. if db.IsUsernameUsed(ctx, newUsername, userID) {
  231. return ErrUserAlreadyExist{
  232. args: errutil.Args{
  233. "name": newUsername,
  234. },
  235. }
  236. }
  237. user, err := db.GetByID(ctx, userID)
  238. if err != nil {
  239. return errors.Wrap(err, "get user")
  240. }
  241. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  242. err := tx.Model(&User{}).
  243. Where("id = ?", user.ID).
  244. Updates(map[string]any{
  245. "lower_name": strings.ToLower(newUsername),
  246. "name": newUsername,
  247. "updated_unix": tx.NowFunc().Unix(),
  248. }).Error
  249. if err != nil {
  250. return errors.Wrap(err, "update user name")
  251. }
  252. // Stop here if it's just a case-change of the username
  253. if strings.EqualFold(user.Name, newUsername) {
  254. return nil
  255. }
  256. // Update all references to the user name in pull requests
  257. err = tx.Model(&PullRequest{}).
  258. Where("head_user_name = ?", user.LowerName).
  259. Update("head_user_name", strings.ToLower(newUsername)).
  260. Error
  261. if err != nil {
  262. return errors.Wrap(err, `update "pull_request.head_user_name"`)
  263. }
  264. // Delete local copies of repositories and their wikis that are owned by the user
  265. rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
  266. if err != nil {
  267. return errors.Wrap(err, "iterate repositories")
  268. }
  269. defer func() { _ = rows.Close() }()
  270. for rows.Next() {
  271. var repo struct {
  272. ID int64
  273. }
  274. err = tx.ScanRows(rows, &repo)
  275. if err != nil {
  276. return errors.Wrap(err, "scan rows")
  277. }
  278. deleteRepoLocalCopy(repo.ID)
  279. RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
  280. }
  281. if err = rows.Err(); err != nil {
  282. return errors.Wrap(err, "check rows.Err")
  283. }
  284. // Rename user directory if exists
  285. userPath := repoutil.UserPath(user.Name)
  286. if osutil.IsExist(userPath) {
  287. newUserPath := repoutil.UserPath(newUsername)
  288. err = os.Rename(userPath, newUserPath)
  289. if err != nil {
  290. return errors.Wrap(err, "rename user directory")
  291. }
  292. }
  293. return nil
  294. })
  295. }
  296. func (db *users) Count(ctx context.Context) int64 {
  297. var count int64
  298. db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
  299. return count
  300. }
  301. type CreateUserOptions struct {
  302. FullName string
  303. Password string
  304. LoginSource int64
  305. LoginName string
  306. Location string
  307. Website string
  308. Activated bool
  309. Admin bool
  310. }
  311. type ErrUserAlreadyExist struct {
  312. args errutil.Args
  313. }
  314. // IsErrUserAlreadyExist returns true if the underlying error has the type
  315. // ErrUserAlreadyExist.
  316. func IsErrUserAlreadyExist(err error) bool {
  317. _, ok := errors.Cause(err).(ErrUserAlreadyExist)
  318. return ok
  319. }
  320. func (err ErrUserAlreadyExist) Error() string {
  321. return fmt.Sprintf("user already exists: %v", err.args)
  322. }
  323. type ErrEmailAlreadyUsed struct {
  324. args errutil.Args
  325. }
  326. // IsErrEmailAlreadyUsed returns true if the underlying error has the type
  327. // ErrEmailAlreadyUsed.
  328. func IsErrEmailAlreadyUsed(err error) bool {
  329. _, ok := errors.Cause(err).(ErrEmailAlreadyUsed)
  330. return ok
  331. }
  332. func (err ErrEmailAlreadyUsed) Email() string {
  333. email, ok := err.args["email"].(string)
  334. if ok {
  335. return email
  336. }
  337. return "<email not found>"
  338. }
  339. func (err ErrEmailAlreadyUsed) Error() string {
  340. return fmt.Sprintf("email has been used: %v", err.args)
  341. }
  342. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  343. err := isUsernameAllowed(username)
  344. if err != nil {
  345. return nil, err
  346. }
  347. if db.IsUsernameUsed(ctx, username, 0) {
  348. return nil, ErrUserAlreadyExist{
  349. args: errutil.Args{
  350. "name": username,
  351. },
  352. }
  353. }
  354. email = strings.ToLower(strings.TrimSpace(email))
  355. _, err = db.GetByEmail(ctx, email)
  356. if err == nil {
  357. return nil, ErrEmailAlreadyUsed{
  358. args: errutil.Args{
  359. "email": email,
  360. },
  361. }
  362. } else if !IsErrUserNotExist(err) {
  363. return nil, err
  364. }
  365. user := &User{
  366. LowerName: strings.ToLower(username),
  367. Name: username,
  368. FullName: opts.FullName,
  369. Email: email,
  370. Password: opts.Password,
  371. LoginSource: opts.LoginSource,
  372. LoginName: opts.LoginName,
  373. Location: opts.Location,
  374. Website: opts.Website,
  375. MaxRepoCreation: -1,
  376. IsActive: opts.Activated,
  377. IsAdmin: opts.Admin,
  378. Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
  379. AvatarEmail: email,
  380. }
  381. user.Rands, err = userutil.RandomSalt()
  382. if err != nil {
  383. return nil, err
  384. }
  385. user.Salt, err = userutil.RandomSalt()
  386. if err != nil {
  387. return nil, err
  388. }
  389. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  390. return user, db.WithContext(ctx).Create(user).Error
  391. }
  392. func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  393. _ = os.Remove(userutil.CustomAvatarPath(userID))
  394. return db.WithContext(ctx).
  395. Model(&User{}).
  396. Where("id = ?", userID).
  397. Updates(map[string]any{
  398. "use_custom_avatar": false,
  399. "updated_unix": db.NowFunc().Unix(),
  400. }).
  401. Error
  402. }
  403. type ErrUserOwnRepos struct {
  404. args errutil.Args
  405. }
  406. // IsErrUserOwnRepos returns true if the underlying error has the type
  407. // ErrUserOwnRepos.
  408. func IsErrUserOwnRepos(err error) bool {
  409. _, ok := errors.Cause(err).(ErrUserOwnRepos)
  410. return ok
  411. }
  412. func (err ErrUserOwnRepos) Error() string {
  413. return fmt.Sprintf("user still has repository ownership: %v", err.args)
  414. }
  415. type ErrUserHasOrgs struct {
  416. args errutil.Args
  417. }
  418. // IsErrUserHasOrgs returns true if the underlying error has the type
  419. // ErrUserHasOrgs.
  420. func IsErrUserHasOrgs(err error) bool {
  421. _, ok := errors.Cause(err).(ErrUserHasOrgs)
  422. return ok
  423. }
  424. func (err ErrUserHasOrgs) Error() string {
  425. return fmt.Sprintf("user still has organization membership: %v", err.args)
  426. }
  427. func (db *users) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
  428. user, err := db.GetByID(ctx, userID)
  429. if err != nil {
  430. if IsErrUserNotExist(err) {
  431. return nil
  432. }
  433. return errors.Wrap(err, "get user")
  434. }
  435. // Double check the user is not a direct owner of any repository and not a
  436. // member of any organization.
  437. var count int64
  438. err = db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
  439. if err != nil {
  440. return errors.Wrap(err, "count repositories")
  441. } else if count > 0 {
  442. return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
  443. }
  444. err = db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
  445. if err != nil {
  446. return errors.Wrap(err, "count organization membership")
  447. } else if count > 0 {
  448. return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
  449. }
  450. needsRewriteAuthorizedKeys := false
  451. err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  452. /*
  453. Equivalent SQL for PostgreSQL:
  454. UPDATE repository
  455. SET num_watches = num_watches - 1
  456. WHERE id IN (
  457. SELECT repo_id FROM watch WHERE user_id = @userID
  458. )
  459. */
  460. err = tx.Table("repository").
  461. Where("id IN (?)", tx.
  462. Select("repo_id").
  463. Table("watch").
  464. Where("user_id = ?", userID),
  465. ).
  466. UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
  467. Error
  468. if err != nil {
  469. return errors.Wrap(err, `decrease "repository.num_watches"`)
  470. }
  471. /*
  472. Equivalent SQL for PostgreSQL:
  473. UPDATE repository
  474. SET num_stars = num_stars - 1
  475. WHERE id IN (
  476. SELECT repo_id FROM star WHERE uid = @userID
  477. )
  478. */
  479. err = tx.Table("repository").
  480. Where("id IN (?)", tx.
  481. Select("repo_id").
  482. Table("star").
  483. Where("uid = ?", userID),
  484. ).
  485. UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
  486. Error
  487. if err != nil {
  488. return errors.Wrap(err, `decrease "repository.num_stars"`)
  489. }
  490. /*
  491. Equivalent SQL for PostgreSQL:
  492. UPDATE user
  493. SET num_followers = num_followers - 1
  494. WHERE id IN (
  495. SELECT follow_id FROM follow WHERE user_id = @userID
  496. )
  497. */
  498. err = tx.Table("user").
  499. Where("id IN (?)", tx.
  500. Select("follow_id").
  501. Table("follow").
  502. Where("user_id = ?", userID),
  503. ).
  504. UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
  505. Error
  506. if err != nil {
  507. return errors.Wrap(err, `decrease "user.num_followers"`)
  508. }
  509. /*
  510. Equivalent SQL for PostgreSQL:
  511. UPDATE user
  512. SET num_following = num_following - 1
  513. WHERE id IN (
  514. SELECT user_id FROM follow WHERE follow_id = @userID
  515. )
  516. */
  517. err = tx.Table("user").
  518. Where("id IN (?)", tx.
  519. Select("user_id").
  520. Table("follow").
  521. Where("follow_id = ?", userID),
  522. ).
  523. UpdateColumn("num_following", gorm.Expr("num_following - 1")).
  524. Error
  525. if err != nil {
  526. return errors.Wrap(err, `decrease "user.num_following"`)
  527. }
  528. if !skipRewriteAuthorizedKeys {
  529. // We need to rewrite "authorized_keys" file if the user owns any public keys.
  530. needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
  531. }
  532. err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
  533. if err != nil {
  534. return errors.Wrap(err, "clear assignees")
  535. }
  536. for _, t := range []struct {
  537. table any
  538. where string
  539. }{
  540. {&Watch{}, "user_id = @userID"},
  541. {&Star{}, "uid = @userID"},
  542. {&Follow{}, "user_id = @userID OR follow_id = @userID"},
  543. {&PublicKey{}, "owner_id = @userID"},
  544. {&AccessToken{}, "uid = @userID"},
  545. {&Collaboration{}, "user_id = @userID"},
  546. {&Access{}, "user_id = @userID"},
  547. {&Action{}, "user_id = @userID"},
  548. {&IssueUser{}, "uid = @userID"},
  549. {&EmailAddress{}, "uid = @userID"},
  550. {&User{}, "id = @userID"},
  551. } {
  552. err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
  553. if err != nil {
  554. return errors.Wrapf(err, "clean up table %T", t.table)
  555. }
  556. }
  557. return nil
  558. })
  559. if err != nil {
  560. return err
  561. }
  562. _ = os.RemoveAll(repoutil.UserPath(user.Name))
  563. _ = os.Remove(userutil.CustomAvatarPath(userID))
  564. if needsRewriteAuthorizedKeys {
  565. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  566. if err != nil {
  567. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  568. }
  569. }
  570. return nil
  571. }
  572. // NOTE: We do not take context.Context here because this operation in practice
  573. // could much longer than the general request timeout (e.g. one minute).
  574. func (db *users) DeleteInactivated() error {
  575. var userIDs []int64
  576. err := db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
  577. if err != nil {
  578. return errors.Wrap(err, "get inactivated user IDs")
  579. }
  580. for _, userID := range userIDs {
  581. err = db.DeleteByID(context.Background(), userID, true)
  582. if err != nil {
  583. // Skip users that may had set to inactivated by admins.
  584. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  585. continue
  586. }
  587. return errors.Wrapf(err, "delete user with ID %d", userID)
  588. }
  589. }
  590. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  591. if err != nil {
  592. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  593. }
  594. return nil
  595. }
  596. func (*users) recountFollows(tx *gorm.DB, userID, followID int64) error {
  597. /*
  598. Equivalent SQL for PostgreSQL:
  599. UPDATE "user"
  600. SET num_followers = (
  601. SELECT COUNT(*) FROM follow WHERE follow_id = @followID
  602. )
  603. WHERE id = @followID
  604. */
  605. err := tx.Model(&User{}).
  606. Where("id = ?", followID).
  607. Update(
  608. "num_followers",
  609. tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
  610. ).
  611. Error
  612. if err != nil {
  613. return errors.Wrap(err, `update "user.num_followers"`)
  614. }
  615. /*
  616. Equivalent SQL for PostgreSQL:
  617. UPDATE "user"
  618. SET num_following = (
  619. SELECT COUNT(*) FROM follow WHERE user_id = @userID
  620. )
  621. WHERE id = @userID
  622. */
  623. err = tx.Model(&User{}).
  624. Where("id = ?", userID).
  625. Update(
  626. "num_following",
  627. tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
  628. ).
  629. Error
  630. if err != nil {
  631. return errors.Wrap(err, `update "user.num_following"`)
  632. }
  633. return nil
  634. }
  635. func (db *users) Follow(ctx context.Context, userID, followID int64) error {
  636. if userID == followID {
  637. return nil
  638. }
  639. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  640. f := &Follow{
  641. UserID: userID,
  642. FollowID: followID,
  643. }
  644. result := tx.FirstOrCreate(f, f)
  645. if result.Error != nil {
  646. return errors.Wrap(result.Error, "upsert")
  647. } else if result.RowsAffected <= 0 {
  648. return nil // Relation already exists
  649. }
  650. return db.recountFollows(tx, userID, followID)
  651. })
  652. }
  653. func (db *users) Unfollow(ctx context.Context, userID, followID int64) error {
  654. if userID == followID {
  655. return nil
  656. }
  657. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  658. err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
  659. if err != nil {
  660. return errors.Wrap(err, "delete")
  661. }
  662. return db.recountFollows(tx, userID, followID)
  663. })
  664. }
  665. func (db *users) IsFollowing(ctx context.Context, userID, followID int64) bool {
  666. return db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
  667. }
  668. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  669. type ErrUserNotExist struct {
  670. args errutil.Args
  671. }
  672. // IsErrUserNotExist returns true if the underlying error has the type
  673. // ErrUserNotExist.
  674. func IsErrUserNotExist(err error) bool {
  675. _, ok := errors.Cause(err).(ErrUserNotExist)
  676. return ok
  677. }
  678. func (err ErrUserNotExist) Error() string {
  679. return fmt.Sprintf("user does not exist: %v", err.args)
  680. }
  681. func (ErrUserNotExist) NotFound() bool {
  682. return true
  683. }
  684. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  685. if email == "" {
  686. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  687. }
  688. email = strings.ToLower(email)
  689. /*
  690. Equivalent SQL for PostgreSQL:
  691. SELECT * FROM "user"
  692. LEFT JOIN email_address ON email_address.uid = "user".id
  693. WHERE
  694. "user".type = @userType
  695. AND (
  696. "user".email = @email AND "user".is_active = TRUE
  697. OR email_address.email = @email AND email_address.is_activated = TRUE
  698. )
  699. */
  700. user := new(User)
  701. err := db.WithContext(ctx).
  702. Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
  703. Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
  704. Where(db.
  705. Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
  706. Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
  707. ).
  708. First(&user).
  709. Error
  710. if err != nil {
  711. if err == gorm.ErrRecordNotFound {
  712. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  713. }
  714. return nil, err
  715. }
  716. return user, nil
  717. }
  718. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  719. user := new(User)
  720. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  721. if err != nil {
  722. if err == gorm.ErrRecordNotFound {
  723. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  724. }
  725. return nil, err
  726. }
  727. return user, nil
  728. }
  729. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  730. user := new(User)
  731. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  732. if err != nil {
  733. if err == gorm.ErrRecordNotFound {
  734. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  735. }
  736. return nil, err
  737. }
  738. return user, nil
  739. }
  740. func (db *users) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
  741. user := new(User)
  742. err := db.WithContext(ctx).
  743. Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
  744. Where("public_key.id = ?", keyID).
  745. First(user).
  746. Error
  747. if err != nil {
  748. if err == gorm.ErrRecordNotFound {
  749. return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
  750. }
  751. return nil, err
  752. }
  753. return user, nil
  754. }
  755. func (db *users) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
  756. emails := make([]string, 0, len(usernames))
  757. return emails, db.WithContext(ctx).
  758. Model(&User{}).
  759. Select("email").
  760. Where("lower_name IN (?) AND is_active = ?", usernames, true).
  761. Find(&emails).Error
  762. }
  763. func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
  764. if username == "" {
  765. return false
  766. }
  767. return db.WithContext(ctx).
  768. Select("id").
  769. Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
  770. First(&User{}).
  771. Error != gorm.ErrRecordNotFound
  772. }
  773. func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
  774. users := make([]*User, 0, pageSize)
  775. return users, db.WithContext(ctx).
  776. Where("type = ?", UserTypeIndividual).
  777. Limit(pageSize).Offset((page - 1) * pageSize).
  778. Order("id ASC").
  779. Find(&users).
  780. Error
  781. }
  782. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  783. /*
  784. Equivalent SQL for PostgreSQL:
  785. SELECT * FROM "user"
  786. LEFT JOIN follow ON follow.user_id = "user".id
  787. WHERE follow.follow_id = @userID
  788. ORDER BY follow.id DESC
  789. LIMIT @limit OFFSET @offset
  790. */
  791. users := make([]*User, 0, pageSize)
  792. return users, db.WithContext(ctx).
  793. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  794. Where("follow.follow_id = ?", userID).
  795. Limit(pageSize).Offset((page - 1) * pageSize).
  796. Order("follow.id DESC").
  797. Find(&users).
  798. Error
  799. }
  800. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  801. /*
  802. Equivalent SQL for PostgreSQL:
  803. SELECT * FROM "user"
  804. LEFT JOIN follow ON follow.user_id = "user".id
  805. WHERE follow.user_id = @userID
  806. ORDER BY follow.id DESC
  807. LIMIT @limit OFFSET @offset
  808. */
  809. users := make([]*User, 0, pageSize)
  810. return users, db.WithContext(ctx).
  811. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  812. Where("follow.user_id = ?", userID).
  813. Limit(pageSize).Offset((page - 1) * pageSize).
  814. Order("follow.id DESC").
  815. Find(&users).
  816. Error
  817. }
  818. func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  819. if keyword == "" {
  820. return []*User{}, 0, nil
  821. }
  822. keyword = "%" + strings.ToLower(keyword) + "%"
  823. tx := db.WithContext(ctx).
  824. Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
  825. var count int64
  826. err := tx.Model(&User{}).Count(&count).Error
  827. if err != nil {
  828. return nil, 0, errors.Wrap(err, "count")
  829. }
  830. users := make([]*User, 0, pageSize)
  831. return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
  832. }
  833. func (db *users) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  834. return searchUserByName(ctx, db.DB, UserTypeIndividual, keyword, page, pageSize, orderBy)
  835. }
  836. type UpdateUserOptions struct {
  837. LoginSource *int64
  838. LoginName *string
  839. Password *string
  840. // GenerateNewRands indicates whether to force generate new rands for the user.
  841. GenerateNewRands bool
  842. FullName *string
  843. Email *string
  844. Website *string
  845. Location *string
  846. Description *string
  847. MaxRepoCreation *int
  848. LastRepoVisibility *bool
  849. IsActivated *bool
  850. IsAdmin *bool
  851. AllowGitHook *bool
  852. AllowImportLocal *bool
  853. ProhibitLogin *bool
  854. Avatar *string
  855. AvatarEmail *string
  856. }
  857. func (db *users) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
  858. updates := map[string]any{
  859. "updated_unix": db.NowFunc().Unix(),
  860. }
  861. if opts.LoginSource != nil {
  862. updates["login_source"] = *opts.LoginSource
  863. }
  864. if opts.LoginName != nil {
  865. updates["login_name"] = *opts.LoginName
  866. }
  867. if opts.Password != nil {
  868. salt, err := userutil.RandomSalt()
  869. if err != nil {
  870. return errors.Wrap(err, "generate salt")
  871. }
  872. updates["salt"] = salt
  873. updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
  874. opts.GenerateNewRands = true
  875. }
  876. if opts.GenerateNewRands {
  877. rands, err := userutil.RandomSalt()
  878. if err != nil {
  879. return errors.Wrap(err, "generate rands")
  880. }
  881. updates["rands"] = rands
  882. }
  883. if opts.FullName != nil {
  884. updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
  885. }
  886. if opts.Email != nil {
  887. _, err := db.GetByEmail(ctx, *opts.Email)
  888. if err == nil {
  889. return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
  890. } else if !IsErrUserNotExist(err) {
  891. return errors.Wrap(err, "check email")
  892. }
  893. updates["email"] = *opts.Email
  894. }
  895. if opts.Website != nil {
  896. updates["website"] = strutil.Truncate(*opts.Website, 255)
  897. }
  898. if opts.Location != nil {
  899. updates["location"] = strutil.Truncate(*opts.Location, 255)
  900. }
  901. if opts.Description != nil {
  902. updates["description"] = strutil.Truncate(*opts.Description, 255)
  903. }
  904. if opts.MaxRepoCreation != nil {
  905. if *opts.MaxRepoCreation < -1 {
  906. *opts.MaxRepoCreation = -1
  907. }
  908. updates["max_repo_creation"] = *opts.MaxRepoCreation
  909. }
  910. if opts.LastRepoVisibility != nil {
  911. updates["last_repo_visibility"] = *opts.LastRepoVisibility
  912. }
  913. if opts.IsActivated != nil {
  914. updates["is_active"] = *opts.IsActivated
  915. }
  916. if opts.IsAdmin != nil {
  917. updates["is_admin"] = *opts.IsAdmin
  918. }
  919. if opts.AllowGitHook != nil {
  920. updates["allow_git_hook"] = *opts.AllowGitHook
  921. }
  922. if opts.AllowImportLocal != nil {
  923. updates["allow_import_local"] = *opts.AllowImportLocal
  924. }
  925. if opts.ProhibitLogin != nil {
  926. updates["prohibit_login"] = *opts.ProhibitLogin
  927. }
  928. if opts.Avatar != nil {
  929. updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
  930. }
  931. if opts.AvatarEmail != nil {
  932. updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
  933. }
  934. return db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
  935. }
  936. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  937. err := userutil.SaveAvatar(userID, avatar)
  938. if err != nil {
  939. return errors.Wrap(err, "save avatar")
  940. }
  941. return db.WithContext(ctx).
  942. Model(&User{}).
  943. Where("id = ?", userID).
  944. Updates(map[string]any{
  945. "use_custom_avatar": true,
  946. "updated_unix": db.NowFunc().Unix(),
  947. }).
  948. Error
  949. }
  950. func (db *users) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
  951. email = strings.ToLower(strings.TrimSpace(email))
  952. _, err := db.GetByEmail(ctx, email)
  953. if err == nil {
  954. return ErrEmailAlreadyUsed{
  955. args: errutil.Args{
  956. "email": email,
  957. },
  958. }
  959. } else if !IsErrUserNotExist(err) {
  960. return errors.Wrap(err, "check user by email")
  961. }
  962. return db.WithContext(ctx).Create(
  963. &EmailAddress{
  964. UserID: userID,
  965. Email: email,
  966. IsActivated: isActivated,
  967. },
  968. ).Error
  969. }
  970. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  971. type ErrEmailNotExist struct {
  972. args errutil.Args
  973. }
  974. // IsErrEmailAddressNotExist returns true if the underlying error has the type
  975. // ErrEmailNotExist.
  976. func IsErrEmailAddressNotExist(err error) bool {
  977. _, ok := errors.Cause(err).(ErrEmailNotExist)
  978. return ok
  979. }
  980. func (err ErrEmailNotExist) Error() string {
  981. return fmt.Sprintf("email address does not exist: %v", err.args)
  982. }
  983. func (ErrEmailNotExist) NotFound() bool {
  984. return true
  985. }
  986. func (db *users) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
  987. tx := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
  988. if needsActivated {
  989. tx = tx.Where("is_activated = ?", true)
  990. }
  991. emailAddress := new(EmailAddress)
  992. err := tx.First(emailAddress).Error
  993. if err != nil {
  994. if err == gorm.ErrRecordNotFound {
  995. return nil, ErrEmailNotExist{
  996. args: errutil.Args{
  997. "email": email,
  998. },
  999. }
  1000. }
  1001. return nil, err
  1002. }
  1003. return emailAddress, nil
  1004. }
  1005. func (db *users) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
  1006. user, err := db.GetByID(ctx, userID)
  1007. if err != nil {
  1008. return nil, errors.Wrap(err, "get user")
  1009. }
  1010. var emails []*EmailAddress
  1011. err = db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
  1012. if err != nil {
  1013. return nil, errors.Wrap(err, "list emails")
  1014. }
  1015. isPrimaryFound := false
  1016. for _, email := range emails {
  1017. if email.Email == user.Email {
  1018. isPrimaryFound = true
  1019. email.IsPrimary = true
  1020. break
  1021. }
  1022. }
  1023. // We always want the primary email address displayed, even if it's not in the
  1024. // email_address table yet.
  1025. if !isPrimaryFound {
  1026. emails = append(emails, &EmailAddress{
  1027. Email: user.Email,
  1028. IsActivated: user.IsActive,
  1029. IsPrimary: true,
  1030. })
  1031. }
  1032. return emails, nil
  1033. }
  1034. func (db *users) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
  1035. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1036. err := db.WithContext(ctx).
  1037. Model(&EmailAddress{}).
  1038. Where("uid = ? AND email = ?", userID, email).
  1039. Update("is_activated", true).
  1040. Error
  1041. if err != nil {
  1042. return errors.Wrap(err, "mark email activated")
  1043. }
  1044. return NewUsersStore(tx).Update(ctx, userID, UpdateUserOptions{GenerateNewRands: true})
  1045. })
  1046. }
  1047. type ErrEmailNotVerified struct {
  1048. args errutil.Args
  1049. }
  1050. // IsErrEmailNotVerified returns true if the underlying error has the type
  1051. // ErrEmailNotVerified.
  1052. func IsErrEmailNotVerified(err error) bool {
  1053. _, ok := errors.Cause(err).(ErrEmailNotVerified)
  1054. return ok
  1055. }
  1056. func (err ErrEmailNotVerified) Error() string {
  1057. return fmt.Sprintf("email has not been verified: %v", err.args)
  1058. }
  1059. func (db *users) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
  1060. var emailAddress EmailAddress
  1061. err := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
  1062. if err != nil {
  1063. if err == gorm.ErrRecordNotFound {
  1064. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1065. }
  1066. return errors.Wrap(err, "get email address")
  1067. }
  1068. if !emailAddress.IsActivated {
  1069. return ErrEmailNotVerified{args: errutil.Args{"email": email}}
  1070. }
  1071. user, err := db.GetByID(ctx, userID)
  1072. if err != nil {
  1073. return errors.Wrap(err, "get user")
  1074. }
  1075. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1076. // Make sure the former primary email doesn't disappear.
  1077. err = tx.FirstOrCreate(
  1078. &EmailAddress{
  1079. UserID: user.ID,
  1080. Email: user.Email,
  1081. IsActivated: user.IsActive,
  1082. },
  1083. &EmailAddress{
  1084. UserID: user.ID,
  1085. Email: user.Email,
  1086. },
  1087. ).Error
  1088. if err != nil {
  1089. return errors.Wrap(err, "upsert former primary email address")
  1090. }
  1091. return tx.Model(&User{}).
  1092. Where("id = ?", user.ID).
  1093. Updates(map[string]any{
  1094. "email": email,
  1095. "updated_unix": tx.NowFunc().Unix(),
  1096. },
  1097. ).Error
  1098. })
  1099. }
  1100. func (db *users) DeleteEmail(ctx context.Context, userID int64, email string) error {
  1101. return db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).Delete(&EmailAddress{}).Error
  1102. }
  1103. // UserType indicates the type of the user account.
  1104. type UserType int
  1105. const (
  1106. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  1107. UserTypeOrganization
  1108. )
  1109. // User represents the object of an individual or an organization.
  1110. type User struct {
  1111. ID int64 `gorm:"primaryKey"`
  1112. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  1113. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  1114. FullName string
  1115. // Email is the primary email address (to be used for communication)
  1116. Email string `xorm:"NOT NULL" gorm:"not null"`
  1117. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  1118. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1119. LoginName string
  1120. Type UserType
  1121. Location string
  1122. Website string
  1123. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1124. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1125. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  1126. CreatedUnix int64
  1127. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  1128. UpdatedUnix int64
  1129. // Remember visibility choice for convenience, true for private
  1130. LastRepoVisibility bool
  1131. // Maximum repository creation limit, -1 means use global default
  1132. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  1133. // Permissions
  1134. IsActive bool // Activate primary email
  1135. IsAdmin bool
  1136. AllowGitHook bool
  1137. AllowImportLocal bool // Allow migrate repository by local path
  1138. ProhibitLogin bool
  1139. // Avatar
  1140. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  1141. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  1142. UseCustomAvatar bool
  1143. // Counters
  1144. NumFollowers int
  1145. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1146. NumStars int
  1147. NumRepos int
  1148. // For organization
  1149. Description string
  1150. NumTeams int
  1151. NumMembers int
  1152. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  1153. Members []*User `xorm:"-" gorm:"-" json:"-"`
  1154. }
  1155. // BeforeCreate implements the GORM create hook.
  1156. func (u *User) BeforeCreate(tx *gorm.DB) error {
  1157. if u.CreatedUnix == 0 {
  1158. u.CreatedUnix = tx.NowFunc().Unix()
  1159. u.UpdatedUnix = u.CreatedUnix
  1160. }
  1161. return nil
  1162. }
  1163. // AfterFind implements the GORM query hook.
  1164. func (u *User) AfterFind(_ *gorm.DB) error {
  1165. u.FullName = markup.Sanitize(u.FullName)
  1166. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  1167. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  1168. return nil
  1169. }
  1170. // IsLocal returns true if the user is created as local account.
  1171. func (u *User) IsLocal() bool {
  1172. return u.LoginSource <= 0
  1173. }
  1174. // IsOrganization returns true if the user is an organization.
  1175. func (u *User) IsOrganization() bool {
  1176. return u.Type == UserTypeOrganization
  1177. }
  1178. // APIFormat returns the API format of a user.
  1179. func (u *User) APIFormat() *api.User {
  1180. return &api.User{
  1181. ID: u.ID,
  1182. UserName: u.Name,
  1183. Login: u.Name,
  1184. FullName: u.FullName,
  1185. Email: u.Email,
  1186. AvatarUrl: u.AvatarURL(),
  1187. }
  1188. }
  1189. // maxNumRepos returns the maximum number of repositories that the user can have
  1190. // direct ownership.
  1191. func (u *User) maxNumRepos() int {
  1192. if u.MaxRepoCreation <= -1 {
  1193. return conf.Repository.MaxCreationLimit
  1194. }
  1195. return u.MaxRepoCreation
  1196. }
  1197. // canCreateRepo returns true if the user can create a repository.
  1198. func (u *User) canCreateRepo() bool {
  1199. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1200. }
  1201. // CanCreateOrganization returns true if user can create organizations.
  1202. func (u *User) CanCreateOrganization() bool {
  1203. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  1204. }
  1205. // CanEditGitHook returns true if user can edit Git hooks.
  1206. func (u *User) CanEditGitHook() bool {
  1207. return u.IsAdmin || u.AllowGitHook
  1208. }
  1209. // CanImportLocal returns true if user can migrate repositories by local path.
  1210. func (u *User) CanImportLocal() bool {
  1211. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1212. }
  1213. // DisplayName returns the full name of the user if it's not empty, returns the
  1214. // username otherwise.
  1215. func (u *User) DisplayName() string {
  1216. if len(u.FullName) > 0 {
  1217. return u.FullName
  1218. }
  1219. return u.Name
  1220. }
  1221. // HomeURLPath returns the URL path to the user or organization home page.
  1222. //
  1223. // TODO(unknwon): This is also used in templates, which should be fixed by
  1224. // having a dedicated type `template.User` and move this to the "userutil"
  1225. // package.
  1226. func (u *User) HomeURLPath() string {
  1227. return conf.Server.Subpath + "/" + u.Name
  1228. }
  1229. // HTMLURL returns the full URL to the user or organization home page.
  1230. //
  1231. // TODO(unknwon): This is also used in templates, which should be fixed by
  1232. // having a dedicated type `template.User` and move this to the "userutil"
  1233. // package.
  1234. func (u *User) HTMLURL() string {
  1235. return conf.Server.ExternalURL + u.Name
  1236. }
  1237. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1238. // user enables Gravatar-like service, then an external URL will be returned.
  1239. //
  1240. // TODO(unknwon): This is also used in templates, which should be fixed by
  1241. // having a dedicated type `template.User` and move this to the "userutil"
  1242. // package.
  1243. func (u *User) AvatarURLPath() string {
  1244. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1245. if u.ID <= 0 {
  1246. return defaultURLPath
  1247. }
  1248. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1249. switch {
  1250. case u.UseCustomAvatar:
  1251. if !hasCustomAvatar {
  1252. return defaultURLPath
  1253. }
  1254. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1255. case conf.Picture.DisableGravatar:
  1256. if !hasCustomAvatar {
  1257. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  1258. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1259. }
  1260. }
  1261. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1262. }
  1263. return tool.AvatarLink(u.AvatarEmail)
  1264. }
  1265. // AvatarURL returns the full URL to the user or organization avatar. If the
  1266. // user enables Gravatar-like service, then an external URL will be returned.
  1267. //
  1268. // TODO(unknwon): This is also used in templates, which should be fixed by
  1269. // having a dedicated type `template.User` and move this to the "userutil"
  1270. // package.
  1271. func (u *User) AvatarURL() string {
  1272. link := u.AvatarURLPath()
  1273. if link[0] == '/' && link[1] != '/' {
  1274. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1275. }
  1276. return link
  1277. }
  1278. // IsFollowing returns true if the user is following the given user.
  1279. //
  1280. // TODO(unknwon): This is also used in templates, which should be fixed by
  1281. // having a dedicated type `template.User`.
  1282. func (u *User) IsFollowing(followID int64) bool {
  1283. return Users.IsFollowing(context.TODO(), u.ID, followID)
  1284. }
  1285. // IsUserOrgOwner returns true if the user is in the owner team of the given
  1286. // organization.
  1287. //
  1288. // TODO(unknwon): This is also used in templates, which should be fixed by
  1289. // having a dedicated type `template.User`.
  1290. func (u *User) IsUserOrgOwner(orgId int64) bool {
  1291. return IsOrganizationOwner(orgId, u.ID)
  1292. }
  1293. // IsPublicMember returns true if the user has public membership of the given
  1294. // organization.
  1295. //
  1296. // TODO(unknwon): This is also used in templates, which should be fixed by
  1297. // having a dedicated type `template.User`.
  1298. func (u *User) IsPublicMember(orgId int64) bool {
  1299. return IsPublicMembership(orgId, u.ID)
  1300. }
  1301. // GetOrganizationCount returns the count of organization membership that the
  1302. // user has.
  1303. //
  1304. // TODO(unknwon): This is also used in templates, which should be fixed by
  1305. // having a dedicated type `template.User`.
  1306. func (u *User) GetOrganizationCount() (int64, error) {
  1307. return Orgs.CountByUser(context.TODO(), u.ID)
  1308. }
  1309. // ShortName truncates and returns the username at most in given length.
  1310. //
  1311. // TODO(unknwon): This is also used in templates, which should be fixed by
  1312. // having a dedicated type `template.User`.
  1313. func (u *User) ShortName(length int) string {
  1314. return strutil.Ellipsis(u.Name, length)
  1315. }
  1316. // NewGhostUser creates and returns a fake user for people who has deleted their
  1317. // accounts.
  1318. //
  1319. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1320. // translate the text to local language.
  1321. func NewGhostUser() *User {
  1322. return &User{
  1323. ID: -1,
  1324. Name: "Ghost",
  1325. LowerName: "ghost",
  1326. }
  1327. }
  1328. var (
  1329. reservedUsernames = map[string]struct{}{
  1330. "-": {},
  1331. "explore": {},
  1332. "create": {},
  1333. "assets": {},
  1334. "css": {},
  1335. "img": {},
  1336. "js": {},
  1337. "less": {},
  1338. "plugins": {},
  1339. "debug": {},
  1340. "raw": {},
  1341. "install": {},
  1342. "api": {},
  1343. "avatar": {},
  1344. "user": {},
  1345. "org": {},
  1346. "help": {},
  1347. "stars": {},
  1348. "issues": {},
  1349. "pulls": {},
  1350. "commits": {},
  1351. "repo": {},
  1352. "template": {},
  1353. "admin": {},
  1354. "new": {},
  1355. ".": {},
  1356. "..": {},
  1357. }
  1358. reservedUsernamePatterns = []string{"*.keys"}
  1359. )
  1360. type ErrNameNotAllowed struct {
  1361. args errutil.Args
  1362. }
  1363. // IsErrNameNotAllowed returns true if the underlying error has the type
  1364. // ErrNameNotAllowed.
  1365. func IsErrNameNotAllowed(err error) bool {
  1366. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1367. return ok
  1368. }
  1369. func (err ErrNameNotAllowed) Value() string {
  1370. val, ok := err.args["name"].(string)
  1371. if ok {
  1372. return val
  1373. }
  1374. val, ok = err.args["pattern"].(string)
  1375. if ok {
  1376. return val
  1377. }
  1378. return "<value not found>"
  1379. }
  1380. func (err ErrNameNotAllowed) Error() string {
  1381. return fmt.Sprintf("name is not allowed: %v", err.args)
  1382. }
  1383. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1384. // allowed based on given reserved names and patterns. Names are exact match,
  1385. // patterns can be prefix or suffix match with the wildcard ("*").
  1386. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1387. name = strings.TrimSpace(strings.ToLower(name))
  1388. if utf8.RuneCountInString(name) == 0 {
  1389. return ErrNameNotAllowed{
  1390. args: errutil.Args{
  1391. "reason": "empty name",
  1392. },
  1393. }
  1394. }
  1395. if _, ok := names[name]; ok {
  1396. return ErrNameNotAllowed{
  1397. args: errutil.Args{
  1398. "reason": "reserved",
  1399. "name": name,
  1400. },
  1401. }
  1402. }
  1403. for _, pattern := range patterns {
  1404. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1405. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1406. return ErrNameNotAllowed{
  1407. args: errutil.Args{
  1408. "reason": "reserved",
  1409. "pattern": pattern,
  1410. },
  1411. }
  1412. }
  1413. }
  1414. return nil
  1415. }
  1416. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1417. // the name is not allowed as a username.
  1418. func isUsernameAllowed(name string) error {
  1419. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1420. }
  1421. // EmailAddress is an email address of a user.
  1422. type EmailAddress struct {
  1423. ID int64 `gorm:"primaryKey"`
  1424. UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
  1425. Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
  1426. IsActivated bool `gorm:"not null;default:FALSE"`
  1427. IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
  1428. }
  1429. // Follow represents relations of users and their followers.
  1430. type Follow struct {
  1431. ID int64 `gorm:"primaryKey"`
  1432. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1433. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1434. }