users.go 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package database
  5. import (
  6. "context"
  7. "database/sql"
  8. "fmt"
  9. 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 := s.db.WithContext(ctx).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, s.db.WithContext(ctx).Create(user).Error
  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 && u.IsAdmin {
  1419. return -1
  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. return u.IsOrganization() || (u.IsActive && u.IsAdmin) || u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1428. }
  1429. // CanCreateOrganization returns true if user can create organizations.
  1430. func (u *User) CanCreateOrganization() bool {
  1431. //return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  1432. return u.IsAdmin // 确定只有Admin可以创建仓库
  1433. }
  1434. // CanEditGitHook returns true if user can edit Git hooks.
  1435. func (u *User) CanEditGitHook() bool {
  1436. return u.IsAdmin || u.AllowGitHook
  1437. }
  1438. // CanImportLocal returns true if user can migrate repositories by local path.
  1439. func (u *User) CanImportLocal() bool {
  1440. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1441. }
  1442. // DisplayName returns the full name of the user if it's not empty, returns the
  1443. // username otherwise.
  1444. func (u *User) DisplayName() string {
  1445. if len(u.FullName) > 0 {
  1446. return u.FullName
  1447. }
  1448. return u.Name
  1449. }
  1450. // HomeURLPath returns the URL path to the user or organization home page.
  1451. //
  1452. // TODO(unknwon): This is also used in templates, which should be fixed by
  1453. // having a dedicated type `template.User` and move this to the "userutil"
  1454. // package.
  1455. func (u *User) HomeURLPath() string {
  1456. return conf.Server.Subpath + "/" + u.Name
  1457. }
  1458. // HTMLURL returns the full URL to the user or organization home page.
  1459. //
  1460. // TODO(unknwon): This is also used in templates, which should be fixed by
  1461. // having a dedicated type `template.User` and move this to the "userutil"
  1462. // package.
  1463. func (u *User) HTMLURL() string {
  1464. return conf.Server.ExternalURL + u.Name
  1465. }
  1466. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1467. // user enables Gravatar-like service, then an external URL will be returned.
  1468. //
  1469. // TODO(unknwon): This is also used in templates, which should be fixed by
  1470. // having a dedicated type `template.User` and move this to the "userutil"
  1471. // package.
  1472. func (u *User) AvatarURLPath() string {
  1473. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1474. if u.ID <= 0 {
  1475. return defaultURLPath
  1476. }
  1477. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1478. switch {
  1479. case u.UseCustomAvatar:
  1480. if !hasCustomAvatar {
  1481. return defaultURLPath
  1482. }
  1483. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1484. case conf.Picture.DisableGravatar:
  1485. if !hasCustomAvatar {
  1486. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.PublicEmail); err != nil {
  1487. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1488. }
  1489. }
  1490. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1491. }
  1492. return tool.AvatarLink(u.AvatarEmail)
  1493. }
  1494. // AvatarURL returns the full URL to the user or organization avatar. If the
  1495. // user enables Gravatar-like service, then an external URL will be returned.
  1496. //
  1497. // TODO(unknwon): This is also used in templates, which should be fixed by
  1498. // having a dedicated type `template.User` and move this to the "userutil"
  1499. // package.
  1500. func (u *User) AvatarURL() string {
  1501. link := u.AvatarURLPath()
  1502. if link[0] == '/' && link[1] != '/' {
  1503. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1504. }
  1505. return link
  1506. }
  1507. // IsFollowing returns true if the user is following the given user.
  1508. //
  1509. // TODO(unknwon): This is also used in templates, which should be fixed by
  1510. // having a dedicated type `template.User`.
  1511. func (u *User) IsFollowing(followID int64) bool {
  1512. return Handle.Users().IsFollowing(context.TODO(), u.ID, followID)
  1513. }
  1514. // IsUserOrgOwner returns true if the user is in the owner team of the given
  1515. // organization.
  1516. //
  1517. // TODO(unknwon): This is also used in templates, which should be fixed by
  1518. // having a dedicated type `template.User`.
  1519. func (u *User) IsUserOrgOwner(orgId int64) bool {
  1520. return IsOrganizationOwner(orgId, u.ID)
  1521. }
  1522. // IsPublicMember returns true if the user has public membership of the given
  1523. // organization.
  1524. //
  1525. // TODO(unknwon): This is also used in templates, which should be fixed by
  1526. // having a dedicated type `template.User`.
  1527. func (u *User) IsPublicMember(orgId int64) bool {
  1528. return IsPublicMembership(orgId, u.ID)
  1529. }
  1530. // GetOrganizationCount returns the count of organization membership that the
  1531. // user has.
  1532. //
  1533. // TODO(unknwon): This is also used in templates, which should be fixed by
  1534. // having a dedicated type `template.User`.
  1535. func (u *User) GetOrganizationCount() (int64, error) {
  1536. return Handle.Organizations().CountByUser(context.TODO(), u.ID)
  1537. }
  1538. // ShortName truncates and returns the username at most in given length.
  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) ShortName(length int) string {
  1543. return strutil.Ellipsis(u.Name, length)
  1544. }
  1545. // NewGhostUser creates and returns a fake user for people who has deleted their
  1546. // accounts.
  1547. //
  1548. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1549. // translate the text to local language.
  1550. func NewGhostUser() *User {
  1551. return &User{
  1552. ID: -1,
  1553. Name: "Ghost",
  1554. LowerName: "ghost",
  1555. }
  1556. }
  1557. var (
  1558. reservedUsernames = map[string]struct{}{
  1559. "-": {},
  1560. "explore": {},
  1561. "create": {},
  1562. "assets": {},
  1563. "css": {},
  1564. "img": {},
  1565. "js": {},
  1566. "less": {},
  1567. "plugins": {},
  1568. "debug": {},
  1569. "raw": {},
  1570. "install": {},
  1571. "api": {},
  1572. "avatar": {},
  1573. "user": {},
  1574. "org": {},
  1575. "help": {},
  1576. "stars": {},
  1577. "issues": {},
  1578. "pulls": {},
  1579. "commits": {},
  1580. "repo": {},
  1581. "template": {},
  1582. "admin": {},
  1583. "new": {},
  1584. ".": {},
  1585. "..": {},
  1586. }
  1587. reservedUsernamePatterns = []string{"*.keys"}
  1588. )
  1589. type ErrNameNotAllowed struct {
  1590. args errutil.Args
  1591. }
  1592. // IsErrNameNotAllowed returns true if the underlying error has the type
  1593. // ErrNameNotAllowed.
  1594. func IsErrNameNotAllowed(err error) bool {
  1595. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1596. return ok
  1597. }
  1598. func (err ErrNameNotAllowed) Value() string {
  1599. val, ok := err.args["name"].(string)
  1600. if ok {
  1601. return val
  1602. }
  1603. val, ok = err.args["pattern"].(string)
  1604. if ok {
  1605. return val
  1606. }
  1607. return "<value not found>"
  1608. }
  1609. func (err ErrNameNotAllowed) Error() string {
  1610. return fmt.Sprintf("name is not allowed: %v", err.args)
  1611. }
  1612. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1613. // allowed based on given reserved names and patterns. Names are exact match,
  1614. // patterns can be prefix or suffix match with the wildcard ("*").
  1615. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1616. name = strings.TrimSpace(strings.ToLower(name))
  1617. if utf8.RuneCountInString(name) == 0 {
  1618. return ErrNameNotAllowed{
  1619. args: errutil.Args{
  1620. "reason": "empty name",
  1621. },
  1622. }
  1623. }
  1624. if _, ok := names[name]; ok {
  1625. return ErrNameNotAllowed{
  1626. args: errutil.Args{
  1627. "reason": "reserved",
  1628. "name": name,
  1629. },
  1630. }
  1631. }
  1632. for _, pattern := range patterns {
  1633. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1634. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1635. return ErrNameNotAllowed{
  1636. args: errutil.Args{
  1637. "reason": "reserved",
  1638. "pattern": pattern,
  1639. },
  1640. }
  1641. }
  1642. }
  1643. return nil
  1644. }
  1645. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1646. // the name is not allowed as a username.
  1647. func isUsernameAllowed(name string) error {
  1648. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1649. }
  1650. // EmailAddress is an email address of a user.
  1651. type EmailAddress struct {
  1652. ID int64 `gorm:"primaryKey"`
  1653. UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
  1654. Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
  1655. IsActivated bool `gorm:"not null;default:FALSE"`
  1656. IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
  1657. IsPublic bool `xorm:"-" gorm:"-" json:"-"`
  1658. IsLocal bool `xorm:"-" gorm:"-" json:"-"`
  1659. NotExists bool `xorm:"-" gorm:"-" json:"-"`
  1660. }
  1661. // Follow represents relations of users and their followers.
  1662. type Follow struct {
  1663. ID int64 `gorm:"primaryKey"`
  1664. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1665. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1666. }