users.go 39 KB

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