users.go 14 KB

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