You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

email_address.go 15KB

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