users.go 54 KB

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