users.go 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. _, ok := errors.Cause(err).(ErrUserOwnRepos)
  409. return ok
  410. }
  411. func (err ErrUserOwnRepos) Error() string {
  412. return fmt.Sprintf("user still has repository ownership: %v", err.args)
  413. }
  414. type ErrUserHasOrgs struct {
  415. args errutil.Args
  416. }
  417. // IsErrUserHasOrgs returns true if the underlying error has the type
  418. // ErrUserHasOrgs.
  419. func IsErrUserHasOrgs(err error) bool {
  420. _, ok := errors.Cause(err).(ErrUserHasOrgs)
  421. return ok
  422. }
  423. func (err ErrUserHasOrgs) Error() string {
  424. return fmt.Sprintf("user still has organization membership: %v", err.args)
  425. }
  426. func (db *users) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
  427. user, err := db.GetByID(ctx, userID)
  428. if err != nil {
  429. if IsErrUserNotExist(err) {
  430. return nil
  431. }
  432. return errors.Wrap(err, "get user")
  433. }
  434. // Double check the user is not a direct owner of any repository and not a
  435. // member of any organization.
  436. var count int64
  437. err = db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
  438. if err != nil {
  439. return errors.Wrap(err, "count repositories")
  440. } else if count > 0 {
  441. return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
  442. }
  443. err = db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
  444. if err != nil {
  445. return errors.Wrap(err, "count organization membership")
  446. } else if count > 0 {
  447. return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
  448. }
  449. needsRewriteAuthorizedKeys := false
  450. err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  451. /*
  452. Equivalent SQL for PostgreSQL:
  453. UPDATE repository
  454. SET num_watches = num_watches - 1
  455. WHERE id IN (
  456. SELECT repo_id FROM watch WHERE user_id = @userID
  457. )
  458. */
  459. err = tx.Table("repository").
  460. Where("id IN (?)", tx.
  461. Select("repo_id").
  462. Table("watch").
  463. Where("user_id = ?", userID),
  464. ).
  465. UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
  466. Error
  467. if err != nil {
  468. return errors.Wrap(err, `decrease "repository.num_watches"`)
  469. }
  470. /*
  471. Equivalent SQL for PostgreSQL:
  472. UPDATE repository
  473. SET num_stars = num_stars - 1
  474. WHERE id IN (
  475. SELECT repo_id FROM star WHERE uid = @userID
  476. )
  477. */
  478. err = tx.Table("repository").
  479. Where("id IN (?)", tx.
  480. Select("repo_id").
  481. Table("star").
  482. Where("uid = ?", userID),
  483. ).
  484. UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
  485. Error
  486. if err != nil {
  487. return errors.Wrap(err, `decrease "repository.num_stars"`)
  488. }
  489. /*
  490. Equivalent SQL for PostgreSQL:
  491. UPDATE user
  492. SET num_followers = num_followers - 1
  493. WHERE id IN (
  494. SELECT follow_id FROM follow WHERE user_id = @userID
  495. )
  496. */
  497. err = tx.Table("user").
  498. Where("id IN (?)", tx.
  499. Select("follow_id").
  500. Table("follow").
  501. Where("user_id = ?", userID),
  502. ).
  503. UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
  504. Error
  505. if err != nil {
  506. return errors.Wrap(err, `decrease "user.num_followers"`)
  507. }
  508. /*
  509. Equivalent SQL for PostgreSQL:
  510. UPDATE user
  511. SET num_following = num_following - 1
  512. WHERE id IN (
  513. SELECT user_id FROM follow WHERE follow_id = @userID
  514. )
  515. */
  516. err = tx.Table("user").
  517. Where("id IN (?)", tx.
  518. Select("user_id").
  519. Table("follow").
  520. Where("follow_id = ?", userID),
  521. ).
  522. UpdateColumn("num_following", gorm.Expr("num_following - 1")).
  523. Error
  524. if err != nil {
  525. return errors.Wrap(err, `decrease "user.num_following"`)
  526. }
  527. if !skipRewriteAuthorizedKeys {
  528. // We need to rewrite "authorized_keys" file if the user owns any public keys.
  529. needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
  530. }
  531. err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
  532. if err != nil {
  533. return errors.Wrap(err, "clear assignees")
  534. }
  535. for _, t := range []struct {
  536. table any
  537. where string
  538. }{
  539. {&Watch{}, "user_id = @userID"},
  540. {&Star{}, "uid = @userID"},
  541. {&Follow{}, "user_id = @userID OR follow_id = @userID"},
  542. {&PublicKey{}, "owner_id = @userID"},
  543. {&AccessToken{}, "uid = @userID"},
  544. {&Collaboration{}, "user_id = @userID"},
  545. {&Access{}, "user_id = @userID"},
  546. {&Action{}, "user_id = @userID"},
  547. {&IssueUser{}, "uid = @userID"},
  548. {&EmailAddress{}, "uid = @userID"},
  549. {&User{}, "id = @userID"},
  550. } {
  551. err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
  552. if err != nil {
  553. return errors.Wrapf(err, "clean up table %T", t.table)
  554. }
  555. }
  556. return nil
  557. })
  558. if err != nil {
  559. return err
  560. }
  561. _ = os.RemoveAll(repoutil.UserPath(user.Name))
  562. _ = os.Remove(userutil.CustomAvatarPath(userID))
  563. if needsRewriteAuthorizedKeys {
  564. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  565. if err != nil {
  566. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  567. }
  568. }
  569. return nil
  570. }
  571. // NOTE: We do not take context.Context here because this operation in practice
  572. // could much longer than the general request timeout (e.g. one minute).
  573. func (db *users) DeleteInactivated() error {
  574. var userIDs []int64
  575. err := db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
  576. if err != nil {
  577. return errors.Wrap(err, "get inactivated user IDs")
  578. }
  579. for _, userID := range userIDs {
  580. err = db.DeleteByID(context.Background(), userID, true)
  581. if err != nil {
  582. // Skip users that may had set to inactivated by admins.
  583. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  584. continue
  585. }
  586. return errors.Wrapf(err, "delete user with ID %d", userID)
  587. }
  588. }
  589. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  590. if err != nil {
  591. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  592. }
  593. return nil
  594. }
  595. func (*users) recountFollows(tx *gorm.DB, userID, followID int64) error {
  596. /*
  597. Equivalent SQL for PostgreSQL:
  598. UPDATE "user"
  599. SET num_followers = (
  600. SELECT COUNT(*) FROM follow WHERE follow_id = @followID
  601. )
  602. WHERE id = @followID
  603. */
  604. err := tx.Model(&User{}).
  605. Where("id = ?", followID).
  606. Update(
  607. "num_followers",
  608. tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
  609. ).
  610. Error
  611. if err != nil {
  612. return errors.Wrap(err, `update "user.num_followers"`)
  613. }
  614. /*
  615. Equivalent SQL for PostgreSQL:
  616. UPDATE "user"
  617. SET num_following = (
  618. SELECT COUNT(*) FROM follow WHERE user_id = @userID
  619. )
  620. WHERE id = @userID
  621. */
  622. err = tx.Model(&User{}).
  623. Where("id = ?", userID).
  624. Update(
  625. "num_following",
  626. tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
  627. ).
  628. Error
  629. if err != nil {
  630. return errors.Wrap(err, `update "user.num_following"`)
  631. }
  632. return nil
  633. }
  634. func (db *users) Follow(ctx context.Context, userID, followID int64) error {
  635. if userID == followID {
  636. return nil
  637. }
  638. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  639. f := &Follow{
  640. UserID: userID,
  641. FollowID: followID,
  642. }
  643. result := tx.FirstOrCreate(f, f)
  644. if result.Error != nil {
  645. return errors.Wrap(result.Error, "upsert")
  646. } else if result.RowsAffected <= 0 {
  647. return nil // Relation already exists
  648. }
  649. return db.recountFollows(tx, userID, followID)
  650. })
  651. }
  652. func (db *users) Unfollow(ctx context.Context, userID, followID int64) error {
  653. if userID == followID {
  654. return nil
  655. }
  656. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  657. err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
  658. if err != nil {
  659. return errors.Wrap(err, "delete")
  660. }
  661. return db.recountFollows(tx, userID, followID)
  662. })
  663. }
  664. func (db *users) IsFollowing(ctx context.Context, userID, followID int64) bool {
  665. return db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
  666. }
  667. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  668. type ErrUserNotExist struct {
  669. args errutil.Args
  670. }
  671. // IsErrUserNotExist returns true if the underlying error has the type
  672. // ErrUserNotExist.
  673. func IsErrUserNotExist(err error) bool {
  674. return errors.As(err, &ErrUserNotExist{})
  675. }
  676. func (err ErrUserNotExist) Error() string {
  677. return fmt.Sprintf("user does not exist: %v", err.args)
  678. }
  679. func (ErrUserNotExist) NotFound() bool {
  680. return true
  681. }
  682. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  683. if email == "" {
  684. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  685. }
  686. email = strings.ToLower(email)
  687. /*
  688. Equivalent SQL for PostgreSQL:
  689. SELECT * FROM "user"
  690. LEFT JOIN email_address ON email_address.uid = "user".id
  691. WHERE
  692. "user".type = @userType
  693. AND (
  694. "user".email = @email AND "user".is_active = TRUE
  695. OR email_address.email = @email AND email_address.is_activated = TRUE
  696. )
  697. */
  698. user := new(User)
  699. err := db.WithContext(ctx).
  700. Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
  701. Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
  702. Where(db.
  703. Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
  704. Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
  705. ).
  706. First(&user).
  707. Error
  708. if err != nil {
  709. if errors.Is(err, gorm.ErrRecordNotFound) {
  710. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  711. }
  712. return nil, err
  713. }
  714. return user, nil
  715. }
  716. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  717. user := new(User)
  718. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  719. if err != nil {
  720. if errors.Is(err, gorm.ErrRecordNotFound) {
  721. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  722. }
  723. return nil, err
  724. }
  725. return user, nil
  726. }
  727. func getUserByUsername(ctx context.Context, db *gorm.DB, userType UserType, username string) (*User, error) {
  728. if username == "" {
  729. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  730. }
  731. user := new(User)
  732. err := db.WithContext(ctx).
  733. Where("type = ? AND lower_name = ?", userType, strings.ToLower(username)).
  734. First(user).
  735. Error
  736. if err != nil {
  737. if errors.Is(err, gorm.ErrRecordNotFound) {
  738. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  739. }
  740. return nil, err
  741. }
  742. return user, nil
  743. }
  744. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  745. return getUserByUsername(ctx, db.DB, UserTypeIndividual, username)
  746. }
  747. func (db *users) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
  748. user := new(User)
  749. err := db.WithContext(ctx).
  750. Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
  751. Where("public_key.id = ?", keyID).
  752. First(user).
  753. Error
  754. if err != nil {
  755. if errors.Is(err, gorm.ErrRecordNotFound) {
  756. return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
  757. }
  758. return nil, err
  759. }
  760. return user, nil
  761. }
  762. func (db *users) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
  763. emails := make([]string, 0, len(usernames))
  764. return emails, db.WithContext(ctx).
  765. Model(&User{}).
  766. Select("email").
  767. Where("lower_name IN (?) AND is_active = ?", usernames, true).
  768. Find(&emails).Error
  769. }
  770. func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
  771. if username == "" {
  772. return false
  773. }
  774. err := db.WithContext(ctx).
  775. Select("id").
  776. Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
  777. First(&User{}).
  778. Error
  779. return !errors.Is(err, gorm.ErrRecordNotFound)
  780. }
  781. func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
  782. users := make([]*User, 0, pageSize)
  783. return users, db.WithContext(ctx).
  784. Where("type = ?", UserTypeIndividual).
  785. Limit(pageSize).Offset((page - 1) * pageSize).
  786. Order("id ASC").
  787. Find(&users).
  788. Error
  789. }
  790. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  791. /*
  792. Equivalent SQL for PostgreSQL:
  793. SELECT * FROM "user"
  794. LEFT JOIN follow ON follow.user_id = "user".id
  795. WHERE follow.follow_id = @userID
  796. ORDER BY follow.id DESC
  797. LIMIT @limit OFFSET @offset
  798. */
  799. users := make([]*User, 0, pageSize)
  800. return users, db.WithContext(ctx).
  801. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  802. Where("follow.follow_id = ?", userID).
  803. Limit(pageSize).Offset((page - 1) * pageSize).
  804. Order("follow.id DESC").
  805. Find(&users).
  806. Error
  807. }
  808. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  809. /*
  810. Equivalent SQL for PostgreSQL:
  811. SELECT * FROM "user"
  812. LEFT JOIN follow ON follow.user_id = "user".id
  813. WHERE follow.user_id = @userID
  814. ORDER BY follow.id DESC
  815. LIMIT @limit OFFSET @offset
  816. */
  817. users := make([]*User, 0, pageSize)
  818. return users, db.WithContext(ctx).
  819. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  820. Where("follow.user_id = ?", userID).
  821. Limit(pageSize).Offset((page - 1) * pageSize).
  822. Order("follow.id DESC").
  823. Find(&users).
  824. Error
  825. }
  826. func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  827. if keyword == "" {
  828. return []*User{}, 0, nil
  829. }
  830. keyword = "%" + strings.ToLower(keyword) + "%"
  831. tx := db.WithContext(ctx).
  832. Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
  833. var count int64
  834. err := tx.Model(&User{}).Count(&count).Error
  835. if err != nil {
  836. return nil, 0, errors.Wrap(err, "count")
  837. }
  838. users := make([]*User, 0, pageSize)
  839. return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
  840. }
  841. func (db *users) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  842. return searchUserByName(ctx, db.DB, UserTypeIndividual, keyword, page, pageSize, orderBy)
  843. }
  844. type UpdateUserOptions struct {
  845. LoginSource *int64
  846. LoginName *string
  847. Password *string
  848. // GenerateNewRands indicates whether to force generate new rands for the user.
  849. GenerateNewRands bool
  850. FullName *string
  851. Email *string
  852. Website *string
  853. Location *string
  854. Description *string
  855. MaxRepoCreation *int
  856. LastRepoVisibility *bool
  857. IsActivated *bool
  858. IsAdmin *bool
  859. AllowGitHook *bool
  860. AllowImportLocal *bool
  861. ProhibitLogin *bool
  862. Avatar *string
  863. AvatarEmail *string
  864. }
  865. func (db *users) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
  866. updates := map[string]any{
  867. "updated_unix": db.NowFunc().Unix(),
  868. }
  869. if opts.LoginSource != nil {
  870. updates["login_source"] = *opts.LoginSource
  871. }
  872. if opts.LoginName != nil {
  873. updates["login_name"] = *opts.LoginName
  874. }
  875. if opts.Password != nil {
  876. salt, err := userutil.RandomSalt()
  877. if err != nil {
  878. return errors.Wrap(err, "generate salt")
  879. }
  880. updates["salt"] = salt
  881. updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
  882. opts.GenerateNewRands = true
  883. }
  884. if opts.GenerateNewRands {
  885. rands, err := userutil.RandomSalt()
  886. if err != nil {
  887. return errors.Wrap(err, "generate rands")
  888. }
  889. updates["rands"] = rands
  890. }
  891. if opts.FullName != nil {
  892. updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
  893. }
  894. if opts.Email != nil {
  895. _, err := db.GetByEmail(ctx, *opts.Email)
  896. if err == nil {
  897. return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
  898. } else if !IsErrUserNotExist(err) {
  899. return errors.Wrap(err, "check email")
  900. }
  901. updates["email"] = *opts.Email
  902. }
  903. if opts.Website != nil {
  904. updates["website"] = strutil.Truncate(*opts.Website, 255)
  905. }
  906. if opts.Location != nil {
  907. updates["location"] = strutil.Truncate(*opts.Location, 255)
  908. }
  909. if opts.Description != nil {
  910. updates["description"] = strutil.Truncate(*opts.Description, 255)
  911. }
  912. if opts.MaxRepoCreation != nil {
  913. if *opts.MaxRepoCreation < -1 {
  914. *opts.MaxRepoCreation = -1
  915. }
  916. updates["max_repo_creation"] = *opts.MaxRepoCreation
  917. }
  918. if opts.LastRepoVisibility != nil {
  919. updates["last_repo_visibility"] = *opts.LastRepoVisibility
  920. }
  921. if opts.IsActivated != nil {
  922. updates["is_active"] = *opts.IsActivated
  923. }
  924. if opts.IsAdmin != nil {
  925. updates["is_admin"] = *opts.IsAdmin
  926. }
  927. if opts.AllowGitHook != nil {
  928. updates["allow_git_hook"] = *opts.AllowGitHook
  929. }
  930. if opts.AllowImportLocal != nil {
  931. updates["allow_import_local"] = *opts.AllowImportLocal
  932. }
  933. if opts.ProhibitLogin != nil {
  934. updates["prohibit_login"] = *opts.ProhibitLogin
  935. }
  936. if opts.Avatar != nil {
  937. updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
  938. }
  939. if opts.AvatarEmail != nil {
  940. updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
  941. }
  942. return db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
  943. }
  944. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  945. err := userutil.SaveAvatar(userID, avatar)
  946. if err != nil {
  947. return errors.Wrap(err, "save avatar")
  948. }
  949. return db.WithContext(ctx).
  950. Model(&User{}).
  951. Where("id = ?", userID).
  952. Updates(map[string]any{
  953. "use_custom_avatar": true,
  954. "updated_unix": db.NowFunc().Unix(),
  955. }).
  956. Error
  957. }
  958. func (db *users) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
  959. email = strings.ToLower(strings.TrimSpace(email))
  960. _, err := db.GetByEmail(ctx, email)
  961. if err == nil {
  962. return ErrEmailAlreadyUsed{
  963. args: errutil.Args{
  964. "email": email,
  965. },
  966. }
  967. } else if !IsErrUserNotExist(err) {
  968. return errors.Wrap(err, "check user by email")
  969. }
  970. return db.WithContext(ctx).Create(
  971. &EmailAddress{
  972. UserID: userID,
  973. Email: email,
  974. IsActivated: isActivated,
  975. },
  976. ).Error
  977. }
  978. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  979. type ErrEmailNotExist struct {
  980. args errutil.Args
  981. }
  982. // IsErrEmailAddressNotExist returns true if the underlying error has the type
  983. // ErrEmailNotExist.
  984. func IsErrEmailAddressNotExist(err error) bool {
  985. _, ok := errors.Cause(err).(ErrEmailNotExist)
  986. return ok
  987. }
  988. func (err ErrEmailNotExist) Error() string {
  989. return fmt.Sprintf("email address does not exist: %v", err.args)
  990. }
  991. func (ErrEmailNotExist) NotFound() bool {
  992. return true
  993. }
  994. func (db *users) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
  995. conds := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
  996. if needsActivated {
  997. conds.Where("is_activated = ?", true)
  998. }
  999. emailAddress := new(EmailAddress)
  1000. err := conds.First(emailAddress).Error
  1001. if err != nil {
  1002. if errors.Is(err, gorm.ErrRecordNotFound) {
  1003. return nil, ErrEmailNotExist{
  1004. args: errutil.Args{
  1005. "email": email,
  1006. },
  1007. }
  1008. }
  1009. return nil, err
  1010. }
  1011. return emailAddress, nil
  1012. }
  1013. func (db *users) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
  1014. user, err := db.GetByID(ctx, userID)
  1015. if err != nil {
  1016. return nil, errors.Wrap(err, "get user")
  1017. }
  1018. var emails []*EmailAddress
  1019. err = db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
  1020. if err != nil {
  1021. return nil, errors.Wrap(err, "list emails")
  1022. }
  1023. isPrimaryFound := false
  1024. for _, email := range emails {
  1025. if email.Email == user.Email {
  1026. isPrimaryFound = true
  1027. email.IsPrimary = true
  1028. break
  1029. }
  1030. }
  1031. // We always want the primary email address displayed, even if it's not in the
  1032. // email_address table yet.
  1033. if !isPrimaryFound {
  1034. emails = append(emails, &EmailAddress{
  1035. Email: user.Email,
  1036. IsActivated: user.IsActive,
  1037. IsPrimary: true,
  1038. })
  1039. }
  1040. return emails, nil
  1041. }
  1042. func (db *users) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
  1043. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1044. err := db.WithContext(ctx).
  1045. Model(&EmailAddress{}).
  1046. Where("uid = ? AND email = ?", userID, email).
  1047. Update("is_activated", true).
  1048. Error
  1049. if err != nil {
  1050. return errors.Wrap(err, "mark email activated")
  1051. }
  1052. return NewUsersStore(tx).Update(ctx, userID, UpdateUserOptions{GenerateNewRands: true})
  1053. })
  1054. }
  1055. type ErrEmailNotVerified struct {
  1056. args errutil.Args
  1057. }
  1058. // IsErrEmailNotVerified returns true if the underlying error has the type
  1059. // ErrEmailNotVerified.
  1060. func IsErrEmailNotVerified(err error) bool {
  1061. _, ok := errors.Cause(err).(ErrEmailNotVerified)
  1062. return ok
  1063. }
  1064. func (err ErrEmailNotVerified) Error() string {
  1065. return fmt.Sprintf("email has not been verified: %v", err.args)
  1066. }
  1067. func (db *users) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
  1068. var emailAddress EmailAddress
  1069. err := db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
  1070. if err != nil {
  1071. if errors.Is(err, gorm.ErrRecordNotFound) {
  1072. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1073. }
  1074. return errors.Wrap(err, "get email address")
  1075. }
  1076. if !emailAddress.IsActivated {
  1077. return ErrEmailNotVerified{args: errutil.Args{"email": email}}
  1078. }
  1079. user, err := db.GetByID(ctx, userID)
  1080. if err != nil {
  1081. return errors.Wrap(err, "get user")
  1082. }
  1083. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1084. // Make sure the former primary email doesn't disappear.
  1085. err = tx.FirstOrCreate(
  1086. &EmailAddress{
  1087. UserID: user.ID,
  1088. Email: user.Email,
  1089. IsActivated: user.IsActive,
  1090. },
  1091. &EmailAddress{
  1092. UserID: user.ID,
  1093. Email: user.Email,
  1094. },
  1095. ).Error
  1096. if err != nil {
  1097. return errors.Wrap(err, "upsert former primary email address")
  1098. }
  1099. return tx.Model(&User{}).
  1100. Where("id = ?", user.ID).
  1101. Updates(map[string]any{
  1102. "email": email,
  1103. "updated_unix": tx.NowFunc().Unix(),
  1104. },
  1105. ).Error
  1106. })
  1107. }
  1108. func (db *users) DeleteEmail(ctx context.Context, userID int64, email string) error {
  1109. return db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).Delete(&EmailAddress{}).Error
  1110. }
  1111. // UserType indicates the type of the user account.
  1112. type UserType int
  1113. const (
  1114. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  1115. UserTypeOrganization
  1116. )
  1117. // User represents the object of an individual or an organization.
  1118. type User struct {
  1119. ID int64 `gorm:"primaryKey"`
  1120. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  1121. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  1122. FullName string
  1123. // Email is the primary email address (to be used for communication)
  1124. Email string `xorm:"NOT NULL" gorm:"not null"`
  1125. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  1126. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1127. LoginName string
  1128. Type UserType
  1129. Location string
  1130. Website string
  1131. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1132. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1133. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  1134. CreatedUnix int64
  1135. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  1136. UpdatedUnix int64
  1137. // Remember visibility choice for convenience, true for private
  1138. LastRepoVisibility bool
  1139. // Maximum repository creation limit, -1 means use global default
  1140. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  1141. // Permissions
  1142. IsActive bool // Activate primary email
  1143. IsAdmin bool
  1144. AllowGitHook bool
  1145. AllowImportLocal bool // Allow migrate repository by local path
  1146. ProhibitLogin bool
  1147. // Avatar
  1148. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  1149. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  1150. UseCustomAvatar bool
  1151. // Counters
  1152. NumFollowers int
  1153. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1154. NumStars int
  1155. NumRepos int
  1156. // For organization
  1157. Description string
  1158. NumTeams int
  1159. NumMembers int
  1160. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  1161. }
  1162. // BeforeCreate implements the GORM create hook.
  1163. func (u *User) BeforeCreate(tx *gorm.DB) error {
  1164. if u.CreatedUnix == 0 {
  1165. u.CreatedUnix = tx.NowFunc().Unix()
  1166. u.UpdatedUnix = u.CreatedUnix
  1167. }
  1168. return nil
  1169. }
  1170. // AfterFind implements the GORM query hook.
  1171. func (u *User) AfterFind(_ *gorm.DB) error {
  1172. u.FullName = markup.Sanitize(u.FullName)
  1173. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  1174. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  1175. return nil
  1176. }
  1177. // IsLocal returns true if the user is created as local account.
  1178. func (u *User) IsLocal() bool {
  1179. return u.LoginSource <= 0
  1180. }
  1181. // IsOrganization returns true if the user is an organization.
  1182. func (u *User) IsOrganization() bool {
  1183. return u.Type == UserTypeOrganization
  1184. }
  1185. // APIFormat returns the API format of a user.
  1186. func (u *User) APIFormat() *api.User {
  1187. return &api.User{
  1188. ID: u.ID,
  1189. UserName: u.Name,
  1190. Login: u.Name,
  1191. FullName: u.FullName,
  1192. Email: u.Email,
  1193. AvatarUrl: u.AvatarURL(),
  1194. }
  1195. }
  1196. // maxNumRepos returns the maximum number of repositories that the user can have
  1197. // direct ownership.
  1198. func (u *User) maxNumRepos() int {
  1199. if u.MaxRepoCreation <= -1 {
  1200. return conf.Repository.MaxCreationLimit
  1201. }
  1202. return u.MaxRepoCreation
  1203. }
  1204. // canCreateRepo returns true if the user can create a repository.
  1205. func (u *User) canCreateRepo() bool {
  1206. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1207. }
  1208. // CanCreateOrganization returns true if user can create organizations.
  1209. func (u *User) CanCreateOrganization() bool {
  1210. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  1211. }
  1212. // CanEditGitHook returns true if user can edit Git hooks.
  1213. func (u *User) CanEditGitHook() bool {
  1214. return u.IsAdmin || u.AllowGitHook
  1215. }
  1216. // CanImportLocal returns true if user can migrate repositories by local path.
  1217. func (u *User) CanImportLocal() bool {
  1218. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1219. }
  1220. // DisplayName returns the full name of the user if it's not empty, returns the
  1221. // username otherwise.
  1222. func (u *User) DisplayName() string {
  1223. if len(u.FullName) > 0 {
  1224. return u.FullName
  1225. }
  1226. return u.Name
  1227. }
  1228. // HomeURLPath returns the URL path to the user or organization home page.
  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) HomeURLPath() string {
  1234. return conf.Server.Subpath + "/" + u.Name
  1235. }
  1236. // HTMLURL returns the full URL to the user or organization home page.
  1237. //
  1238. // TODO(unknwon): This is also used in templates, which should be fixed by
  1239. // having a dedicated type `template.User` and move this to the "userutil"
  1240. // package.
  1241. func (u *User) HTMLURL() string {
  1242. return conf.Server.ExternalURL + u.Name
  1243. }
  1244. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1245. // user enables Gravatar-like service, then an external URL will be returned.
  1246. //
  1247. // TODO(unknwon): This is also used in templates, which should be fixed by
  1248. // having a dedicated type `template.User` and move this to the "userutil"
  1249. // package.
  1250. func (u *User) AvatarURLPath() string {
  1251. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1252. if u.ID <= 0 {
  1253. return defaultURLPath
  1254. }
  1255. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1256. switch {
  1257. case u.UseCustomAvatar:
  1258. if !hasCustomAvatar {
  1259. return defaultURLPath
  1260. }
  1261. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1262. case conf.Picture.DisableGravatar:
  1263. if !hasCustomAvatar {
  1264. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  1265. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1266. }
  1267. }
  1268. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1269. }
  1270. return tool.AvatarLink(u.AvatarEmail)
  1271. }
  1272. // AvatarURL returns the full URL to the user or organization avatar. If the
  1273. // user enables Gravatar-like service, then an external URL will be returned.
  1274. //
  1275. // TODO(unknwon): This is also used in templates, which should be fixed by
  1276. // having a dedicated type `template.User` and move this to the "userutil"
  1277. // package.
  1278. func (u *User) AvatarURL() string {
  1279. link := u.AvatarURLPath()
  1280. if link[0] == '/' && link[1] != '/' {
  1281. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1282. }
  1283. return link
  1284. }
  1285. // IsFollowing returns true if the user is following the given user.
  1286. //
  1287. // TODO(unknwon): This is also used in templates, which should be fixed by
  1288. // having a dedicated type `template.User`.
  1289. func (u *User) IsFollowing(followID int64) bool {
  1290. return Users.IsFollowing(context.TODO(), u.ID, followID)
  1291. }
  1292. // IsUserOrgOwner returns true if the user is an owner of the organization.
  1293. //
  1294. // TODO(unknwon): This is also used in templates, which should be fixed by
  1295. // having a dedicated type `template.User`.
  1296. func (u *User) IsUserOrgOwner(orgID int64) bool {
  1297. return Organizations.IsOwnedBy(context.TODO(), orgID, u.ID)
  1298. }
  1299. // IsPublicMember returns true if the user has public membership of the given
  1300. // organization.
  1301. //
  1302. // TODO(unknwon): This is also used in templates, which should be fixed by
  1303. // having a dedicated type `template.User`.
  1304. func (u *User) IsPublicMember(orgID int64) bool {
  1305. _, public := Organizations.HasMember(context.TODO(), orgID, u.ID)
  1306. return public
  1307. }
  1308. // GetOrganizationCount returns the count of organization membership that the
  1309. // user has.
  1310. //
  1311. // TODO(unknwon): This is also used in templates, which should be fixed by
  1312. // having a dedicated type `template.User`.
  1313. func (u *User) GetOrganizationCount() (int64, error) {
  1314. return Organizations.CountByUser(context.TODO(), u.ID)
  1315. }
  1316. // ShortName truncates and returns the username at most in given length.
  1317. //
  1318. // TODO(unknwon): This is also used in templates, which should be fixed by
  1319. // having a dedicated type `template.User`.
  1320. func (u *User) ShortName(length int) string {
  1321. return strutil.Ellipsis(u.Name, length)
  1322. }
  1323. // NewGhostUser creates and returns a fake user for people who has deleted their
  1324. // accounts.
  1325. //
  1326. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1327. // translate the text to local language.
  1328. func NewGhostUser() *User {
  1329. return &User{
  1330. ID: -1,
  1331. Name: "Ghost",
  1332. LowerName: "ghost",
  1333. }
  1334. }
  1335. var (
  1336. reservedUsernames = map[string]struct{}{
  1337. "-": {},
  1338. "explore": {},
  1339. "create": {},
  1340. "assets": {},
  1341. "css": {},
  1342. "img": {},
  1343. "js": {},
  1344. "less": {},
  1345. "plugins": {},
  1346. "debug": {},
  1347. "raw": {},
  1348. "install": {},
  1349. "api": {},
  1350. "avatar": {},
  1351. "user": {},
  1352. "org": {},
  1353. "help": {},
  1354. "stars": {},
  1355. "issues": {},
  1356. "pulls": {},
  1357. "commits": {},
  1358. "repo": {},
  1359. "template": {},
  1360. "admin": {},
  1361. "new": {},
  1362. ".": {},
  1363. "..": {},
  1364. }
  1365. reservedUsernamePatterns = []string{"*.keys"}
  1366. )
  1367. type ErrNameNotAllowed struct {
  1368. args errutil.Args
  1369. }
  1370. // IsErrNameNotAllowed returns true if the underlying error has the type
  1371. // ErrNameNotAllowed.
  1372. func IsErrNameNotAllowed(err error) bool {
  1373. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1374. return ok
  1375. }
  1376. func (err ErrNameNotAllowed) Value() string {
  1377. val, ok := err.args["name"].(string)
  1378. if ok {
  1379. return val
  1380. }
  1381. val, ok = err.args["pattern"].(string)
  1382. if ok {
  1383. return val
  1384. }
  1385. return "<value not found>"
  1386. }
  1387. func (err ErrNameNotAllowed) Error() string {
  1388. return fmt.Sprintf("name is not allowed: %v", err.args)
  1389. }
  1390. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1391. // allowed based on given reserved names and patterns. Names are exact match,
  1392. // patterns can be prefix or suffix match with the wildcard ("*").
  1393. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1394. name = strings.TrimSpace(strings.ToLower(name))
  1395. if utf8.RuneCountInString(name) == 0 {
  1396. return ErrNameNotAllowed{
  1397. args: errutil.Args{
  1398. "reason": "empty name",
  1399. },
  1400. }
  1401. }
  1402. if _, ok := names[name]; ok {
  1403. return ErrNameNotAllowed{
  1404. args: errutil.Args{
  1405. "reason": "reserved",
  1406. "name": name,
  1407. },
  1408. }
  1409. }
  1410. for _, pattern := range patterns {
  1411. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1412. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1413. return ErrNameNotAllowed{
  1414. args: errutil.Args{
  1415. "reason": "reserved",
  1416. "pattern": pattern,
  1417. },
  1418. }
  1419. }
  1420. }
  1421. return nil
  1422. }
  1423. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1424. // the name is not allowed as a username.
  1425. func isUsernameAllowed(name string) error {
  1426. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1427. }
  1428. // EmailAddress is an email address of a user.
  1429. type EmailAddress struct {
  1430. ID int64 `gorm:"primaryKey"`
  1431. UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
  1432. Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
  1433. IsActivated bool `gorm:"not null;default:FALSE"`
  1434. IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
  1435. }
  1436. // Follow represents relations of users and their followers.
  1437. type Follow struct {
  1438. ID int64 `gorm:"primaryKey"`
  1439. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1440. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1441. }