users.go 45 KB

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