users.go 15 KB

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