users.go 30 KB

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