1
0

users.go 45 KB

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