users.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. "strings"
  9. "time"
  10. "github.com/go-macaron/binding"
  11. api "github.com/gogs/go-gogs-client"
  12. "github.com/pkg/errors"
  13. "gorm.io/gorm"
  14. log "unknwon.dev/clog/v2"
  15. "gogs.io/gogs/internal/auth"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/cryptoutil"
  18. "gogs.io/gogs/internal/errutil"
  19. "gogs.io/gogs/internal/osutil"
  20. "gogs.io/gogs/internal/tool"
  21. "gogs.io/gogs/internal/userutil"
  22. )
  23. // UsersStore is the persistent interface for users.
  24. //
  25. // NOTE: All methods are sorted in alphabetical order.
  26. type UsersStore interface {
  27. // Authenticate validates username and password via given login source ID. It
  28. // returns ErrUserNotExist when the user was not found.
  29. //
  30. // When the "loginSourceID" is negative, it aborts the process and returns
  31. // ErrUserNotExist if the user was not found in the database.
  32. //
  33. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  34. // if the user has different login source ID than the "loginSourceID".
  35. //
  36. // When the "loginSourceID" is positive, it tries to authenticate via given
  37. // login source and creates a new user when not yet exists in the database.
  38. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  39. // Create creates a new user and persists to database. It returns
  40. // ErrUserAlreadyExist when a user with same name already exists, or
  41. // ErrEmailAlreadyUsed if the email has been used by another user.
  42. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
  43. // GetByEmail returns the user (not organization) with given email. It ignores
  44. // records with unverified emails and returns ErrUserNotExist when not found.
  45. GetByEmail(ctx context.Context, email string) (*User, error)
  46. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  47. // found.
  48. GetByID(ctx context.Context, id int64) (*User, error)
  49. // GetByUsername returns the user with given username. It returns
  50. // ErrUserNotExist when not found.
  51. GetByUsername(ctx context.Context, username string) (*User, error)
  52. // HasForkedRepository returns true if the user has forked given repository.
  53. HasForkedRepository(ctx context.Context, userID, repoID int64) bool
  54. // ListFollowers returns a list of users that are following the given user.
  55. // Results are paginated by given page and page size, and sorted by the time of
  56. // follow in descending order.
  57. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  58. // ListFollowings returns a list of users that are followed by the given user.
  59. // Results are paginated by given page and page size, and sorted by the time of
  60. // follow in descending order.
  61. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  62. }
  63. var Users UsersStore
  64. var _ UsersStore = (*users)(nil)
  65. type users struct {
  66. *gorm.DB
  67. }
  68. // NewUsersStore returns a persistent interface for users with given database
  69. // connection.
  70. func NewUsersStore(db *gorm.DB) UsersStore {
  71. return &users{DB: db}
  72. }
  73. type ErrLoginSourceMismatch struct {
  74. args errutil.Args
  75. }
  76. func (err ErrLoginSourceMismatch) Error() string {
  77. return fmt.Sprintf("login source mismatch: %v", err.args)
  78. }
  79. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  80. login = strings.ToLower(login)
  81. query := db.WithContext(ctx)
  82. if strings.Contains(login, "@") {
  83. query = query.Where("email = ?", login)
  84. } else {
  85. query = query.Where("lower_name = ?", login)
  86. }
  87. user := new(User)
  88. err := query.First(user).Error
  89. if err != nil && err != gorm.ErrRecordNotFound {
  90. return nil, errors.Wrap(err, "get user")
  91. }
  92. var authSourceID int64 // The login source ID will be used to authenticate the user
  93. createNewUser := false // Whether to create a new user after successful authentication
  94. // User found in the database
  95. if err == nil {
  96. // Note: This check is unnecessary but to reduce user confusion at login page
  97. // and make it more consistent from user's perspective.
  98. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  99. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  100. }
  101. // Validate password hash fetched from database for local accounts.
  102. if user.IsLocal() {
  103. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  104. return user, nil
  105. }
  106. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login, "userID": user.ID}}
  107. }
  108. authSourceID = user.LoginSource
  109. } else {
  110. // Non-local login source is always greater than 0.
  111. if loginSourceID <= 0 {
  112. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login}}
  113. }
  114. authSourceID = loginSourceID
  115. createNewUser = true
  116. }
  117. source, err := LoginSources.GetByID(ctx, authSourceID)
  118. if err != nil {
  119. return nil, errors.Wrap(err, "get login source")
  120. }
  121. if !source.IsActived {
  122. return nil, errors.Errorf("login source %d is not activated", source.ID)
  123. }
  124. extAccount, err := source.Provider.Authenticate(login, password)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if !createNewUser {
  129. return user, nil
  130. }
  131. // Validate username make sure it satisfies requirement.
  132. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  133. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  134. }
  135. return db.Create(ctx, extAccount.Name, extAccount.Email,
  136. CreateUserOptions{
  137. FullName: extAccount.FullName,
  138. LoginSource: authSourceID,
  139. LoginName: extAccount.Login,
  140. Location: extAccount.Location,
  141. Website: extAccount.Website,
  142. Activated: true,
  143. Admin: extAccount.Admin,
  144. },
  145. )
  146. }
  147. type CreateUserOptions struct {
  148. FullName string
  149. Password string
  150. LoginSource int64
  151. LoginName string
  152. Location string
  153. Website string
  154. Activated bool
  155. Admin bool
  156. }
  157. type ErrUserAlreadyExist struct {
  158. args errutil.Args
  159. }
  160. func IsErrUserAlreadyExist(err error) bool {
  161. _, ok := err.(ErrUserAlreadyExist)
  162. return ok
  163. }
  164. func (err ErrUserAlreadyExist) Error() string {
  165. return fmt.Sprintf("user already exists: %v", err.args)
  166. }
  167. type ErrEmailAlreadyUsed struct {
  168. args errutil.Args
  169. }
  170. func IsErrEmailAlreadyUsed(err error) bool {
  171. _, ok := err.(ErrEmailAlreadyUsed)
  172. return ok
  173. }
  174. func (err ErrEmailAlreadyUsed) Email() string {
  175. email, ok := err.args["email"].(string)
  176. if ok {
  177. return email
  178. }
  179. return "<email not found>"
  180. }
  181. func (err ErrEmailAlreadyUsed) Error() string {
  182. return fmt.Sprintf("email has been used: %v", err.args)
  183. }
  184. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  185. err := isUsernameAllowed(username)
  186. if err != nil {
  187. return nil, err
  188. }
  189. _, err = db.GetByUsername(ctx, username)
  190. if err == nil {
  191. return nil, ErrUserAlreadyExist{args: errutil.Args{"name": username}}
  192. } else if !IsErrUserNotExist(err) {
  193. return nil, err
  194. }
  195. _, err = db.GetByEmail(ctx, email)
  196. if err == nil {
  197. return nil, ErrEmailAlreadyUsed{args: errutil.Args{"email": email}}
  198. } else if !IsErrUserNotExist(err) {
  199. return nil, err
  200. }
  201. user := &User{
  202. LowerName: strings.ToLower(username),
  203. Name: username,
  204. FullName: opts.FullName,
  205. Email: email,
  206. Password: opts.Password,
  207. LoginSource: opts.LoginSource,
  208. LoginName: opts.LoginName,
  209. Location: opts.Location,
  210. Website: opts.Website,
  211. MaxRepoCreation: -1,
  212. IsActive: opts.Activated,
  213. IsAdmin: opts.Admin,
  214. Avatar: cryptoutil.MD5(email),
  215. AvatarEmail: email,
  216. }
  217. user.Rands, err = GetUserSalt()
  218. if err != nil {
  219. return nil, err
  220. }
  221. user.Salt, err = GetUserSalt()
  222. if err != nil {
  223. return nil, err
  224. }
  225. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  226. return user, db.WithContext(ctx).Create(user).Error
  227. }
  228. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  229. type ErrUserNotExist struct {
  230. args errutil.Args
  231. }
  232. func IsErrUserNotExist(err error) bool {
  233. _, ok := err.(ErrUserNotExist)
  234. return ok
  235. }
  236. func (err ErrUserNotExist) Error() string {
  237. return fmt.Sprintf("user does not exist: %v", err.args)
  238. }
  239. func (ErrUserNotExist) NotFound() bool {
  240. return true
  241. }
  242. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  243. email = strings.ToLower(email)
  244. if email == "" {
  245. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  246. }
  247. // First try to find the user by primary email
  248. user := new(User)
  249. err := db.WithContext(ctx).
  250. Where("email = ? AND type = ? AND is_active = ?", email, UserTypeIndividual, true).
  251. First(user).
  252. Error
  253. if err == nil {
  254. return user, nil
  255. } else if err != gorm.ErrRecordNotFound {
  256. return nil, err
  257. }
  258. // Otherwise, check activated email addresses
  259. emailAddress := new(EmailAddress)
  260. err = db.WithContext(ctx).
  261. Where("email = ? AND is_activated = ?", email, true).
  262. First(emailAddress).
  263. Error
  264. if err != nil {
  265. if err == gorm.ErrRecordNotFound {
  266. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  267. }
  268. return nil, err
  269. }
  270. return db.GetByID(ctx, emailAddress.UID)
  271. }
  272. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  273. user := new(User)
  274. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  275. if err != nil {
  276. if err == gorm.ErrRecordNotFound {
  277. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  278. }
  279. return nil, err
  280. }
  281. return user, nil
  282. }
  283. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  284. user := new(User)
  285. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  286. if err != nil {
  287. if err == gorm.ErrRecordNotFound {
  288. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  289. }
  290. return nil, err
  291. }
  292. return user, nil
  293. }
  294. func (db *users) HasForkedRepository(ctx context.Context, userID, repoID int64) bool {
  295. var count int64
  296. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  297. return count > 0
  298. }
  299. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  300. /*
  301. Equivalent SQL for PostgreSQL:
  302. SELECT * FROM "user"
  303. LEFT JOIN follow ON follow.user_id = "user".id
  304. WHERE follow.follow_id = @userID
  305. ORDER BY follow.id DESC
  306. LIMIT @limit OFFSET @offset
  307. */
  308. users := make([]*User, 0, pageSize)
  309. tx := db.WithContext(ctx).
  310. Where("follow.follow_id = ?", userID).
  311. Limit(pageSize).Offset((page - 1) * pageSize).
  312. Order("follow.id DESC")
  313. if conf.UsePostgreSQL {
  314. tx.Joins(`LEFT JOIN follow ON follow.user_id = "user".id`)
  315. } else {
  316. tx.Joins(`LEFT JOIN follow ON follow.user_id = user.id`)
  317. }
  318. return users, tx.Find(&users).Error
  319. }
  320. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  321. /*
  322. Equivalent SQL for PostgreSQL:
  323. SELECT * FROM "user"
  324. LEFT JOIN follow ON follow.user_id = "user".id
  325. WHERE follow.user_id = @userID
  326. ORDER BY follow.id DESC
  327. LIMIT @limit OFFSET @offset
  328. */
  329. users := make([]*User, 0, pageSize)
  330. tx := db.WithContext(ctx).
  331. Where("follow.user_id = ?", userID).
  332. Limit(pageSize).Offset((page - 1) * pageSize).
  333. Order("follow.id DESC")
  334. if conf.UsePostgreSQL {
  335. tx.Joins(`LEFT JOIN follow ON follow.follow_id = "user".id`)
  336. } else {
  337. tx.Joins(`LEFT JOIN follow ON follow.follow_id = user.id`)
  338. }
  339. return users, tx.Find(&users).Error
  340. }
  341. // UserType indicates the type of the user account.
  342. type UserType int
  343. const (
  344. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  345. UserTypeOrganization
  346. )
  347. // User represents the object of an individual or an organization.
  348. type User struct {
  349. ID int64 `gorm:"primaryKey"`
  350. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  351. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  352. FullName string
  353. // Email is the primary email address (to be used for communication)
  354. Email string `xorm:"NOT NULL" gorm:"not null"`
  355. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  356. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  357. LoginName string
  358. Type UserType
  359. OwnedOrgs []*User `xorm:"-" gorm:"-" json:"-"`
  360. Orgs []*User `xorm:"-" gorm:"-" json:"-"`
  361. Repos []*Repository `xorm:"-" gorm:"-" json:"-"`
  362. Location string
  363. Website string
  364. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  365. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  366. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  367. CreatedUnix int64
  368. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  369. UpdatedUnix int64
  370. // Remember visibility choice for convenience, true for private
  371. LastRepoVisibility bool
  372. // Maximum repository creation limit, -1 means use global default
  373. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  374. // Permissions
  375. IsActive bool // Activate primary email
  376. IsAdmin bool
  377. AllowGitHook bool
  378. AllowImportLocal bool // Allow migrate repository by local path
  379. ProhibitLogin bool
  380. // Avatar
  381. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  382. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  383. UseCustomAvatar bool
  384. // Counters
  385. NumFollowers int
  386. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  387. NumStars int
  388. NumRepos int
  389. // For organization
  390. Description string
  391. NumTeams int
  392. NumMembers int
  393. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  394. Members []*User `xorm:"-" gorm:"-" json:"-"`
  395. }
  396. // BeforeCreate implements the GORM create hook.
  397. func (u *User) BeforeCreate(tx *gorm.DB) error {
  398. if u.CreatedUnix == 0 {
  399. u.CreatedUnix = tx.NowFunc().Unix()
  400. u.UpdatedUnix = u.CreatedUnix
  401. }
  402. return nil
  403. }
  404. // AfterFind implements the GORM query hook.
  405. func (u *User) AfterFind(_ *gorm.DB) error {
  406. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  407. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  408. return nil
  409. }
  410. // IsLocal returns true if user is created as local account.
  411. func (u *User) IsLocal() bool {
  412. return u.LoginSource <= 0
  413. }
  414. // APIFormat returns the API format of a user.
  415. func (u *User) APIFormat() *api.User {
  416. return &api.User{
  417. ID: u.ID,
  418. UserName: u.Name,
  419. Login: u.Name,
  420. FullName: u.FullName,
  421. Email: u.Email,
  422. AvatarUrl: u.AvatarURL(),
  423. }
  424. }
  425. // maxNumRepos returns the maximum number of repositories that the user can have
  426. // direct ownership.
  427. func (u *User) maxNumRepos() int {
  428. if u.MaxRepoCreation <= -1 {
  429. return conf.Repository.MaxCreationLimit
  430. }
  431. return u.MaxRepoCreation
  432. }
  433. // canCreateRepo returns true if the user can create a repository.
  434. func (u *User) canCreateRepo() bool {
  435. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  436. }
  437. // CanCreateOrganization returns true if user can create organizations.
  438. func (u *User) CanCreateOrganization() bool {
  439. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  440. }
  441. // CanEditGitHook returns true if user can edit Git hooks.
  442. func (u *User) CanEditGitHook() bool {
  443. return u.IsAdmin || u.AllowGitHook
  444. }
  445. // CanImportLocal returns true if user can migrate repositories by local path.
  446. func (u *User) CanImportLocal() bool {
  447. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  448. }
  449. // HomeURLPath returns the URL path to the user or organization home page.
  450. //
  451. // TODO(unknwon): This is also used in templates, which should be fixed by
  452. // having a dedicated type `template.User` and move this to the "userutil"
  453. // package.
  454. func (u *User) HomeURLPath() string {
  455. return conf.Server.Subpath + "/" + u.Name
  456. }
  457. // HTMLURL returns the full URL to the user or organization home page.
  458. //
  459. // TODO(unknwon): This is also used in templates, which should be fixed by
  460. // having a dedicated type `template.User` and move this to the "userutil"
  461. // package.
  462. func (u *User) HTMLURL() string {
  463. return conf.Server.ExternalURL + u.Name
  464. }
  465. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  466. // user enables Gravatar-like service, then an external URL will be returned.
  467. //
  468. // TODO(unknwon): This is also used in templates, which should be fixed by
  469. // having a dedicated type `template.User` and move this to the "userutil"
  470. // package.
  471. func (u *User) AvatarURLPath() string {
  472. defaultURLPath := conf.UserDefaultAvatarURLPath()
  473. if u.ID <= 0 {
  474. return defaultURLPath
  475. }
  476. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  477. switch {
  478. case u.UseCustomAvatar:
  479. if !hasCustomAvatar {
  480. return defaultURLPath
  481. }
  482. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  483. case conf.Picture.DisableGravatar:
  484. if !hasCustomAvatar {
  485. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  486. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  487. }
  488. }
  489. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  490. }
  491. return tool.AvatarLink(u.AvatarEmail)
  492. }
  493. // AvatarURL returns the full URL to the user or organization avatar. If the
  494. // user enables Gravatar-like service, then an external URL will be returned.
  495. //
  496. // TODO(unknwon): This is also used in templates, which should be fixed by
  497. // having a dedicated type `template.User` and move this to the "userutil"
  498. // package.
  499. func (u *User) AvatarURL() string {
  500. link := u.AvatarURLPath()
  501. if link[0] == '/' && link[1] != '/' {
  502. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  503. }
  504. return link
  505. }
  506. // IsFollowing returns true if the user is following the given user.
  507. //
  508. // TODO(unknwon): This is also used in templates, which should be fixed by
  509. // having a dedicated type `template.User`.
  510. func (u *User) IsFollowing(followID int64) bool {
  511. return Follows.IsFollowing(context.TODO(), u.ID, followID)
  512. }