users.go 48 KB

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