users.go 28 KB

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