users.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  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.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. "gogs.io/gogs/internal/auth"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/cryptoutil"
  22. "gogs.io/gogs/internal/dbutil"
  23. "gogs.io/gogs/internal/errutil"
  24. "gogs.io/gogs/internal/markup"
  25. "gogs.io/gogs/internal/osutil"
  26. "gogs.io/gogs/internal/repoutil"
  27. "gogs.io/gogs/internal/strutil"
  28. "gogs.io/gogs/internal/tool"
  29. "gogs.io/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. err = tx.Save(user).Error
  1006. if err != nil {
  1007. return err
  1008. }
  1009. return nil
  1010. })
  1011. }
  1012. // UseCustomAvatar uses the given avatar as the user custom avatar.
  1013. func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  1014. err := userutil.SaveAvatar(userID, avatar)
  1015. if err != nil {
  1016. return errors.Wrap(err, "save avatar")
  1017. }
  1018. return s.db.WithContext(ctx).
  1019. Model(&User{}).
  1020. Where("id = ?", userID).
  1021. Updates(map[string]any{
  1022. "use_custom_avatar": true,
  1023. "updated_unix": s.db.NowFunc().Unix(),
  1024. }).
  1025. Error
  1026. }
  1027. // AddEmail adds a new email address to given user. It returns
  1028. // ErrEmailAlreadyUsed if the email has been verified by another user.
  1029. func (s *UsersStore) addEmail(tx *gorm.DB, userID int64, email string, isActivated bool) error {
  1030. email = strings.ToLower(strings.TrimSpace(email))
  1031. _, err := s.getByEmail(tx, email)
  1032. if err == nil {
  1033. return ErrEmailAlreadyUsed{
  1034. args: errutil.Args{
  1035. "email": email,
  1036. },
  1037. }
  1038. } else if !IsErrUserNotExist(err) {
  1039. return errors.Wrap(err, "check user by email")
  1040. }
  1041. return tx.Create(
  1042. &EmailAddress{
  1043. UserID: userID,
  1044. Email: email,
  1045. IsActivated: isActivated,
  1046. },
  1047. ).Error
  1048. }
  1049. // AddEmail adds a new email address to given user. It returns
  1050. // ErrEmailAlreadyUsed if the email has been verified by another user.
  1051. func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
  1052. email = strings.ToLower(strings.TrimSpace(email))
  1053. _, err := s.GetByEmail(ctx, email)
  1054. if err == nil {
  1055. return ErrEmailAlreadyUsed{
  1056. args: errutil.Args{
  1057. "email": email,
  1058. },
  1059. }
  1060. } else if !IsErrUserNotExist(err) {
  1061. return errors.Wrap(err, "check user by email")
  1062. }
  1063. return s.db.WithContext(ctx).Create(
  1064. &EmailAddress{
  1065. UserID: userID,
  1066. Email: email,
  1067. IsActivated: isActivated,
  1068. },
  1069. ).Error
  1070. }
  1071. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  1072. type ErrEmailNotExist struct {
  1073. args errutil.Args
  1074. }
  1075. // IsErrEmailAddressNotExist returns true if the underlying error has the type
  1076. // ErrEmailNotExist.
  1077. func IsErrEmailAddressNotExist(err error) bool {
  1078. _, ok := errors.Cause(err).(ErrEmailNotExist)
  1079. return ok
  1080. }
  1081. func (err ErrEmailNotExist) Error() string {
  1082. return fmt.Sprintf("email address does not exist: %v", err.args)
  1083. }
  1084. func (ErrEmailNotExist) NotFound() bool {
  1085. return true
  1086. }
  1087. // GetEmail returns the email address of the given user. If `needsActivated` is
  1088. // true, only activated email will be returned, otherwise, it may return
  1089. // inactivated email addresses. It returns ErrEmailNotExist when no qualified
  1090. // email is not found.
  1091. func (s *UsersStore) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
  1092. tx := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
  1093. if needsActivated {
  1094. tx = tx.Where("is_activated = ?", true)
  1095. }
  1096. emailAddress := new(EmailAddress)
  1097. err := tx.First(emailAddress).Error
  1098. if err != nil {
  1099. if errors.Is(err, gorm.ErrRecordNotFound) {
  1100. return nil, ErrEmailNotExist{
  1101. args: errutil.Args{
  1102. "email": email,
  1103. },
  1104. }
  1105. }
  1106. return nil, err
  1107. }
  1108. return emailAddress, nil
  1109. }
  1110. // ListEmails returns all email addresses of the given user. It always includes
  1111. // a primary email address.
  1112. func (s *UsersStore) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
  1113. user, err := s.GetByID(ctx, userID)
  1114. if err != nil {
  1115. return nil, errors.Wrap(err, "get user")
  1116. }
  1117. var emails []*EmailAddress
  1118. err = s.db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
  1119. if err != nil {
  1120. return nil, errors.Wrap(err, "list emails")
  1121. }
  1122. var emailMap = make(map[string]*EmailAddress, 10)
  1123. for _, email := range emails {
  1124. if e, ok := emailMap[email.Email]; ok && e != nil {
  1125. continue
  1126. }
  1127. email.NotExists = false
  1128. emailMap[email.Email] = email
  1129. if email.Email == user.Email {
  1130. email.IsPrimary = true
  1131. }
  1132. if email.Email == user.PublicEmail {
  1133. email.IsPublic = true
  1134. }
  1135. if email.Email == user.LocalEmail {
  1136. email.IsActivated = true
  1137. email.IsLocal = true
  1138. }
  1139. }
  1140. // We always want the primary email address displayed, even if it's not in the
  1141. // email_address table yet.
  1142. if email, ok := emailMap[user.Email]; !ok || email == nil {
  1143. email = &EmailAddress{
  1144. Email: user.Email,
  1145. IsActivated: user.IsActive,
  1146. IsPrimary: true,
  1147. NotExists: true,
  1148. }
  1149. emailMap[email.Email] = email
  1150. emails = append(emails, email)
  1151. } else {
  1152. email.IsPrimary = true
  1153. }
  1154. if email, ok := emailMap[user.PublicEmail]; !ok || email == nil {
  1155. email = &EmailAddress{
  1156. Email: user.PublicEmail,
  1157. IsActivated: false,
  1158. IsPublic: true,
  1159. NotExists: true,
  1160. }
  1161. emailMap[email.Email] = email
  1162. emails = append(emails, email)
  1163. } else {
  1164. email.IsPublic = true
  1165. }
  1166. if email, ok := emailMap[user.LocalEmail]; !ok || email == nil {
  1167. email = &EmailAddress{
  1168. Email: user.LocalEmail,
  1169. IsActivated: true,
  1170. IsLocal: true,
  1171. NotExists: false,
  1172. }
  1173. emailMap[user.LocalEmail] = email
  1174. emails = append(emails, email)
  1175. } else {
  1176. email.IsActivated = true
  1177. email.IsLocal = true
  1178. email.NotExists = false
  1179. }
  1180. return emails, nil
  1181. }
  1182. // MarkEmailActivated marks the email address of the given user as activated,
  1183. // and new rands are generated for the user.
  1184. func (s *UsersStore) markEmailActivated(tx *gorm.DB, userID int64, email string) error {
  1185. err := tx.
  1186. Model(&EmailAddress{}).
  1187. Where("uid = ? AND email = ?", userID, email).
  1188. Update("is_activated", true).
  1189. Error
  1190. if err != nil {
  1191. return errors.Wrap(err, "mark email activated")
  1192. }
  1193. return nil
  1194. }
  1195. // MarkEmailActivated marks the email address of the given user as activated,
  1196. // and new rands are generated for the user.
  1197. func (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
  1198. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1199. err := s.db.WithContext(ctx).
  1200. Model(&EmailAddress{}).
  1201. Where("uid = ? AND email = ?", userID, email).
  1202. Update("is_activated", true).
  1203. Error
  1204. if err != nil {
  1205. return errors.Wrap(err, "mark email activated")
  1206. }
  1207. return newUsersStore(tx).Update(ctx, userID, UpdateUserOptions{GenerateNewRands: true})
  1208. })
  1209. }
  1210. type ErrEmailNotVerified struct {
  1211. args errutil.Args
  1212. }
  1213. // IsErrEmailNotVerified returns true if the underlying error has the type
  1214. // ErrEmailNotVerified.
  1215. func IsErrEmailNotVerified(err error) bool {
  1216. _, ok := errors.Cause(err).(ErrEmailNotVerified)
  1217. return ok
  1218. }
  1219. func (err ErrEmailNotVerified) Error() string {
  1220. return fmt.Sprintf("email has not been verified: %v", err.args)
  1221. }
  1222. // MarkEmailPrimary marks the email address of the given user as primary. It
  1223. // returns ErrEmailNotExist when the email is not found for the user, and
  1224. // ErrEmailNotActivated when the email is not activated.
  1225. func (s *UsersStore) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
  1226. var emailAddress EmailAddress
  1227. err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
  1228. if err != nil {
  1229. if errors.Is(err, gorm.ErrRecordNotFound) {
  1230. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1231. }
  1232. return errors.Wrap(err, "get email address")
  1233. }
  1234. if !emailAddress.IsActivated {
  1235. return ErrEmailNotVerified{args: errutil.Args{"email": email}}
  1236. }
  1237. user, err := s.GetByID(ctx, userID)
  1238. if err != nil {
  1239. return errors.Wrap(err, "get user")
  1240. }
  1241. if email == user.LocalEmail {
  1242. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1243. }
  1244. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1245. err = tx.FirstOrCreate(&EmailAddress{
  1246. UserID: user.ID,
  1247. Email: user.Email,
  1248. IsActivated: false,
  1249. }, &EmailAddress{
  1250. UserID: user.ID,
  1251. Email: user.Email,
  1252. }).Error
  1253. return tx.Model(&User{}).
  1254. Where("id = ?", user.ID).
  1255. Updates(map[string]any{
  1256. "email": email,
  1257. "updated_unix": tx.NowFunc().Unix(),
  1258. },
  1259. ).Error
  1260. })
  1261. }
  1262. func (s *UsersStore) MarkEmailPublic(ctx context.Context, userID int64, email string) error {
  1263. user, err := s.GetByID(ctx, userID)
  1264. if err != nil {
  1265. return errors.Wrap(err, "get user")
  1266. }
  1267. if email != user.LocalEmail {
  1268. var emailAddress EmailAddress
  1269. err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
  1270. if err != nil {
  1271. if errors.Is(err, gorm.ErrRecordNotFound) {
  1272. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1273. }
  1274. return errors.Wrap(err, "get email address")
  1275. }
  1276. if !emailAddress.IsActivated {
  1277. return ErrEmailNotVerified{args: errutil.Args{"email": email}}
  1278. }
  1279. }
  1280. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1281. err = tx.FirstOrCreate(&EmailAddress{
  1282. UserID: user.ID,
  1283. Email: user.PublicEmail,
  1284. IsActivated: false,
  1285. }, &EmailAddress{
  1286. UserID: user.ID,
  1287. Email: user.PublicEmail,
  1288. }).Error
  1289. if err != nil {
  1290. return err
  1291. }
  1292. return tx.Model(&User{}).
  1293. Where("id = ?", user.ID).
  1294. Updates(map[string]any{
  1295. "public_email": email,
  1296. "updated_unix": tx.NowFunc().Unix(),
  1297. },
  1298. ).Error
  1299. })
  1300. }
  1301. // DeleteEmail deletes the email address of the given user.
  1302. func (s *UsersStore) DeleteEmail(ctx context.Context, userID int64, email string) error {
  1303. return s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).Delete(&EmailAddress{}).Error
  1304. }
  1305. // DeletePublicEmail deletes the email address of the given user.
  1306. func (s *UsersStore) DeletePublicEmail(ctx context.Context, user *User) error {
  1307. if user.PublicEmail == "" {
  1308. return nil
  1309. }
  1310. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1311. if user.Email != user.LocalEmail {
  1312. err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", user.ID, user.PublicEmail).Delete(&EmailAddress{}).Error
  1313. if err != nil {
  1314. return nil
  1315. }
  1316. }
  1317. user.PublicEmail = user.LocalEmail
  1318. updates := map[string]any{
  1319. "updated_unix": s.db.NowFunc().Unix(),
  1320. "public_email": user.PublicEmail,
  1321. }
  1322. return tx.Model(&User{}).Where("id = ?", user.ID).Updates(updates).Error
  1323. })
  1324. }
  1325. // UserType indicates the type of the user account.
  1326. type UserType int
  1327. const (
  1328. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  1329. UserTypeOrganization
  1330. )
  1331. // User represents the object of an individual or an organization.
  1332. type User struct {
  1333. ID int64 `gorm:"primaryKey"`
  1334. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  1335. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  1336. FullName string
  1337. // Email is the primary email address (to be used for communication)
  1338. Email string `xorm:"NOT NULL" gorm:"not null"`
  1339. // PublicEmail is the public email address
  1340. PublicEmail string `xorm:"NOT NULL" gorm:"not null"`
  1341. // LocalEmail is the fake email
  1342. LocalEmail string `xorm:"NOT NULL" gorm:"not null"`
  1343. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  1344. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1345. LoginName string
  1346. Type UserType
  1347. Location string
  1348. Website string
  1349. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1350. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1351. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  1352. CreatedUnix int64
  1353. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  1354. UpdatedUnix int64
  1355. // Remember visibility choice for convenience, true for private
  1356. LastRepoVisibility bool
  1357. // Maximum repository creation limit, -1 means use global default
  1358. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  1359. // Permissions
  1360. IsActive bool // Activate primary email
  1361. IsAdmin bool
  1362. AllowGitHook bool
  1363. AllowImportLocal bool // Allow migrate repository by local path
  1364. ProhibitLogin bool
  1365. // Avatar
  1366. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  1367. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  1368. UseCustomAvatar bool
  1369. // Counters
  1370. NumFollowers int
  1371. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1372. NumStars int
  1373. NumRepos int
  1374. // For organization
  1375. Description string
  1376. NumTeams int
  1377. NumMembers int
  1378. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  1379. Members []*User `xorm:"-" gorm:"-" json:"-"`
  1380. }
  1381. // BeforeCreate implements the GORM create hook.
  1382. func (u *User) BeforeCreate(tx *gorm.DB) error {
  1383. if u.CreatedUnix == 0 {
  1384. u.CreatedUnix = tx.NowFunc().Unix()
  1385. u.UpdatedUnix = u.CreatedUnix
  1386. }
  1387. return nil
  1388. }
  1389. // AfterFind implements the GORM query hook.
  1390. func (u *User) AfterFind(_ *gorm.DB) error {
  1391. u.FullName = markup.Sanitize(u.FullName)
  1392. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  1393. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  1394. return nil
  1395. }
  1396. // IsLocal returns true if the user is created as local account.
  1397. func (u *User) IsLocal() bool {
  1398. return u.LoginSource <= 0
  1399. }
  1400. // IsOrganization returns true if the user is an organization.
  1401. func (u *User) IsOrganization() bool {
  1402. return u.Type == UserTypeOrganization
  1403. }
  1404. // APIFormat returns the API format of a user.
  1405. func (u *User) APIFormat() *api.User { // TODO 待检查
  1406. return &api.User{
  1407. ID: u.ID,
  1408. UserName: u.Name,
  1409. Login: u.Name,
  1410. FullName: u.FullName,
  1411. Email: u.Email,
  1412. AvatarUrl: u.AvatarURL(),
  1413. }
  1414. }
  1415. // maxNumRepos returns the maximum number of repositories that the user can have
  1416. // direct ownership.
  1417. func (u *User) maxNumRepos() int {
  1418. if !u.IsActive {
  1419. return 0
  1420. } else if u.MaxRepoCreation <= -1 {
  1421. return conf.Repository.MaxCreationLimit
  1422. }
  1423. return u.MaxRepoCreation
  1424. }
  1425. // CanCreateRepo returns true if the user can create a repository.
  1426. func (u *User) CanCreateRepo() bool {
  1427. if !u.IsActive {
  1428. return false
  1429. }
  1430. if conf.Repository.AdminNotCreationLimit && u.IsAdmin {
  1431. return true
  1432. }
  1433. if conf.Admin.DisableRegularOrgCreation && conf.Repository.OrganizationNotCreationLimit && u.IsOrganization() {
  1434. return true
  1435. }
  1436. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1437. }
  1438. // CanCreateOrganization returns true if user can create organizations.
  1439. func (u *User) CanCreateOrganization() bool {
  1440. if !u.IsActive {
  1441. return false
  1442. }
  1443. if conf.Admin.DisableRegularOrgCreation {
  1444. return u.IsAdmin
  1445. }
  1446. return true
  1447. }
  1448. // CanEditGitHook returns true if user can edit Git hooks.
  1449. func (u *User) CanEditGitHook() bool {
  1450. return u.IsAdmin || u.AllowGitHook
  1451. }
  1452. // CanImportLocal returns true if user can migrate repositories by local path.
  1453. func (u *User) CanImportLocal() bool {
  1454. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1455. }
  1456. // DisplayName returns the full name of the user if it's not empty, returns the
  1457. // username otherwise.
  1458. func (u *User) DisplayName() string {
  1459. if len(u.FullName) > 0 {
  1460. return u.FullName
  1461. }
  1462. return u.Name
  1463. }
  1464. // HomeURLPath returns the URL path to the user or organization home page.
  1465. //
  1466. // TODO(unknwon): This is also used in templates, which should be fixed by
  1467. // having a dedicated type `template.User` and move this to the "userutil"
  1468. // package.
  1469. func (u *User) HomeURLPath() string {
  1470. return conf.Server.Subpath + "/" + u.Name
  1471. }
  1472. // HTMLURL returns the full URL to the user or organization home page.
  1473. //
  1474. // TODO(unknwon): This is also used in templates, which should be fixed by
  1475. // having a dedicated type `template.User` and move this to the "userutil"
  1476. // package.
  1477. func (u *User) HTMLURL() string {
  1478. return conf.Server.ExternalURL + u.Name
  1479. }
  1480. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1481. // user enables Gravatar-like service, then an external URL will be returned.
  1482. //
  1483. // TODO(unknwon): This is also used in templates, which should be fixed by
  1484. // having a dedicated type `template.User` and move this to the "userutil"
  1485. // package.
  1486. func (u *User) AvatarURLPath() string {
  1487. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1488. if u.ID <= 0 {
  1489. return defaultURLPath
  1490. }
  1491. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1492. switch {
  1493. case u.UseCustomAvatar:
  1494. if !hasCustomAvatar {
  1495. return defaultURLPath
  1496. }
  1497. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1498. case conf.Picture.DisableGravatar:
  1499. if !hasCustomAvatar {
  1500. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.PublicEmail); err != nil {
  1501. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1502. }
  1503. }
  1504. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1505. }
  1506. return tool.AvatarLink(u.AvatarEmail)
  1507. }
  1508. // AvatarURL returns the full URL to the user or organization avatar. If the
  1509. // user enables Gravatar-like service, then an external URL will be returned.
  1510. //
  1511. // TODO(unknwon): This is also used in templates, which should be fixed by
  1512. // having a dedicated type `template.User` and move this to the "userutil"
  1513. // package.
  1514. func (u *User) AvatarURL() string {
  1515. link := u.AvatarURLPath()
  1516. if link[0] == '/' && link[1] != '/' {
  1517. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1518. }
  1519. return link
  1520. }
  1521. // IsFollowing returns true if the user is following the given user.
  1522. //
  1523. // TODO(unknwon): This is also used in templates, which should be fixed by
  1524. // having a dedicated type `template.User`.
  1525. func (u *User) IsFollowing(followID int64) bool {
  1526. return Handle.Users().IsFollowing(context.TODO(), u.ID, followID)
  1527. }
  1528. // IsUserOrgOwner returns true if the user is in the owner team of the given
  1529. // organization.
  1530. //
  1531. // TODO(unknwon): This is also used in templates, which should be fixed by
  1532. // having a dedicated type `template.User`.
  1533. func (u *User) IsUserOrgOwner(orgId int64) bool {
  1534. return IsOrganizationOwner(orgId, u.ID)
  1535. }
  1536. // IsPublicMember returns true if the user has public membership of the given
  1537. // organization.
  1538. //
  1539. // TODO(unknwon): This is also used in templates, which should be fixed by
  1540. // having a dedicated type `template.User`.
  1541. func (u *User) IsPublicMember(orgId int64) bool {
  1542. return IsPublicMembership(orgId, u.ID)
  1543. }
  1544. // GetOrganizationCount returns the count of organization membership that the
  1545. // user has.
  1546. //
  1547. // TODO(unknwon): This is also used in templates, which should be fixed by
  1548. // having a dedicated type `template.User`.
  1549. func (u *User) GetOrganizationCount() (int64, error) {
  1550. return Handle.Organizations().CountByUser(context.TODO(), u.ID)
  1551. }
  1552. // ShortName truncates and returns the username at most in given length.
  1553. //
  1554. // TODO(unknwon): This is also used in templates, which should be fixed by
  1555. // having a dedicated type `template.User`.
  1556. func (u *User) ShortName(length int) string {
  1557. return strutil.Ellipsis(u.Name, length)
  1558. }
  1559. // NewGhostUser creates and returns a fake user for people who has deleted their
  1560. // accounts.
  1561. //
  1562. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1563. // translate the text to local language.
  1564. func NewGhostUser() *User {
  1565. return &User{
  1566. ID: -1,
  1567. Name: "Ghost",
  1568. LowerName: "ghost",
  1569. }
  1570. }
  1571. var (
  1572. reservedUsernames = map[string]struct{}{
  1573. "-": {},
  1574. "explore": {},
  1575. "create": {},
  1576. "assets": {},
  1577. "css": {},
  1578. "img": {},
  1579. "js": {},
  1580. "less": {},
  1581. "plugins": {},
  1582. "debug": {},
  1583. "raw": {},
  1584. "install": {},
  1585. "api": {},
  1586. "avatar": {},
  1587. "user": {},
  1588. "org": {},
  1589. "help": {},
  1590. "stars": {},
  1591. "issues": {},
  1592. "pulls": {},
  1593. "commits": {},
  1594. "repo": {},
  1595. "template": {},
  1596. "admin": {},
  1597. "new": {},
  1598. ".": {},
  1599. "..": {},
  1600. }
  1601. reservedUsernamePatterns = []string{"*.keys"}
  1602. )
  1603. type ErrNameNotAllowed struct {
  1604. args errutil.Args
  1605. }
  1606. // IsErrNameNotAllowed returns true if the underlying error has the type
  1607. // ErrNameNotAllowed.
  1608. func IsErrNameNotAllowed(err error) bool {
  1609. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1610. return ok
  1611. }
  1612. func (err ErrNameNotAllowed) Value() string {
  1613. val, ok := err.args["name"].(string)
  1614. if ok {
  1615. return val
  1616. }
  1617. val, ok = err.args["pattern"].(string)
  1618. if ok {
  1619. return val
  1620. }
  1621. return "<value not found>"
  1622. }
  1623. func (err ErrNameNotAllowed) Error() string {
  1624. return fmt.Sprintf("name is not allowed: %v", err.args)
  1625. }
  1626. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1627. // allowed based on given reserved names and patterns. Names are exact match,
  1628. // patterns can be prefix or suffix match with the wildcard ("*").
  1629. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1630. name = strings.TrimSpace(strings.ToLower(name))
  1631. if utf8.RuneCountInString(name) == 0 {
  1632. return ErrNameNotAllowed{
  1633. args: errutil.Args{
  1634. "reason": "empty name",
  1635. },
  1636. }
  1637. }
  1638. if _, ok := names[name]; ok {
  1639. return ErrNameNotAllowed{
  1640. args: errutil.Args{
  1641. "reason": "reserved",
  1642. "name": name,
  1643. },
  1644. }
  1645. }
  1646. for _, pattern := range patterns {
  1647. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1648. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1649. return ErrNameNotAllowed{
  1650. args: errutil.Args{
  1651. "reason": "reserved",
  1652. "pattern": pattern,
  1653. },
  1654. }
  1655. }
  1656. }
  1657. return nil
  1658. }
  1659. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1660. // the name is not allowed as a username.
  1661. func isUsernameAllowed(name string) error {
  1662. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1663. }
  1664. // EmailAddress is an email address of a user.
  1665. type EmailAddress struct {
  1666. ID int64 `gorm:"primaryKey"`
  1667. UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
  1668. Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
  1669. IsActivated bool `gorm:"not null;default:FALSE"`
  1670. IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
  1671. IsPublic bool `xorm:"-" gorm:"-" json:"-"`
  1672. IsLocal bool `xorm:"-" gorm:"-" json:"-"`
  1673. NotExists bool `xorm:"-" gorm:"-" json:"-"`
  1674. }
  1675. // Follow represents relations of users and their followers.
  1676. type Follow struct {
  1677. ID int64 `gorm:"primaryKey"`
  1678. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1679. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1680. }