Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

user_email.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2021 The Gitea 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 models
  5. import (
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models/db"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/util"
  11. "xorm.io/builder"
  12. )
  13. // ActivateEmail activates the email address to given user.
  14. func ActivateEmail(email *user_model.EmailAddress) error {
  15. ctx, committer, err := db.TxContext()
  16. if err != nil {
  17. return err
  18. }
  19. defer committer.Close()
  20. if err := updateActivation(db.GetEngine(ctx), email, true); err != nil {
  21. return err
  22. }
  23. return committer.Commit()
  24. }
  25. func updateActivation(e db.Engine, email *user_model.EmailAddress, activate bool) error {
  26. user, err := getUserByID(e, email.UID)
  27. if err != nil {
  28. return err
  29. }
  30. if user.Rands, err = GetUserSalt(); err != nil {
  31. return err
  32. }
  33. email.IsActivated = activate
  34. if _, err := e.ID(email.ID).Cols("is_activated").Update(email); err != nil {
  35. return err
  36. }
  37. return updateUserCols(e, user, "rands")
  38. }
  39. // MakeEmailPrimary sets primary email address of given user.
  40. func MakeEmailPrimary(email *user_model.EmailAddress) error {
  41. has, err := db.GetEngine(db.DefaultContext).Get(email)
  42. if err != nil {
  43. return err
  44. } else if !has {
  45. return user_model.ErrEmailAddressNotExist{Email: email.Email}
  46. }
  47. if !email.IsActivated {
  48. return user_model.ErrEmailNotActivated
  49. }
  50. user := &User{}
  51. has, err = db.GetEngine(db.DefaultContext).ID(email.UID).Get(user)
  52. if err != nil {
  53. return err
  54. } else if !has {
  55. return ErrUserNotExist{email.UID, "", 0}
  56. }
  57. ctx, committer, err := db.TxContext()
  58. if err != nil {
  59. return err
  60. }
  61. defer committer.Close()
  62. sess := db.GetEngine(ctx)
  63. // 1. Update user table
  64. user.Email = email.Email
  65. if _, err = sess.ID(user.ID).Cols("email").Update(user); err != nil {
  66. return err
  67. }
  68. // 2. Update old primary email
  69. if _, err = sess.Where("uid=? AND is_primary=?", email.UID, true).Cols("is_primary").Update(&user_model.EmailAddress{
  70. IsPrimary: false,
  71. }); err != nil {
  72. return err
  73. }
  74. // 3. update new primary email
  75. email.IsPrimary = true
  76. if _, err = sess.ID(email.ID).Cols("is_primary").Update(email); err != nil {
  77. return err
  78. }
  79. return committer.Commit()
  80. }
  81. // SearchEmailOrderBy is used to sort the results from SearchEmails()
  82. type SearchEmailOrderBy string
  83. func (s SearchEmailOrderBy) String() string {
  84. return string(s)
  85. }
  86. // Strings for sorting result
  87. const (
  88. SearchEmailOrderByEmail SearchEmailOrderBy = "email_address.lower_email ASC, email_address.is_primary DESC, email_address.id ASC"
  89. SearchEmailOrderByEmailReverse SearchEmailOrderBy = "email_address.lower_email DESC, email_address.is_primary ASC, email_address.id DESC"
  90. SearchEmailOrderByName SearchEmailOrderBy = "`user`.lower_name ASC, email_address.is_primary DESC, email_address.id ASC"
  91. SearchEmailOrderByNameReverse SearchEmailOrderBy = "`user`.lower_name DESC, email_address.is_primary ASC, email_address.id DESC"
  92. )
  93. // SearchEmailOptions are options to search e-mail addresses for the admin panel
  94. type SearchEmailOptions struct {
  95. db.ListOptions
  96. Keyword string
  97. SortType SearchEmailOrderBy
  98. IsPrimary util.OptionalBool
  99. IsActivated util.OptionalBool
  100. }
  101. // SearchEmailResult is an e-mail address found in the user or email_address table
  102. type SearchEmailResult struct {
  103. UID int64
  104. Email string
  105. IsActivated bool
  106. IsPrimary bool
  107. // From User
  108. Name string
  109. FullName string
  110. }
  111. // SearchEmails takes options i.e. keyword and part of email name to search,
  112. // it returns results in given range and number of total results.
  113. func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) {
  114. var cond builder.Cond = builder.Eq{"`user`.`type`": UserTypeIndividual}
  115. if len(opts.Keyword) > 0 {
  116. likeStr := "%" + strings.ToLower(opts.Keyword) + "%"
  117. cond = cond.And(builder.Or(
  118. builder.Like{"lower(`user`.full_name)", likeStr},
  119. builder.Like{"`user`.lower_name", likeStr},
  120. builder.Like{"email_address.lower_email", likeStr},
  121. ))
  122. }
  123. switch {
  124. case opts.IsPrimary.IsTrue():
  125. cond = cond.And(builder.Eq{"email_address.is_primary": true})
  126. case opts.IsPrimary.IsFalse():
  127. cond = cond.And(builder.Eq{"email_address.is_primary": false})
  128. }
  129. switch {
  130. case opts.IsActivated.IsTrue():
  131. cond = cond.And(builder.Eq{"email_address.is_activated": true})
  132. case opts.IsActivated.IsFalse():
  133. cond = cond.And(builder.Eq{"email_address.is_activated": false})
  134. }
  135. count, err := db.GetEngine(db.DefaultContext).Join("INNER", "`user`", "`user`.ID = email_address.uid").
  136. Where(cond).Count(new(user_model.EmailAddress))
  137. if err != nil {
  138. return nil, 0, fmt.Errorf("Count: %v", err)
  139. }
  140. orderby := opts.SortType.String()
  141. if orderby == "" {
  142. orderby = SearchEmailOrderByEmail.String()
  143. }
  144. opts.SetDefaultValues()
  145. emails := make([]*SearchEmailResult, 0, opts.PageSize)
  146. err = db.GetEngine(db.DefaultContext).Table("email_address").
  147. Select("email_address.*, `user`.name, `user`.full_name").
  148. Join("INNER", "`user`", "`user`.ID = email_address.uid").
  149. Where(cond).
  150. OrderBy(orderby).
  151. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  152. Find(&emails)
  153. return emails, count, err
  154. }
  155. // ActivateUserEmail will change the activated state of an email address,
  156. // either primary or secondary (all in the email_address table)
  157. func ActivateUserEmail(userID int64, email string, activate bool) (err error) {
  158. ctx, committer, err := db.TxContext()
  159. if err != nil {
  160. return err
  161. }
  162. defer committer.Close()
  163. sess := db.GetEngine(ctx)
  164. // Activate/deactivate a user's secondary email address
  165. // First check if there's another user active with the same address
  166. addr := user_model.EmailAddress{UID: userID, LowerEmail: strings.ToLower(email)}
  167. if has, err := sess.Get(&addr); err != nil {
  168. return err
  169. } else if !has {
  170. return fmt.Errorf("no such email: %d (%s)", userID, email)
  171. }
  172. if addr.IsActivated == activate {
  173. // Already in the desired state; no action
  174. return nil
  175. }
  176. if activate {
  177. if used, err := user_model.IsEmailActive(ctx, email, addr.ID); err != nil {
  178. return fmt.Errorf("unable to check isEmailActive() for %s: %v", email, err)
  179. } else if used {
  180. return user_model.ErrEmailAlreadyUsed{Email: email}
  181. }
  182. }
  183. if err = updateActivation(sess, &addr, activate); err != nil {
  184. return fmt.Errorf("unable to updateActivation() for %d:%s: %w", addr.ID, addr.Email, err)
  185. }
  186. // Activate/deactivate a user's primary email address and account
  187. if addr.IsPrimary {
  188. user := User{ID: userID, Email: email}
  189. if has, err := sess.Get(&user); err != nil {
  190. return err
  191. } else if !has {
  192. return fmt.Errorf("no user with ID: %d and Email: %s", userID, email)
  193. }
  194. // The user's activation state should be synchronized with the primary email
  195. if user.IsActive != activate {
  196. user.IsActive = activate
  197. if user.Rands, err = GetUserSalt(); err != nil {
  198. return fmt.Errorf("unable to generate salt: %v", err)
  199. }
  200. if err = updateUserCols(sess, &user, "is_active", "rands"); err != nil {
  201. return fmt.Errorf("unable to updateUserCols() for user ID: %d: %v", userID, err)
  202. }
  203. }
  204. }
  205. return committer.Commit()
  206. }