user.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package model
  2. import (
  3. "errors"
  4. "message-pusher/common"
  5. "strings"
  6. )
  7. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  8. // Otherwise, the sensitive information will be saved on local storage in plain text!
  9. type User struct {
  10. Id int `json:"id"`
  11. Username string `json:"username" gorm:"unique;index" validate:"max=12"`
  12. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  13. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  14. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  15. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  16. Token string `json:"token"`
  17. Email string `json:"email" gorm:"index" validate:"max=50"`
  18. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  19. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  20. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  21. Channel string `json:"channel"`
  22. WeChatTestAccountId string `json:"wechat_test_account_id" gorm:"column:wechat_test_account_id"`
  23. WeChatTestAccountSecret string `json:"wechat_test_account_secret" gorm:"column:wechat_test_account_secret"`
  24. WeChatTestAccountTemplateId string `json:"wechat_test_account_template_id" gorm:"column:wechat_test_account_template_id"`
  25. WeChatTestAccountOpenId string `json:"wechat_test_account_open_id" gorm:"column:wechat_test_account_open_id"`
  26. WeChatTestAccountVerificationToken string `json:"wechat_test_account_verification_token" gorm:"column:wechat_test_account_verification_token"`
  27. WeChatCorpAccountId string `json:"wechat_corp_account_id" gorm:"column:wechat_corp_account_id"`
  28. WeChatCorpAccountAgentSecret string `json:"wechat_corp_account_agent_secret" gorm:"column:wechat_corp_account_agent_secret"`
  29. WeChatCorpAccountAgentId string `json:"wechat_corp_account_agent_id" gorm:"column:wechat_corp_account_agent_id"`
  30. WeChatCorpAccountUserId string `json:"wechat_corp_account_user_id" gorm:"column:wechat_corp_account_user_id"`
  31. WeChatCorpAccountClientType string `json:"wechat_corp_account_client_type" gorm:"column:wechat_corp_account_client_type;default=plugin"`
  32. CorpWebhookURL string `json:"corp_webhook_url" gorm:"corp_webhook_url"`
  33. LarkWebhookURL string `json:"lark_webhook_url"`
  34. LarkWebhookSecret string `json:"lark_webhook_secret"`
  35. DingWebhookURL string `json:"ding_webhook_url"`
  36. DingWebhookSecret string `json:"ding_webhook_secret"`
  37. BarkServer string `json:"bark_server"`
  38. BarkSecret string `json:"bark_secret"`
  39. }
  40. func GetMaxUserId() int {
  41. var user User
  42. DB.Last(&user)
  43. return user.Id
  44. }
  45. func GetAllUsers(startIdx int, num int) (users []*User, err error) {
  46. err = DB.Order("id desc").Limit(num).Offset(startIdx).Select([]string{"id", "username", "display_name", "role", "status", "email"}).Find(&users).Error
  47. return users, err
  48. }
  49. func GetAllUsersWithSecrets() (users []*User, err error) {
  50. err = DB.Find(&users).Error
  51. return users, err
  52. }
  53. func SearchUsers(keyword string) (users []*User, err error) {
  54. err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email"}).Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
  55. return users, err
  56. }
  57. func GetUserById(id int, selectAll bool) (*User, error) {
  58. if id == 0 {
  59. return nil, errors.New("id 为空!")
  60. }
  61. user := User{Id: id}
  62. var err error = nil
  63. if selectAll {
  64. err = DB.First(&user, "id = ?", id).Error
  65. } else {
  66. err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email", "wechat_id", "github_id",
  67. "channel", "token",
  68. "wechat_test_account_id", "wechat_test_account_template_id", "wechat_test_account_open_id",
  69. "wechat_corp_account_id", "wechat_corp_account_agent_id", "wechat_corp_account_user_id", "wechat_corp_account_client_type",
  70. "corp_webhook_url", "lark_webhook_url", "ding_webhook_url", "bark_server",
  71. }).First(&user, "id = ?", id).Error
  72. }
  73. return &user, err
  74. }
  75. func DeleteUserById(id int) (err error) {
  76. if id == 0 {
  77. return errors.New("id 为空!")
  78. }
  79. user := User{Id: id}
  80. return user.Delete()
  81. }
  82. func (user *User) Insert() error {
  83. var err error
  84. if user.Password != "" {
  85. user.Password, err = common.Password2Hash(user.Password)
  86. if err != nil {
  87. return err
  88. }
  89. }
  90. err = DB.Create(user).Error
  91. return err
  92. }
  93. func (user *User) Update(updatePassword bool) error {
  94. var err error
  95. if updatePassword {
  96. user.Password, err = common.Password2Hash(user.Password)
  97. if err != nil {
  98. return err
  99. }
  100. }
  101. err = DB.Model(user).Updates(user).Error
  102. return err
  103. }
  104. func (user *User) Delete() error {
  105. if user.Id == 0 {
  106. return errors.New("id 为空!")
  107. }
  108. err := DB.Delete(user).Error
  109. return err
  110. }
  111. // ValidateAndFill check password & user status
  112. func (user *User) ValidateAndFill() (err error) {
  113. // When querying with struct, GORM will only query with non-zero fields,
  114. // that means if your field’s value is 0, '', false or other zero values,
  115. // it won’t be used to build query conditions
  116. password := user.Password
  117. if user.Username == "" || password == "" {
  118. return errors.New("用户名或密码为空")
  119. }
  120. DB.Where(User{Username: user.Username}).First(user)
  121. okay := common.ValidatePasswordAndHash(password, user.Password)
  122. if !okay || user.Status != common.UserStatusEnabled {
  123. return errors.New("用户名或密码错误,或用户已被封禁")
  124. }
  125. return nil
  126. }
  127. func (user *User) FillUserById() error {
  128. if user.Id == 0 {
  129. return errors.New("id 为空!")
  130. }
  131. DB.Where(User{Id: user.Id}).First(user)
  132. return nil
  133. }
  134. func (user *User) FillUserByEmail() error {
  135. if user.Email == "" {
  136. return errors.New("email 为空!")
  137. }
  138. DB.Where(User{Email: user.Email}).First(user)
  139. return nil
  140. }
  141. func (user *User) FillUserByGitHubId() error {
  142. if user.GitHubId == "" {
  143. return errors.New("GitHub id 为空!")
  144. }
  145. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  146. return nil
  147. }
  148. func (user *User) FillUserByWeChatId() error {
  149. if user.WeChatId == "" {
  150. return errors.New("WeChat id 为空!")
  151. }
  152. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  153. return nil
  154. }
  155. func (user *User) FillUserByUsername() error {
  156. if user.Username == "" {
  157. return errors.New("username 为空!")
  158. }
  159. DB.Where(User{Username: user.Username}).First(user)
  160. return nil
  161. }
  162. func ValidateUserToken(token string) (user *User) {
  163. if token == "" {
  164. return nil
  165. }
  166. token = strings.Replace(token, "Bearer ", "", 1)
  167. user = &User{}
  168. if DB.Where("token = ?", token).First(user).RowsAffected == 1 {
  169. return user
  170. }
  171. return nil
  172. }
  173. func IsEmailAlreadyTaken(email string) bool {
  174. return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
  175. }
  176. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  177. return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  178. }
  179. func IsGitHubIdAlreadyTaken(githubId string) bool {
  180. return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  181. }
  182. func IsUsernameAlreadyTaken(username string) bool {
  183. return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
  184. }
  185. func ResetUserPasswordByEmail(email string, password string) error {
  186. if email == "" || password == "" {
  187. return errors.New("邮箱地址或密码为空!")
  188. }
  189. hashedPassword, err := common.Password2Hash(password)
  190. if err != nil {
  191. return err
  192. }
  193. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  194. return err
  195. }