users.go 41 KB

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