1
0

users.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  1. package database
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "os"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "unicode/utf8"
  11. "github.com/cockroachdb/errors"
  12. api "github.com/gogs/go-gogs-client"
  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/dbutil"
  19. "gogs.io/gogs/internal/errutil"
  20. "gogs.io/gogs/internal/markup"
  21. "gogs.io/gogs/internal/osutil"
  22. "gogs.io/gogs/internal/repoutil"
  23. "gogs.io/gogs/internal/strutil"
  24. "gogs.io/gogs/internal/tool"
  25. "gogs.io/gogs/internal/userutil"
  26. )
  27. // alphaDashDotPattern is a regex to match alpha, numeric, dash, underscore and dot characters
  28. var alphaDashDotPattern = regexp.MustCompile(`[^\w-.]`)
  29. // UsersStore is the storage layer for users.
  30. type UsersStore struct {
  31. db *gorm.DB
  32. }
  33. func newUsersStore(db *gorm.DB) *UsersStore {
  34. return &UsersStore{db: db}
  35. }
  36. type ErrLoginSourceMismatch struct {
  37. args errutil.Args
  38. }
  39. // IsErrLoginSourceMismatch returns true if the underlying error has the type
  40. // ErrLoginSourceMismatch.
  41. func IsErrLoginSourceMismatch(err error) bool {
  42. return errors.As(err, &ErrLoginSourceMismatch{})
  43. }
  44. func (err ErrLoginSourceMismatch) Error() string {
  45. return fmt.Sprintf("login source mismatch: %v", err.args)
  46. }
  47. // Authenticate validates username and password via given login source ID. It
  48. // returns ErrUserNotExist when the user was not found.
  49. //
  50. // When the "loginSourceID" is negative, it aborts the process and returns
  51. // ErrUserNotExist if the user was not found in the database.
  52. //
  53. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  54. // if the user has different login source ID than the "loginSourceID".
  55. //
  56. // When the "loginSourceID" is positive, it tries to authenticate via given
  57. // login source and creates a new user when not yet exists in the database.
  58. func (s *UsersStore) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  59. login = strings.ToLower(login)
  60. query := s.db.WithContext(ctx)
  61. if strings.Contains(login, "@") {
  62. query = query.Where("email = ?", login)
  63. } else {
  64. query = query.Where("lower_name = ?", login)
  65. }
  66. user := new(User)
  67. err := query.First(user).Error
  68. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  69. return nil, errors.Wrap(err, "get user")
  70. }
  71. var authSourceID int64 // The login source ID will be used to authenticate the user
  72. createNewUser := false // Whether to create a new user after successful authentication
  73. // User found in the database
  74. if err == nil {
  75. // Note: This check is unnecessary but to reduce user confusion at login page
  76. // and make it more consistent from user's perspective.
  77. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  78. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  79. }
  80. // Validate password hash fetched from database for local accounts.
  81. if user.IsLocal() {
  82. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  83. return user, nil
  84. }
  85. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
  86. }
  87. authSourceID = user.LoginSource
  88. } else {
  89. // Non-local login source is always greater than 0.
  90. if loginSourceID <= 0 {
  91. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
  92. }
  93. authSourceID = loginSourceID
  94. createNewUser = true
  95. }
  96. source, err := newLoginSourcesStore(s.db, loadedLoginSourceFilesStore).GetByID(ctx, authSourceID)
  97. if err != nil {
  98. return nil, errors.Wrap(err, "get login source")
  99. }
  100. if !source.IsActived {
  101. return nil, errors.Errorf("login source %d is not activated", source.ID)
  102. }
  103. extAccount, err := source.Provider.Authenticate(login, password)
  104. if err != nil {
  105. return nil, err
  106. }
  107. if !createNewUser {
  108. return user, nil
  109. }
  110. // Validate username make sure it satisfies requirement.
  111. if alphaDashDotPattern.MatchString(extAccount.Name) {
  112. return nil, errors.Newf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  113. }
  114. return s.Create(ctx, extAccount.Name, extAccount.Email,
  115. CreateUserOptions{
  116. FullName: extAccount.FullName,
  117. LoginSource: authSourceID,
  118. LoginName: extAccount.Login,
  119. Location: extAccount.Location,
  120. Website: extAccount.Website,
  121. Activated: true,
  122. Admin: extAccount.Admin,
  123. },
  124. )
  125. }
  126. // ChangeUsername changes the username of the given user and updates all
  127. // references to the old username. It returns ErrNameNotAllowed if the given
  128. // name or pattern of the name is not allowed as a username, or
  129. // ErrUserAlreadyExist when another user with same name already exists.
  130. func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
  131. err := isUsernameAllowed(newUsername)
  132. if err != nil {
  133. return err
  134. }
  135. if s.IsUsernameUsed(ctx, newUsername, userID) {
  136. return ErrUserAlreadyExist{
  137. args: errutil.Args{
  138. "name": newUsername,
  139. },
  140. }
  141. }
  142. user, err := s.GetByID(ctx, userID)
  143. if err != nil {
  144. return errors.Wrap(err, "get user")
  145. }
  146. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  147. err := tx.Model(&User{}).
  148. Where("id = ?", user.ID).
  149. Updates(map[string]any{
  150. "lower_name": strings.ToLower(newUsername),
  151. "name": newUsername,
  152. "updated_unix": tx.NowFunc().Unix(),
  153. }).Error
  154. if err != nil {
  155. return errors.Wrap(err, "update user name")
  156. }
  157. // Stop here if it's just a case-change of the username
  158. if strings.EqualFold(user.Name, newUsername) {
  159. return nil
  160. }
  161. // Update all references to the user name in pull requests
  162. err = tx.Model(&PullRequest{}).
  163. Where("head_user_name = ?", user.LowerName).
  164. Update("head_user_name", strings.ToLower(newUsername)).
  165. Error
  166. if err != nil {
  167. return errors.Wrap(err, `update "pull_request.head_user_name"`)
  168. }
  169. // Delete local copies of repositories and their wikis that are owned by the user
  170. rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
  171. if err != nil {
  172. return errors.Wrap(err, "iterate repositories")
  173. }
  174. defer func() { _ = rows.Close() }()
  175. for rows.Next() {
  176. var repo struct {
  177. ID int64
  178. }
  179. err = tx.ScanRows(rows, &repo)
  180. if err != nil {
  181. return errors.Wrap(err, "scan rows")
  182. }
  183. deleteRepoLocalCopy(repo.ID)
  184. RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
  185. }
  186. if err = rows.Err(); err != nil {
  187. return errors.Wrap(err, "check rows.Err")
  188. }
  189. // Rename user directory if exists
  190. userPath := repoutil.UserPath(user.Name)
  191. if osutil.Exist(userPath) {
  192. newUserPath := repoutil.UserPath(newUsername)
  193. err = os.Rename(userPath, newUserPath)
  194. if err != nil {
  195. return errors.Wrap(err, "rename user directory")
  196. }
  197. }
  198. return nil
  199. })
  200. }
  201. // Count returns the total number of users.
  202. func (s *UsersStore) Count(ctx context.Context) int64 {
  203. var count int64
  204. s.db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
  205. return count
  206. }
  207. type CreateUserOptions struct {
  208. FullName string
  209. Password string
  210. LoginSource int64
  211. LoginName string
  212. Location string
  213. Website string
  214. Activated bool
  215. Admin bool
  216. }
  217. type ErrUserAlreadyExist struct {
  218. args errutil.Args
  219. }
  220. // IsErrUserAlreadyExist returns true if the underlying error has the type
  221. // ErrUserAlreadyExist.
  222. func IsErrUserAlreadyExist(err error) bool {
  223. return errors.As(err, &ErrUserAlreadyExist{})
  224. }
  225. func (err ErrUserAlreadyExist) Error() string {
  226. return fmt.Sprintf("user already exists: %v", err.args)
  227. }
  228. type ErrEmailAlreadyUsed struct {
  229. args errutil.Args
  230. }
  231. // IsErrEmailAlreadyUsed returns true if the underlying error has the type
  232. // ErrEmailAlreadyUsed.
  233. func IsErrEmailAlreadyUsed(err error) bool {
  234. return errors.As(err, &ErrEmailAlreadyUsed{})
  235. }
  236. func (err ErrEmailAlreadyUsed) Email() string {
  237. email, ok := err.args["email"].(string)
  238. if ok {
  239. return email
  240. }
  241. return "<email not found>"
  242. }
  243. func (err ErrEmailAlreadyUsed) Error() string {
  244. return fmt.Sprintf("email has been used: %v", err.args)
  245. }
  246. // Create creates a new user and persists to database. It returns
  247. // ErrNameNotAllowed if the given name or pattern of the name is not allowed as
  248. // a username, or ErrUserAlreadyExist when a user with same name already exists,
  249. // or ErrEmailAlreadyUsed if the email has been verified by another user.
  250. func (s *UsersStore) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  251. err := isUsernameAllowed(username)
  252. if err != nil {
  253. return nil, err
  254. }
  255. if s.IsUsernameUsed(ctx, username, 0) {
  256. return nil, ErrUserAlreadyExist{
  257. args: errutil.Args{
  258. "name": username,
  259. },
  260. }
  261. }
  262. email = strings.ToLower(strings.TrimSpace(email))
  263. _, err = s.GetByEmail(ctx, email)
  264. if err == nil {
  265. return nil, ErrEmailAlreadyUsed{
  266. args: errutil.Args{
  267. "email": email,
  268. },
  269. }
  270. } else if !IsErrUserNotExist(err) {
  271. return nil, err
  272. }
  273. user := &User{
  274. LowerName: strings.ToLower(username),
  275. Name: username,
  276. FullName: opts.FullName,
  277. Email: email,
  278. Password: opts.Password,
  279. LoginSource: opts.LoginSource,
  280. LoginName: opts.LoginName,
  281. Location: opts.Location,
  282. Website: opts.Website,
  283. MaxRepoCreation: -1,
  284. IsActive: opts.Activated,
  285. IsAdmin: opts.Admin,
  286. Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
  287. AvatarEmail: email,
  288. }
  289. user.Rands, err = userutil.RandomSalt()
  290. if err != nil {
  291. return nil, err
  292. }
  293. user.Salt, err = userutil.RandomSalt()
  294. if err != nil {
  295. return nil, err
  296. }
  297. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  298. return user, s.db.WithContext(ctx).Create(user).Error
  299. }
  300. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  301. // use look up avatar by email.
  302. func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  303. _ = os.Remove(userutil.CustomAvatarPath(userID))
  304. return s.db.WithContext(ctx).
  305. Model(&User{}).
  306. Where("id = ?", userID).
  307. Updates(map[string]any{
  308. "use_custom_avatar": false,
  309. "updated_unix": s.db.NowFunc().Unix(),
  310. }).
  311. Error
  312. }
  313. type ErrUserOwnRepos struct {
  314. args errutil.Args
  315. }
  316. // IsErrUserOwnRepos returns true if the underlying error has the type
  317. // ErrUserOwnRepos.
  318. func IsErrUserOwnRepos(err error) bool {
  319. return errors.As(err, &ErrUserOwnRepos{})
  320. }
  321. func (err ErrUserOwnRepos) Error() string {
  322. return fmt.Sprintf("user still has repository ownership: %v", err.args)
  323. }
  324. type ErrUserHasOrgs struct {
  325. args errutil.Args
  326. }
  327. // IsErrUserHasOrgs returns true if the underlying error has the type
  328. // ErrUserHasOrgs.
  329. func IsErrUserHasOrgs(err error) bool {
  330. return errors.As(err, &ErrUserHasOrgs{})
  331. }
  332. func (err ErrUserHasOrgs) Error() string {
  333. return fmt.Sprintf("user still has organization membership: %v", err.args)
  334. }
  335. // DeleteByID deletes the given user and all their resources. It returns
  336. // ErrUserOwnRepos when the user still has repository ownership, or returns
  337. // ErrUserHasOrgs when the user still has organization membership. It is more
  338. // performant to skip rewriting the "authorized_keys" file for individual
  339. // deletion in a batch operation.
  340. func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
  341. user, err := s.GetByID(ctx, userID)
  342. if err != nil {
  343. if IsErrUserNotExist(err) {
  344. return nil
  345. }
  346. return errors.Wrap(err, "get user")
  347. }
  348. // Double-check the user is not a direct owner of any repository and not a
  349. // member of any organization.
  350. var count int64
  351. err = s.db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
  352. if err != nil {
  353. return errors.Wrap(err, "count repositories")
  354. } else if count > 0 {
  355. return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
  356. }
  357. err = s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
  358. if err != nil {
  359. return errors.Wrap(err, "count organization membership")
  360. } else if count > 0 {
  361. return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
  362. }
  363. needsRewriteAuthorizedKeys := false
  364. err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  365. /*
  366. Equivalent SQL for PostgreSQL:
  367. UPDATE repository
  368. SET num_watches = num_watches - 1
  369. WHERE id IN (
  370. SELECT repo_id FROM watch WHERE user_id = @userID
  371. )
  372. */
  373. err = tx.Table("repository").
  374. Where("id IN (?)", tx.
  375. Select("repo_id").
  376. Table("watch").
  377. Where("user_id = ?", userID),
  378. ).
  379. UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
  380. Error
  381. if err != nil {
  382. return errors.Wrap(err, `decrease "repository.num_watches"`)
  383. }
  384. /*
  385. Equivalent SQL for PostgreSQL:
  386. UPDATE repository
  387. SET num_stars = num_stars - 1
  388. WHERE id IN (
  389. SELECT repo_id FROM star WHERE uid = @userID
  390. )
  391. */
  392. err = tx.Table("repository").
  393. Where("id IN (?)", tx.
  394. Select("repo_id").
  395. Table("star").
  396. Where("uid = ?", userID),
  397. ).
  398. UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
  399. Error
  400. if err != nil {
  401. return errors.Wrap(err, `decrease "repository.num_stars"`)
  402. }
  403. /*
  404. Equivalent SQL for PostgreSQL:
  405. UPDATE user
  406. SET num_followers = num_followers - 1
  407. WHERE id IN (
  408. SELECT follow_id FROM follow WHERE user_id = @userID
  409. )
  410. */
  411. err = tx.Table("user").
  412. Where("id IN (?)", tx.
  413. Select("follow_id").
  414. Table("follow").
  415. Where("user_id = ?", userID),
  416. ).
  417. UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
  418. Error
  419. if err != nil {
  420. return errors.Wrap(err, `decrease "user.num_followers"`)
  421. }
  422. /*
  423. Equivalent SQL for PostgreSQL:
  424. UPDATE user
  425. SET num_following = num_following - 1
  426. WHERE id IN (
  427. SELECT user_id FROM follow WHERE follow_id = @userID
  428. )
  429. */
  430. err = tx.Table("user").
  431. Where("id IN (?)", tx.
  432. Select("user_id").
  433. Table("follow").
  434. Where("follow_id = ?", userID),
  435. ).
  436. UpdateColumn("num_following", gorm.Expr("num_following - 1")).
  437. Error
  438. if err != nil {
  439. return errors.Wrap(err, `decrease "user.num_following"`)
  440. }
  441. if !skipRewriteAuthorizedKeys {
  442. // We need to rewrite "authorized_keys" file if the user owns any public keys.
  443. needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
  444. }
  445. err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
  446. if err != nil {
  447. return errors.Wrap(err, "clear assignees")
  448. }
  449. for _, t := range []struct {
  450. table any
  451. where string
  452. }{
  453. {&Watch{}, "user_id = @userID"},
  454. {&Star{}, "uid = @userID"},
  455. {&Follow{}, "user_id = @userID OR follow_id = @userID"},
  456. {&PublicKey{}, "owner_id = @userID"},
  457. {&AccessToken{}, "uid = @userID"},
  458. {&Collaboration{}, "user_id = @userID"},
  459. {&Access{}, "user_id = @userID"},
  460. {&Action{}, "user_id = @userID"},
  461. {&IssueUser{}, "uid = @userID"},
  462. {&EmailAddress{}, "uid = @userID"},
  463. {&User{}, "id = @userID"},
  464. } {
  465. err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
  466. if err != nil {
  467. return errors.Wrapf(err, "clean up table %T", t.table)
  468. }
  469. }
  470. return nil
  471. })
  472. if err != nil {
  473. return err
  474. }
  475. _ = os.RemoveAll(repoutil.UserPath(user.Name))
  476. _ = os.Remove(userutil.CustomAvatarPath(userID))
  477. if needsRewriteAuthorizedKeys {
  478. err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
  479. if err != nil {
  480. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  481. }
  482. }
  483. return nil
  484. }
  485. // DeleteInactivated deletes all inactivated users.
  486. //
  487. // NOTE: We do not take context.Context here because this operation in practice
  488. // could much longer than the general request timeout (e.g. one minute).
  489. func (s *UsersStore) DeleteInactivated() error {
  490. var userIDs []int64
  491. err := s.db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
  492. if err != nil {
  493. return errors.Wrap(err, "get inactivated user IDs")
  494. }
  495. for _, userID := range userIDs {
  496. err = s.DeleteByID(context.Background(), userID, true)
  497. if err != nil {
  498. // Skip users that may had set to inactivated by admins.
  499. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  500. continue
  501. }
  502. return errors.Wrapf(err, "delete user with ID %d", userID)
  503. }
  504. }
  505. err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
  506. if err != nil {
  507. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  508. }
  509. return nil
  510. }
  511. func (*UsersStore) recountFollows(tx *gorm.DB, userID, followID int64) error {
  512. /*
  513. Equivalent SQL for PostgreSQL:
  514. UPDATE "user"
  515. SET num_followers = (
  516. SELECT COUNT(*) FROM follow WHERE follow_id = @followID
  517. )
  518. WHERE id = @followID
  519. */
  520. err := tx.Model(&User{}).
  521. Where("id = ?", followID).
  522. Update(
  523. "num_followers",
  524. tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
  525. ).
  526. Error
  527. if err != nil {
  528. return errors.Wrap(err, `update "user.num_followers"`)
  529. }
  530. /*
  531. Equivalent SQL for PostgreSQL:
  532. UPDATE "user"
  533. SET num_following = (
  534. SELECT COUNT(*) FROM follow WHERE user_id = @userID
  535. )
  536. WHERE id = @userID
  537. */
  538. err = tx.Model(&User{}).
  539. Where("id = ?", userID).
  540. Update(
  541. "num_following",
  542. tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
  543. ).
  544. Error
  545. if err != nil {
  546. return errors.Wrap(err, `update "user.num_following"`)
  547. }
  548. return nil
  549. }
  550. // Follow marks the user to follow the other user.
  551. func (s *UsersStore) Follow(ctx context.Context, userID, followID int64) error {
  552. if userID == followID {
  553. return nil
  554. }
  555. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  556. f := &Follow{
  557. UserID: userID,
  558. FollowID: followID,
  559. }
  560. result := tx.FirstOrCreate(f, f)
  561. if result.Error != nil {
  562. return errors.Wrap(result.Error, "upsert")
  563. } else if result.RowsAffected <= 0 {
  564. return nil // Relation already exists
  565. }
  566. return s.recountFollows(tx, userID, followID)
  567. })
  568. }
  569. // Unfollow removes the mark the user to follow the other user.
  570. func (s *UsersStore) Unfollow(ctx context.Context, userID, followID int64) error {
  571. if userID == followID {
  572. return nil
  573. }
  574. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  575. err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
  576. if err != nil {
  577. return errors.Wrap(err, "delete")
  578. }
  579. return s.recountFollows(tx, userID, followID)
  580. })
  581. }
  582. // IsFollowing returns true if the user is following the other user.
  583. func (s *UsersStore) IsFollowing(ctx context.Context, userID, followID int64) bool {
  584. return s.db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
  585. }
  586. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  587. type ErrUserNotExist struct {
  588. args errutil.Args
  589. }
  590. // IsErrUserNotExist returns true if the underlying error has the type
  591. // ErrUserNotExist.
  592. func IsErrUserNotExist(err error) bool {
  593. _, ok := errors.Cause(err).(ErrUserNotExist)
  594. return ok
  595. }
  596. func (err ErrUserNotExist) Error() string {
  597. return fmt.Sprintf("user does not exist: %v", err.args)
  598. }
  599. func (ErrUserNotExist) NotFound() bool {
  600. return true
  601. }
  602. // GetByEmail returns the user (not organization) with given email. It ignores
  603. // records with unverified emails and returns ErrUserNotExist when not found.
  604. func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error) {
  605. if email == "" {
  606. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  607. }
  608. email = strings.ToLower(email)
  609. /*
  610. Equivalent SQL for PostgreSQL:
  611. SELECT * FROM "user"
  612. LEFT JOIN email_address ON email_address.uid = "user".id
  613. WHERE
  614. "user".type = @userType
  615. AND (
  616. "user".email = @email AND "user".is_active = TRUE
  617. OR email_address.email = @email AND email_address.is_activated = TRUE
  618. )
  619. */
  620. user := new(User)
  621. err := s.db.WithContext(ctx).
  622. Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
  623. Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
  624. Where(s.db.
  625. Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
  626. Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
  627. ).
  628. First(&user).
  629. Error
  630. if err != nil {
  631. if errors.Is(err, gorm.ErrRecordNotFound) {
  632. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  633. }
  634. return nil, err
  635. }
  636. return user, nil
  637. }
  638. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  639. // found.
  640. func (s *UsersStore) GetByID(ctx context.Context, id int64) (*User, error) {
  641. user := new(User)
  642. err := s.db.WithContext(ctx).Where("id = ?", id).First(user).Error
  643. if err != nil {
  644. if errors.Is(err, gorm.ErrRecordNotFound) {
  645. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  646. }
  647. return nil, err
  648. }
  649. return user, nil
  650. }
  651. // GetByUsername returns the user with given username. It returns
  652. // ErrUserNotExist when not found.
  653. func (s *UsersStore) GetByUsername(ctx context.Context, username string) (*User, error) {
  654. user := new(User)
  655. err := s.db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  656. if err != nil {
  657. if errors.Is(err, gorm.ErrRecordNotFound) {
  658. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  659. }
  660. return nil, err
  661. }
  662. return user, nil
  663. }
  664. // GetByKeyID returns the owner of given public key ID. It returns
  665. // ErrUserNotExist when not found.
  666. func (s *UsersStore) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
  667. user := new(User)
  668. err := s.db.WithContext(ctx).
  669. Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
  670. Where("public_key.id = ?", keyID).
  671. First(user).
  672. Error
  673. if err != nil {
  674. if errors.Is(err, gorm.ErrRecordNotFound) {
  675. return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
  676. }
  677. return nil, err
  678. }
  679. return user, nil
  680. }
  681. // GetMailableEmailsByUsernames returns a list of verified primary email
  682. // addresses (where email notifications are sent to) of users with given list of
  683. // usernames. Non-existing usernames are ignored.
  684. func (s *UsersStore) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
  685. emails := make([]string, 0, len(usernames))
  686. return emails, s.db.WithContext(ctx).
  687. Model(&User{}).
  688. Select("email").
  689. Where("lower_name IN (?) AND is_active = ?", usernames, true).
  690. Find(&emails).Error
  691. }
  692. // IsUsernameUsed returns true if the given username has been used other than
  693. // the excluded user (a non-positive ID effectively meaning check against all
  694. // users).
  695. func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserID int64) bool {
  696. if username == "" {
  697. return false
  698. }
  699. return s.db.WithContext(ctx).
  700. Select("id").
  701. Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserID).
  702. First(&User{}).
  703. Error != gorm.ErrRecordNotFound
  704. }
  705. // List returns a list of users. Results are paginated by given page and page
  706. // size, and sorted by primary key (id) in ascending order.
  707. func (s *UsersStore) List(ctx context.Context, page, pageSize int) ([]*User, error) {
  708. users := make([]*User, 0, pageSize)
  709. return users, s.db.WithContext(ctx).
  710. Where("type = ?", UserTypeIndividual).
  711. Limit(pageSize).Offset((page - 1) * pageSize).
  712. Order("id ASC").
  713. Find(&users).
  714. Error
  715. }
  716. // ListFollowers returns a list of users that are following the given user.
  717. // Results are paginated by given page and page size, and sorted by the time of
  718. // follow in descending order.
  719. func (s *UsersStore) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  720. /*
  721. Equivalent SQL for PostgreSQL:
  722. SELECT * FROM "user"
  723. LEFT JOIN follow ON follow.user_id = "user".id
  724. WHERE follow.follow_id = @userID
  725. ORDER BY follow.id DESC
  726. LIMIT @limit OFFSET @offset
  727. */
  728. users := make([]*User, 0, pageSize)
  729. return users, s.db.WithContext(ctx).
  730. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  731. Where("follow.follow_id = ?", userID).
  732. Limit(pageSize).Offset((page - 1) * pageSize).
  733. Order("follow.id DESC").
  734. Find(&users).
  735. Error
  736. }
  737. // ListFollowings returns a list of users that are followed by the given user.
  738. // Results are paginated by given page and page size, and sorted by the time of
  739. // follow in descending order.
  740. func (s *UsersStore) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  741. /*
  742. Equivalent SQL for PostgreSQL:
  743. SELECT * FROM "user"
  744. LEFT JOIN follow ON follow.user_id = "user".id
  745. WHERE follow.user_id = @userID
  746. ORDER BY follow.id DESC
  747. LIMIT @limit OFFSET @offset
  748. */
  749. users := make([]*User, 0, pageSize)
  750. return users, s.db.WithContext(ctx).
  751. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  752. Where("follow.user_id = ?", userID).
  753. Limit(pageSize).Offset((page - 1) * pageSize).
  754. Order("follow.id DESC").
  755. Find(&users).
  756. Error
  757. }
  758. func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  759. if keyword == "" {
  760. return []*User{}, 0, nil
  761. }
  762. keyword = "%" + strings.ToLower(keyword) + "%"
  763. tx := db.WithContext(ctx).
  764. Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
  765. var count int64
  766. err := tx.Model(&User{}).Count(&count).Error
  767. if err != nil {
  768. return nil, 0, errors.Wrap(err, "count")
  769. }
  770. users := make([]*User, 0, pageSize)
  771. return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
  772. }
  773. // SearchByName returns a list of users whose username or full name matches the
  774. // given keyword case-insensitively. Results are paginated by given page and
  775. // page size, and sorted by the given order (e.g. "id DESC"). A total count of
  776. // all results is also returned. If the order is not given, it's up to the
  777. // database to decide.
  778. func (s *UsersStore) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  779. return searchUserByName(ctx, s.db, UserTypeIndividual, keyword, page, pageSize, orderBy)
  780. }
  781. type UpdateUserOptions struct {
  782. LoginSource *int64
  783. LoginName *string
  784. Password *string
  785. // GenerateNewRands indicates whether to force generate new rands for the user.
  786. GenerateNewRands bool
  787. FullName *string
  788. Email *string
  789. Website *string
  790. Location *string
  791. Description *string
  792. MaxRepoCreation *int
  793. LastRepoVisibility *bool
  794. IsActivated *bool
  795. IsAdmin *bool
  796. AllowGitHook *bool
  797. AllowImportLocal *bool
  798. ProhibitLogin *bool
  799. Avatar *string
  800. AvatarEmail *string
  801. }
  802. // Update updates fields for the given user.
  803. func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
  804. updates := map[string]any{
  805. "updated_unix": s.db.NowFunc().Unix(),
  806. }
  807. if opts.LoginSource != nil {
  808. updates["login_source"] = *opts.LoginSource
  809. }
  810. if opts.LoginName != nil {
  811. updates["login_name"] = *opts.LoginName
  812. }
  813. if opts.Password != nil {
  814. salt, err := userutil.RandomSalt()
  815. if err != nil {
  816. return errors.Wrap(err, "generate salt")
  817. }
  818. updates["salt"] = salt
  819. updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
  820. opts.GenerateNewRands = true
  821. }
  822. if opts.GenerateNewRands {
  823. rands, err := userutil.RandomSalt()
  824. if err != nil {
  825. return errors.Wrap(err, "generate rands")
  826. }
  827. updates["rands"] = rands
  828. }
  829. if opts.FullName != nil {
  830. updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
  831. }
  832. if opts.Email != nil {
  833. _, err := s.GetByEmail(ctx, *opts.Email)
  834. if err == nil {
  835. return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
  836. } else if !IsErrUserNotExist(err) {
  837. return errors.Wrap(err, "check email")
  838. }
  839. updates["email"] = *opts.Email
  840. }
  841. if opts.Website != nil {
  842. updates["website"] = strutil.Truncate(*opts.Website, 255)
  843. }
  844. if opts.Location != nil {
  845. updates["location"] = strutil.Truncate(*opts.Location, 255)
  846. }
  847. if opts.Description != nil {
  848. updates["description"] = strutil.Truncate(*opts.Description, 255)
  849. }
  850. if opts.MaxRepoCreation != nil {
  851. if *opts.MaxRepoCreation < -1 {
  852. *opts.MaxRepoCreation = -1
  853. }
  854. updates["max_repo_creation"] = *opts.MaxRepoCreation
  855. }
  856. if opts.LastRepoVisibility != nil {
  857. updates["last_repo_visibility"] = *opts.LastRepoVisibility
  858. }
  859. if opts.IsActivated != nil {
  860. updates["is_active"] = *opts.IsActivated
  861. }
  862. if opts.IsAdmin != nil {
  863. updates["is_admin"] = *opts.IsAdmin
  864. }
  865. if opts.AllowGitHook != nil {
  866. updates["allow_git_hook"] = *opts.AllowGitHook
  867. }
  868. if opts.AllowImportLocal != nil {
  869. updates["allow_import_local"] = *opts.AllowImportLocal
  870. }
  871. if opts.ProhibitLogin != nil {
  872. updates["prohibit_login"] = *opts.ProhibitLogin
  873. }
  874. if opts.Avatar != nil {
  875. updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
  876. }
  877. if opts.AvatarEmail != nil {
  878. updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
  879. }
  880. return s.db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
  881. }
  882. // UseCustomAvatar uses the given avatar as the user custom avatar.
  883. func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  884. err := userutil.SaveAvatar(userID, avatar)
  885. if err != nil {
  886. return errors.Wrap(err, "save avatar")
  887. }
  888. return s.db.WithContext(ctx).
  889. Model(&User{}).
  890. Where("id = ?", userID).
  891. Updates(map[string]any{
  892. "use_custom_avatar": true,
  893. "updated_unix": s.db.NowFunc().Unix(),
  894. }).
  895. Error
  896. }
  897. // AddEmail adds a new email address to given user. It returns
  898. // ErrEmailAlreadyUsed if the email has been verified by another user.
  899. func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
  900. email = strings.ToLower(strings.TrimSpace(email))
  901. _, err := s.GetByEmail(ctx, email)
  902. if err == nil {
  903. return ErrEmailAlreadyUsed{
  904. args: errutil.Args{
  905. "email": email,
  906. },
  907. }
  908. } else if !IsErrUserNotExist(err) {
  909. return errors.Wrap(err, "check user by email")
  910. }
  911. return s.db.WithContext(ctx).Create(
  912. &EmailAddress{
  913. UserID: userID,
  914. Email: email,
  915. IsActivated: isActivated,
  916. },
  917. ).Error
  918. }
  919. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  920. type ErrEmailNotExist struct {
  921. args errutil.Args
  922. }
  923. // IsErrEmailAddressNotExist returns true if the underlying error has the type
  924. // ErrEmailNotExist.
  925. func IsErrEmailAddressNotExist(err error) bool {
  926. _, ok := errors.Cause(err).(ErrEmailNotExist)
  927. return ok
  928. }
  929. func (err ErrEmailNotExist) Error() string {
  930. return fmt.Sprintf("email address does not exist: %v", err.args)
  931. }
  932. func (ErrEmailNotExist) NotFound() bool {
  933. return true
  934. }
  935. // GetEmail returns the email address of the given user. If `needsActivated` is
  936. // true, only activated email will be returned, otherwise, it may return
  937. // inactivated email addresses. It returns ErrEmailNotExist when no qualified
  938. // email is not found.
  939. func (s *UsersStore) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
  940. tx := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
  941. if needsActivated {
  942. tx = tx.Where("is_activated = ?", true)
  943. }
  944. emailAddress := new(EmailAddress)
  945. err := tx.First(emailAddress).Error
  946. if err != nil {
  947. if errors.Is(err, gorm.ErrRecordNotFound) {
  948. return nil, ErrEmailNotExist{
  949. args: errutil.Args{
  950. "email": email,
  951. },
  952. }
  953. }
  954. return nil, err
  955. }
  956. return emailAddress, nil
  957. }
  958. // ListEmails returns all email addresses of the given user. It always includes
  959. // a primary email address.
  960. func (s *UsersStore) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
  961. user, err := s.GetByID(ctx, userID)
  962. if err != nil {
  963. return nil, errors.Wrap(err, "get user")
  964. }
  965. var emails []*EmailAddress
  966. err = s.db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
  967. if err != nil {
  968. return nil, errors.Wrap(err, "list emails")
  969. }
  970. isPrimaryFound := false
  971. for _, email := range emails {
  972. if email.Email == user.Email {
  973. isPrimaryFound = true
  974. email.IsPrimary = true
  975. break
  976. }
  977. }
  978. // We always want the primary email address displayed, even if it's not in the
  979. // email_address table yet.
  980. if !isPrimaryFound {
  981. emails = append(emails, &EmailAddress{
  982. Email: user.Email,
  983. IsActivated: user.IsActive,
  984. IsPrimary: true,
  985. })
  986. }
  987. return emails, nil
  988. }
  989. // MarkEmailActivated marks the email address of the given user as activated,
  990. // and new rands are generated for the user.
  991. func (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
  992. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  993. err := s.db.WithContext(ctx).
  994. Model(&EmailAddress{}).
  995. Where("uid = ? AND email = ?", userID, email).
  996. Update("is_activated", true).
  997. Error
  998. if err != nil {
  999. return errors.Wrap(err, "mark email activated")
  1000. }
  1001. return newUsersStore(tx).Update(ctx, userID, UpdateUserOptions{GenerateNewRands: true})
  1002. })
  1003. }
  1004. type ErrEmailNotVerified struct {
  1005. args errutil.Args
  1006. }
  1007. // IsErrEmailNotVerified returns true if the underlying error has the type
  1008. // ErrEmailNotVerified.
  1009. func IsErrEmailNotVerified(err error) bool {
  1010. _, ok := errors.Cause(err).(ErrEmailNotVerified)
  1011. return ok
  1012. }
  1013. func (err ErrEmailNotVerified) Error() string {
  1014. return fmt.Sprintf("email has not been verified: %v", err.args)
  1015. }
  1016. // MarkEmailPrimary marks the email address of the given user as primary. It
  1017. // returns ErrEmailNotExist when the email is not found for the user, and
  1018. // ErrEmailNotActivated when the email is not activated.
  1019. func (s *UsersStore) MarkEmailPrimary(ctx context.Context, userID int64, email string) error {
  1020. var emailAddress EmailAddress
  1021. err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
  1022. if err != nil {
  1023. if errors.Is(err, gorm.ErrRecordNotFound) {
  1024. return ErrEmailNotExist{args: errutil.Args{"email": email}}
  1025. }
  1026. return errors.Wrap(err, "get email address")
  1027. }
  1028. if !emailAddress.IsActivated {
  1029. return ErrEmailNotVerified{args: errutil.Args{"email": email}}
  1030. }
  1031. user, err := s.GetByID(ctx, userID)
  1032. if err != nil {
  1033. return errors.Wrap(err, "get user")
  1034. }
  1035. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  1036. // Make sure the former primary email doesn't disappear.
  1037. err = tx.FirstOrCreate(
  1038. &EmailAddress{
  1039. UserID: user.ID,
  1040. Email: user.Email,
  1041. IsActivated: user.IsActive,
  1042. },
  1043. &EmailAddress{
  1044. UserID: user.ID,
  1045. Email: user.Email,
  1046. },
  1047. ).Error
  1048. if err != nil {
  1049. return errors.Wrap(err, "upsert former primary email address")
  1050. }
  1051. return tx.Model(&User{}).
  1052. Where("id = ?", user.ID).
  1053. Updates(map[string]any{
  1054. "email": email,
  1055. "updated_unix": tx.NowFunc().Unix(),
  1056. },
  1057. ).Error
  1058. })
  1059. }
  1060. // DeleteEmail deletes the email address of the given user.
  1061. func (s *UsersStore) DeleteEmail(ctx context.Context, userID int64, email string) error {
  1062. return s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).Delete(&EmailAddress{}).Error
  1063. }
  1064. // UserType indicates the type of the user account.
  1065. type UserType int
  1066. const (
  1067. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  1068. UserTypeOrganization
  1069. )
  1070. // User represents the object of an individual or an organization.
  1071. type User struct {
  1072. ID int64 `gorm:"primaryKey"`
  1073. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  1074. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  1075. FullName string
  1076. // Email is the primary email address (to be used for communication)
  1077. Email string `xorm:"NOT NULL" gorm:"not null"`
  1078. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  1079. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1080. LoginName string
  1081. Type UserType
  1082. Location string
  1083. Website string
  1084. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1085. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  1086. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  1087. CreatedUnix int64
  1088. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  1089. UpdatedUnix int64
  1090. // Remember visibility choice for convenience, true for private
  1091. LastRepoVisibility bool
  1092. // Maximum repository creation limit, -1 means use global default
  1093. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  1094. // Permissions
  1095. IsActive bool // Activate primary email
  1096. IsAdmin bool
  1097. AllowGitHook bool
  1098. AllowImportLocal bool // Allow migrate repository by local path
  1099. ProhibitLogin bool
  1100. // Avatar
  1101. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  1102. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  1103. UseCustomAvatar bool
  1104. // Counters
  1105. NumFollowers int
  1106. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  1107. NumStars int
  1108. NumRepos int
  1109. // For organization
  1110. Description string
  1111. NumTeams int
  1112. NumMembers int
  1113. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  1114. Members []*User `xorm:"-" gorm:"-" json:"-"`
  1115. }
  1116. // BeforeCreate implements the GORM create hook.
  1117. func (u *User) BeforeCreate(tx *gorm.DB) error {
  1118. if u.CreatedUnix == 0 {
  1119. u.CreatedUnix = tx.NowFunc().Unix()
  1120. u.UpdatedUnix = u.CreatedUnix
  1121. }
  1122. return nil
  1123. }
  1124. // AfterFind implements the GORM query hook.
  1125. func (u *User) AfterFind(_ *gorm.DB) error {
  1126. u.FullName = markup.Sanitize(u.FullName)
  1127. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  1128. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  1129. return nil
  1130. }
  1131. // IsLocal returns true if the user is created as local account.
  1132. func (u *User) IsLocal() bool {
  1133. return u.LoginSource <= 0
  1134. }
  1135. // IsOrganization returns true if the user is an organization.
  1136. func (u *User) IsOrganization() bool {
  1137. return u.Type == UserTypeOrganization
  1138. }
  1139. // APIFormat returns the API format of a user.
  1140. func (u *User) APIFormat() *api.User {
  1141. return &api.User{
  1142. ID: u.ID,
  1143. UserName: u.Name,
  1144. Login: u.Name,
  1145. FullName: u.FullName,
  1146. Email: u.Email,
  1147. AvatarUrl: u.AvatarURL(),
  1148. }
  1149. }
  1150. // maxNumRepos returns the maximum number of repositories that the user can have
  1151. // direct ownership.
  1152. func (u *User) maxNumRepos() int {
  1153. if u.MaxRepoCreation <= -1 {
  1154. return conf.Repository.MaxCreationLimit
  1155. }
  1156. return u.MaxRepoCreation
  1157. }
  1158. // canCreateRepo returns true if the user can create a repository.
  1159. func (u *User) canCreateRepo() bool {
  1160. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1161. }
  1162. // CanCreateOrganization returns true if user can create organizations.
  1163. func (u *User) CanCreateOrganization() bool {
  1164. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  1165. }
  1166. // CanEditGitHook returns true if user can edit Git hooks.
  1167. func (u *User) CanEditGitHook() bool {
  1168. return u.IsAdmin || u.AllowGitHook
  1169. }
  1170. // CanImportLocal returns true if user can migrate repositories by local path.
  1171. func (u *User) CanImportLocal() bool {
  1172. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1173. }
  1174. // DisplayName returns the full name of the user if it's not empty, returns the
  1175. // username otherwise.
  1176. func (u *User) DisplayName() string {
  1177. if len(u.FullName) > 0 {
  1178. return u.FullName
  1179. }
  1180. return u.Name
  1181. }
  1182. // HomeURLPath returns the URL path to the user or organization home page.
  1183. //
  1184. // TODO(unknwon): This is also used in templates, which should be fixed by
  1185. // having a dedicated type `template.User` and move this to the "userutil"
  1186. // package.
  1187. func (u *User) HomeURLPath() string {
  1188. return conf.Server.Subpath + "/" + u.Name
  1189. }
  1190. // HTMLURL returns the full URL to the user or organization home page.
  1191. //
  1192. // TODO(unknwon): This is also used in templates, which should be fixed by
  1193. // having a dedicated type `template.User` and move this to the "userutil"
  1194. // package.
  1195. func (u *User) HTMLURL() string {
  1196. return conf.Server.ExternalURL + u.Name
  1197. }
  1198. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1199. // user enables Gravatar-like service, then an external URL will be returned.
  1200. //
  1201. // TODO(unknwon): This is also used in templates, which should be fixed by
  1202. // having a dedicated type `template.User` and move this to the "userutil"
  1203. // package.
  1204. func (u *User) AvatarURLPath() string {
  1205. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1206. if u.ID <= 0 {
  1207. return defaultURLPath
  1208. }
  1209. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1210. switch {
  1211. case u.UseCustomAvatar:
  1212. if !hasCustomAvatar {
  1213. return defaultURLPath
  1214. }
  1215. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1216. case conf.Picture.DisableGravatar:
  1217. if !hasCustomAvatar {
  1218. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  1219. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1220. }
  1221. }
  1222. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1223. }
  1224. return tool.AvatarLink(u.AvatarEmail)
  1225. }
  1226. // AvatarURL returns the full URL to the user or organization avatar. If the
  1227. // user enables Gravatar-like service, then an external URL will be returned.
  1228. //
  1229. // TODO(unknwon): This is also used in templates, which should be fixed by
  1230. // having a dedicated type `template.User` and move this to the "userutil"
  1231. // package.
  1232. func (u *User) AvatarURL() string {
  1233. link := u.AvatarURLPath()
  1234. if link[0] == '/' && link[1] != '/' {
  1235. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1236. }
  1237. return link
  1238. }
  1239. // IsFollowing returns true if the user is following the given user.
  1240. //
  1241. // TODO(unknwon): This is also used in templates, which should be fixed by
  1242. // having a dedicated type `template.User`.
  1243. func (u *User) IsFollowing(followID int64) bool {
  1244. return Handle.Users().IsFollowing(context.TODO(), u.ID, followID)
  1245. }
  1246. // IsUserOrgOwner returns true if the user is in the owner team of the given
  1247. // organization.
  1248. //
  1249. // TODO(unknwon): This is also used in templates, which should be fixed by
  1250. // having a dedicated type `template.User`.
  1251. func (u *User) IsUserOrgOwner(orgID int64) bool {
  1252. return IsOrganizationOwner(orgID, u.ID)
  1253. }
  1254. // IsPublicMember returns true if the user has public membership of the given
  1255. // organization.
  1256. //
  1257. // TODO(unknwon): This is also used in templates, which should be fixed by
  1258. // having a dedicated type `template.User`.
  1259. func (u *User) IsPublicMember(orgID int64) bool {
  1260. return IsPublicMembership(orgID, u.ID)
  1261. }
  1262. // GetOrganizationCount returns the count of organization membership that the
  1263. // user has.
  1264. //
  1265. // TODO(unknwon): This is also used in templates, which should be fixed by
  1266. // having a dedicated type `template.User`.
  1267. func (u *User) GetOrganizationCount() (int64, error) {
  1268. return Handle.Organizations().CountByUser(context.TODO(), u.ID)
  1269. }
  1270. // ShortName truncates and returns the username at most in given length.
  1271. //
  1272. // TODO(unknwon): This is also used in templates, which should be fixed by
  1273. // having a dedicated type `template.User`.
  1274. func (u *User) ShortName(length int) string {
  1275. return strutil.Ellipsis(u.Name, length)
  1276. }
  1277. // NewGhostUser creates and returns a fake user for people who has deleted their
  1278. // accounts.
  1279. //
  1280. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1281. // translate the text to local language.
  1282. func NewGhostUser() *User {
  1283. return &User{
  1284. ID: -1,
  1285. Name: "Ghost",
  1286. LowerName: "ghost",
  1287. }
  1288. }
  1289. var (
  1290. reservedUsernames = map[string]struct{}{
  1291. "-": {},
  1292. "explore": {},
  1293. "create": {},
  1294. "assets": {},
  1295. "css": {},
  1296. "img": {},
  1297. "js": {},
  1298. "less": {},
  1299. "plugins": {},
  1300. "debug": {},
  1301. "raw": {},
  1302. "install": {},
  1303. "api": {},
  1304. "avatar": {},
  1305. "user": {},
  1306. "org": {},
  1307. "help": {},
  1308. "stars": {},
  1309. "issues": {},
  1310. "pulls": {},
  1311. "commits": {},
  1312. "repo": {},
  1313. "template": {},
  1314. "admin": {},
  1315. "new": {},
  1316. ".": {},
  1317. "..": {},
  1318. }
  1319. reservedUsernamePatterns = []string{"*.keys"}
  1320. )
  1321. type ErrNameNotAllowed struct {
  1322. args errutil.Args
  1323. }
  1324. // IsErrNameNotAllowed returns true if the underlying error has the type
  1325. // ErrNameNotAllowed.
  1326. func IsErrNameNotAllowed(err error) bool {
  1327. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1328. return ok
  1329. }
  1330. func (err ErrNameNotAllowed) Value() string {
  1331. val, ok := err.args["name"].(string)
  1332. if ok {
  1333. return val
  1334. }
  1335. val, ok = err.args["pattern"].(string)
  1336. if ok {
  1337. return val
  1338. }
  1339. return "<value not found>"
  1340. }
  1341. func (err ErrNameNotAllowed) Error() string {
  1342. return fmt.Sprintf("name is not allowed: %v", err.args)
  1343. }
  1344. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1345. // allowed based on given reserved names and patterns. Names are exact match,
  1346. // patterns can be prefix or suffix match with the wildcard ("*").
  1347. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1348. name = strings.TrimSpace(strings.ToLower(name))
  1349. if utf8.RuneCountInString(name) == 0 {
  1350. return ErrNameNotAllowed{
  1351. args: errutil.Args{
  1352. "reason": "empty name",
  1353. },
  1354. }
  1355. }
  1356. if _, ok := names[name]; ok {
  1357. return ErrNameNotAllowed{
  1358. args: errutil.Args{
  1359. "reason": "reserved",
  1360. "name": name,
  1361. },
  1362. }
  1363. }
  1364. for _, pattern := range patterns {
  1365. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1366. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1367. return ErrNameNotAllowed{
  1368. args: errutil.Args{
  1369. "reason": "reserved",
  1370. "pattern": pattern,
  1371. },
  1372. }
  1373. }
  1374. }
  1375. return nil
  1376. }
  1377. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1378. // the name is not allowed as a username.
  1379. func isUsernameAllowed(name string) error {
  1380. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1381. }
  1382. // EmailAddress is an email address of a user.
  1383. type EmailAddress struct {
  1384. ID int64 `gorm:"primaryKey"`
  1385. UserID int64 `xorm:"uid INDEX NOT NULL" gorm:"column:uid;index;uniqueIndex:email_address_user_email_unique;not null"`
  1386. Email string `xorm:"UNIQUE NOT NULL" gorm:"uniqueIndex:email_address_user_email_unique;not null;size:254"`
  1387. IsActivated bool `gorm:"not null;default:FALSE"`
  1388. IsPrimary bool `xorm:"-" gorm:"-" json:"-"`
  1389. }
  1390. // Follow represents relations of users and their followers.
  1391. type Follow struct {
  1392. ID int64 `gorm:"primaryKey"`
  1393. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1394. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1395. }