users.go 32 KB

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