gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package user
  5. import (
  6. "context"
  7. "fmt"
  8. "net/mail"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models/db"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/optional"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. "code.gitea.io/gitea/modules/validation"
  18. "xorm.io/builder"
  19. )
  20. // ErrEmailCharIsNotSupported e-mail address contains unsupported character
  21. type ErrEmailCharIsNotSupported struct {
  22. Email string
  23. }
  24. // IsErrEmailCharIsNotSupported checks if an error is an ErrEmailCharIsNotSupported
  25. func IsErrEmailCharIsNotSupported(err error) bool {
  26. _, ok := err.(ErrEmailCharIsNotSupported)
  27. return ok
  28. }
  29. func (err ErrEmailCharIsNotSupported) Error() string {
  30. return fmt.Sprintf("e-mail address contains unsupported character [email: %s]", err.Email)
  31. }
  32. func (err ErrEmailCharIsNotSupported) Unwrap() error {
  33. return util.ErrInvalidArgument
  34. }
  35. // ErrEmailInvalid represents an error where the email address does not comply with RFC 5322
  36. // or has a leading '-' character
  37. type ErrEmailInvalid struct {
  38. Email string
  39. }
  40. // IsErrEmailInvalid checks if an error is an ErrEmailInvalid
  41. func IsErrEmailInvalid(err error) bool {
  42. _, ok := err.(ErrEmailInvalid)
  43. return ok
  44. }
  45. func (err ErrEmailInvalid) Error() string {
  46. return fmt.Sprintf("e-mail invalid [email: %s]", err.Email)
  47. }
  48. func (err ErrEmailInvalid) Unwrap() error {
  49. return util.ErrInvalidArgument
  50. }
  51. // ErrEmailAlreadyUsed represents a "EmailAlreadyUsed" kind of error.
  52. type ErrEmailAlreadyUsed struct {
  53. Email string
  54. }
  55. // IsErrEmailAlreadyUsed checks if an error is a ErrEmailAlreadyUsed.
  56. func IsErrEmailAlreadyUsed(err error) bool {
  57. _, ok := err.(ErrEmailAlreadyUsed)
  58. return ok
  59. }
  60. func (err ErrEmailAlreadyUsed) Error() string {
  61. return fmt.Sprintf("e-mail already in use [email: %s]", err.Email)
  62. }
  63. func (err ErrEmailAlreadyUsed) Unwrap() error {
  64. return util.ErrAlreadyExist
  65. }
  66. // ErrEmailAddressNotExist email address not exist
  67. type ErrEmailAddressNotExist struct {
  68. Email string
  69. }
  70. // IsErrEmailAddressNotExist checks if an error is an ErrEmailAddressNotExist
  71. func IsErrEmailAddressNotExist(err error) bool {
  72. _, ok := err.(ErrEmailAddressNotExist)
  73. return ok
  74. }
  75. func (err ErrEmailAddressNotExist) Error() string {
  76. return fmt.Sprintf("Email address does not exist [email: %s]", err.Email)
  77. }
  78. func (err ErrEmailAddressNotExist) Unwrap() error {
  79. return util.ErrNotExist
  80. }
  81. // ErrPrimaryEmailCannotDelete primary email address cannot be deleted
  82. type ErrPrimaryEmailCannotDelete struct {
  83. Email string
  84. }
  85. // IsErrPrimaryEmailCannotDelete checks if an error is an ErrPrimaryEmailCannotDelete
  86. func IsErrPrimaryEmailCannotDelete(err error) bool {
  87. _, ok := err.(ErrPrimaryEmailCannotDelete)
  88. return ok
  89. }
  90. func (err ErrPrimaryEmailCannotDelete) Error() string {
  91. return fmt.Sprintf("Primary email address cannot be deleted [email: %s]", err.Email)
  92. }
  93. func (err ErrPrimaryEmailCannotDelete) Unwrap() error {
  94. return util.ErrInvalidArgument
  95. }
  96. // EmailAddress is the list of all email addresses of a user. It also contains the
  97. // primary email address which is saved in user table.
  98. type EmailAddress struct {
  99. ID int64 `xorm:"pk autoincr"`
  100. UID int64 `xorm:"INDEX NOT NULL"`
  101. Email string `xorm:"UNIQUE NOT NULL"`
  102. LowerEmail string `xorm:"UNIQUE NOT NULL"`
  103. IsActivated bool
  104. IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"`
  105. }
  106. func init() {
  107. db.RegisterModel(new(EmailAddress))
  108. }
  109. // BeforeInsert will be invoked by XORM before inserting a record
  110. func (email *EmailAddress) BeforeInsert() {
  111. if email.LowerEmail == "" {
  112. email.LowerEmail = strings.ToLower(email.Email)
  113. }
  114. }
  115. func InsertEmailAddress(ctx context.Context, email *EmailAddress) (*EmailAddress, error) {
  116. if err := db.Insert(ctx, email); err != nil {
  117. return nil, err
  118. }
  119. return email, nil
  120. }
  121. func UpdateEmailAddress(ctx context.Context, email *EmailAddress) error {
  122. _, err := db.GetEngine(ctx).ID(email.ID).AllCols().Update(email)
  123. return err
  124. }
  125. // ValidateEmail check if email is a valid & allowed address
  126. func ValidateEmail(email string) error {
  127. if err := validateEmailBasic(email); err != nil {
  128. return err
  129. }
  130. return validateEmailDomain(email)
  131. }
  132. // ValidateEmailForAdmin check if email is a valid address when admins manually add or edit users
  133. func ValidateEmailForAdmin(email string) error {
  134. return validateEmailBasic(email)
  135. // In this case we do not need to check the email domain
  136. }
  137. func GetEmailAddressByEmail(ctx context.Context, email string) (*EmailAddress, error) {
  138. ea := &EmailAddress{}
  139. if has, err := db.GetEngine(ctx).Where("lower_email=?", strings.ToLower(email)).Get(ea); err != nil {
  140. return nil, err
  141. } else if !has {
  142. return nil, ErrEmailAddressNotExist{email}
  143. }
  144. return ea, nil
  145. }
  146. func GetEmailAddressOfUser(ctx context.Context, email string, uid int64) (*EmailAddress, error) {
  147. ea := &EmailAddress{}
  148. if has, err := db.GetEngine(ctx).Where("lower_email=? AND uid=?", strings.ToLower(email), uid).Get(ea); err != nil {
  149. return nil, err
  150. } else if !has {
  151. return nil, ErrEmailAddressNotExist{email}
  152. }
  153. return ea, nil
  154. }
  155. func GetPrimaryEmailAddressOfUser(ctx context.Context, uid int64) (*EmailAddress, error) {
  156. ea := &EmailAddress{}
  157. if has, err := db.GetEngine(ctx).Where("uid=? AND is_primary=?", uid, true).Get(ea); err != nil {
  158. return nil, err
  159. } else if !has {
  160. return nil, ErrEmailAddressNotExist{}
  161. }
  162. return ea, nil
  163. }
  164. // GetEmailAddresses returns all email addresses belongs to given user.
  165. func GetEmailAddresses(ctx context.Context, uid int64) ([]*EmailAddress, error) {
  166. emails := make([]*EmailAddress, 0, 5)
  167. if err := db.GetEngine(ctx).
  168. Where("uid=?", uid).
  169. Asc("id").
  170. Find(&emails); err != nil {
  171. return nil, err
  172. }
  173. return emails, nil
  174. }
  175. // GetEmailAddressByID gets a user's email address by ID
  176. func GetEmailAddressByID(ctx context.Context, uid, id int64) (*EmailAddress, error) {
  177. // User ID is required for security reasons
  178. email := &EmailAddress{UID: uid}
  179. if has, err := db.GetEngine(ctx).ID(id).Get(email); err != nil {
  180. return nil, err
  181. } else if !has {
  182. return nil, nil
  183. }
  184. return email, nil
  185. }
  186. // IsEmailActive check if email is activated with a different emailID
  187. func IsEmailActive(ctx context.Context, email string, excludeEmailID int64) (bool, error) {
  188. if len(email) == 0 {
  189. return true, nil
  190. }
  191. // Can't filter by boolean field unless it's explicit
  192. cond := builder.NewCond()
  193. cond = cond.And(builder.Eq{"lower_email": strings.ToLower(email)}, builder.Neq{"id": excludeEmailID})
  194. if setting.Service.RegisterEmailConfirm {
  195. // Inactive (unvalidated) addresses don't count as active if email validation is required
  196. cond = cond.And(builder.Eq{"is_activated": true})
  197. }
  198. var em EmailAddress
  199. if has, err := db.GetEngine(ctx).Where(cond).Get(&em); has || err != nil {
  200. if has {
  201. log.Info("isEmailActive(%q, %d) found duplicate in email ID %d", email, excludeEmailID, em.ID)
  202. }
  203. return has, err
  204. }
  205. return false, nil
  206. }
  207. // IsEmailUsed returns true if the email has been used.
  208. func IsEmailUsed(ctx context.Context, email string) (bool, error) {
  209. if len(email) == 0 {
  210. return true, nil
  211. }
  212. return db.GetEngine(ctx).Where("lower_email=?", strings.ToLower(email)).Get(&EmailAddress{})
  213. }
  214. // ActivateEmail activates the email address to given user.
  215. func ActivateEmail(ctx context.Context, email *EmailAddress) error {
  216. return db.WithTx(ctx, func(ctx context.Context) error {
  217. return updateActivation(ctx, email, true)
  218. })
  219. }
  220. func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error {
  221. user, err := GetUserByID(ctx, email.UID)
  222. if err != nil {
  223. return err
  224. }
  225. if user.Rands, err = GetUserSalt(); err != nil {
  226. return err
  227. }
  228. email.IsActivated = activate
  229. if _, err := db.GetEngine(ctx).ID(email.ID).Cols("is_activated").Update(email); err != nil {
  230. return err
  231. }
  232. return UpdateUserCols(ctx, user, "rands")
  233. }
  234. func MakeActiveEmailPrimary(ctx context.Context, emailID int64) error {
  235. return makeEmailPrimaryInternal(ctx, emailID, true)
  236. }
  237. func MakeInactiveEmailPrimary(ctx context.Context, emailID int64) error {
  238. return makeEmailPrimaryInternal(ctx, emailID, false)
  239. }
  240. func makeEmailPrimaryInternal(ctx context.Context, emailID int64, isActive bool) error {
  241. email := &EmailAddress{}
  242. if has, err := db.GetEngine(ctx).ID(emailID).Where(builder.Eq{"is_activated": isActive}).Get(email); err != nil {
  243. return err
  244. } else if !has {
  245. return ErrEmailAddressNotExist{}
  246. }
  247. user := &User{}
  248. if has, err := db.GetEngine(ctx).ID(email.UID).Get(user); err != nil {
  249. return err
  250. } else if !has {
  251. return ErrUserNotExist{UID: email.UID}
  252. }
  253. return db.WithTx(ctx, func(ctx context.Context) error {
  254. sess := db.GetEngine(ctx)
  255. // 1. Update user table
  256. user.Email = email.Email
  257. if _, err := sess.ID(user.ID).Cols("email").Update(user); err != nil {
  258. return err
  259. }
  260. // 2. Update old primary email
  261. if _, err := sess.Where("uid=? AND is_primary=?", email.UID, true).Cols("is_primary").Update(&EmailAddress{
  262. IsPrimary: false,
  263. }); err != nil {
  264. return err
  265. }
  266. // 3. update new primary email
  267. email.IsPrimary = true
  268. if _, err := sess.ID(email.ID).Cols("is_primary").Update(email); err != nil {
  269. return err
  270. }
  271. return nil
  272. })
  273. }
  274. // ChangeInactivePrimaryEmail replaces the inactive primary email of a given user
  275. func ChangeInactivePrimaryEmail(ctx context.Context, uid int64, oldEmailAddr, newEmailAddr string) error {
  276. return db.WithTx(ctx, func(ctx context.Context) error {
  277. _, err := db.GetEngine(ctx).Where(builder.Eq{"uid": uid, "lower_email": strings.ToLower(oldEmailAddr)}).Delete(&EmailAddress{})
  278. if err != nil {
  279. return err
  280. }
  281. newEmail, err := InsertEmailAddress(ctx, &EmailAddress{UID: uid, Email: newEmailAddr})
  282. if err != nil {
  283. return err
  284. }
  285. return MakeInactiveEmailPrimary(ctx, newEmail.ID)
  286. })
  287. }
  288. // VerifyActiveEmailCode verifies active email code when active account
  289. func VerifyActiveEmailCode(ctx context.Context, code, email string) *EmailAddress {
  290. if user := GetVerifyUser(ctx, code); user != nil {
  291. // time limit code
  292. prefix := code[:base.TimeLimitCodeLength]
  293. opts := &TimeLimitCodeOptions{Purpose: TimeLimitCodeActivateEmail, NewEmail: email}
  294. data := makeTimeLimitCodeHashData(opts, user)
  295. if base.VerifyTimeLimitCode(time.Now(), data, setting.Service.ActiveCodeLives, prefix) {
  296. emailAddress := &EmailAddress{UID: user.ID, Email: email}
  297. if has, _ := db.GetEngine(ctx).Get(emailAddress); has {
  298. return emailAddress
  299. }
  300. }
  301. }
  302. return nil
  303. }
  304. // SearchEmailOrderBy is used to sort the results from SearchEmails()
  305. type SearchEmailOrderBy string
  306. func (s SearchEmailOrderBy) String() string {
  307. return string(s)
  308. }
  309. // Strings for sorting result
  310. const (
  311. SearchEmailOrderByEmail SearchEmailOrderBy = "email_address.lower_email ASC, email_address.is_primary DESC, email_address.id ASC"
  312. SearchEmailOrderByEmailReverse SearchEmailOrderBy = "email_address.lower_email DESC, email_address.is_primary ASC, email_address.id DESC"
  313. SearchEmailOrderByName SearchEmailOrderBy = "`user`.lower_name ASC, email_address.is_primary DESC, email_address.id ASC"
  314. SearchEmailOrderByNameReverse SearchEmailOrderBy = "`user`.lower_name DESC, email_address.is_primary ASC, email_address.id DESC"
  315. )
  316. // SearchEmailOptions are options to search e-mail addresses for the admin panel
  317. type SearchEmailOptions struct {
  318. db.ListOptions
  319. Keyword string
  320. SortType SearchEmailOrderBy
  321. IsPrimary optional.Option[bool]
  322. IsActivated optional.Option[bool]
  323. }
  324. // SearchEmailResult is an e-mail address found in the user or email_address table
  325. type SearchEmailResult struct {
  326. ID int64
  327. UID int64
  328. Email string
  329. IsActivated bool
  330. IsPrimary bool
  331. // From User
  332. Name string
  333. FullName string
  334. }
  335. // SearchEmails takes options i.e. keyword and part of email name to search,
  336. // it returns results in given range and number of total results.
  337. func SearchEmails(ctx context.Context, opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) {
  338. var cond builder.Cond = builder.Eq{"`user`.`type`": UserTypeIndividual}
  339. if len(opts.Keyword) > 0 {
  340. likeStr := "%" + strings.ToLower(opts.Keyword) + "%"
  341. cond = cond.And(builder.Or(
  342. builder.Like{"lower(`user`.full_name)", likeStr},
  343. builder.Like{"`user`.lower_name", likeStr},
  344. builder.Like{"email_address.lower_email", likeStr},
  345. ))
  346. }
  347. if opts.IsPrimary.Has() {
  348. cond = cond.And(builder.Eq{"email_address.is_primary": opts.IsPrimary.Value()})
  349. }
  350. if opts.IsActivated.Has() {
  351. cond = cond.And(builder.Eq{"email_address.is_activated": opts.IsActivated.Value()})
  352. }
  353. count, err := db.GetEngine(ctx).Join("INNER", "`user`", "`user`.id = email_address.uid").
  354. Where(cond).Count(new(EmailAddress))
  355. if err != nil {
  356. return nil, 0, fmt.Errorf("Count: %w", err)
  357. }
  358. orderby := opts.SortType.String()
  359. if orderby == "" {
  360. orderby = SearchEmailOrderByEmail.String()
  361. }
  362. opts.SetDefaultValues()
  363. emails := make([]*SearchEmailResult, 0, opts.PageSize)
  364. err = db.GetEngine(ctx).Table("email_address").
  365. Select("email_address.*, `user`.name, `user`.full_name").
  366. Join("INNER", "`user`", "`user`.id = email_address.uid").
  367. Where(cond).
  368. OrderBy(orderby).
  369. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  370. Find(&emails)
  371. return emails, count, err
  372. }
  373. // ActivateUserEmail will change the activated state of an email address,
  374. // either primary or secondary (all in the email_address table)
  375. func ActivateUserEmail(ctx context.Context, userID int64, email string, activate bool) (err error) {
  376. return db.WithTx(ctx, func(ctx context.Context) error {
  377. // Activate/deactivate a user's secondary email address
  378. // First check if there's another user active with the same address
  379. addr, exist, err := db.Get[EmailAddress](ctx, builder.Eq{"uid": userID, "lower_email": strings.ToLower(email)})
  380. if err != nil {
  381. return err
  382. } else if !exist {
  383. return fmt.Errorf("no such email: %d (%s)", userID, email)
  384. }
  385. if addr.IsActivated == activate {
  386. // Already in the desired state; no action
  387. return nil
  388. }
  389. if activate {
  390. if used, err := IsEmailActive(ctx, email, addr.ID); err != nil {
  391. return fmt.Errorf("unable to check isEmailActive() for %s: %w", email, err)
  392. } else if used {
  393. return ErrEmailAlreadyUsed{Email: email}
  394. }
  395. }
  396. if err = updateActivation(ctx, addr, activate); err != nil {
  397. return fmt.Errorf("unable to updateActivation() for %d:%s: %w", addr.ID, addr.Email, err)
  398. }
  399. // Activate/deactivate a user's primary email address and account
  400. if addr.IsPrimary {
  401. user, exist, err := db.Get[User](ctx, builder.Eq{"id": userID})
  402. if err != nil {
  403. return err
  404. } else if !exist || !strings.EqualFold(user.Email, email) {
  405. return fmt.Errorf("no user with ID: %d and Email: %s", userID, email)
  406. }
  407. // The user's activation state should be synchronized with the primary email
  408. if user.IsActive != activate {
  409. user.IsActive = activate
  410. if user.Rands, err = GetUserSalt(); err != nil {
  411. return fmt.Errorf("unable to generate salt: %w", err)
  412. }
  413. if err = UpdateUserCols(ctx, user, "is_active", "rands"); err != nil {
  414. return fmt.Errorf("unable to updateUserCols() for user ID: %d: %w", userID, err)
  415. }
  416. }
  417. }
  418. return nil
  419. })
  420. }
  421. // validateEmailBasic checks whether the email complies with the rules
  422. func validateEmailBasic(email string) error {
  423. if len(email) == 0 {
  424. return ErrEmailInvalid{email}
  425. }
  426. if !globalVars().emailRegexp.MatchString(email) {
  427. return ErrEmailCharIsNotSupported{email}
  428. }
  429. if email[0] == '-' {
  430. return ErrEmailInvalid{email}
  431. }
  432. if _, err := mail.ParseAddress(email); err != nil {
  433. return ErrEmailInvalid{email}
  434. }
  435. return nil
  436. }
  437. // validateEmailDomain checks whether the email domain is allowed or blocked
  438. func validateEmailDomain(email string) error {
  439. if !IsEmailDomainAllowed(email) {
  440. return ErrEmailInvalid{email}
  441. }
  442. return nil
  443. }
  444. func IsEmailDomainAllowed(email string) bool {
  445. if len(setting.Service.EmailDomainAllowList) == 0 {
  446. return !validation.IsEmailDomainListed(setting.Service.EmailDomainBlockList, email)
  447. }
  448. return validation.IsEmailDomainListed(setting.Service.EmailDomainAllowList, email)
  449. }
  450. func GetActivatedEmailAddresses(ctx context.Context, uid int64) ([]string, error) {
  451. emails := make([]string, 0, 2)
  452. if err := db.GetEngine(ctx).Table("email_address").Select("email").
  453. Where("uid=? AND is_activated=?", uid, true).Asc("id").
  454. Find(&emails); err != nil {
  455. return nil, err
  456. }
  457. return emails, nil
  458. }