users.go 33 KB

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