users.go 48 KB

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