user.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. ClientSecret string `json:"client_secret"`
  40. TelegramBotToken string `json:"telegram_bot_token"`
  41. TelegramChatId string `json:"telegram_chat_id"`
  42. }
  43. func GetMaxUserId() int {
  44. var user User
  45. DB.Last(&user)
  46. return user.Id
  47. }
  48. func GetAllUsers(startIdx int, num int) (users []*User, err error) {
  49. err = DB.Order("id desc").Limit(num).Offset(startIdx).Select([]string{"id", "username", "display_name", "role", "status", "email"}).Find(&users).Error
  50. return users, err
  51. }
  52. func GetAllUsersWithSecrets() (users []*User, err error) {
  53. err = DB.Where("status = ?", common.UserStatusEnabled).Where("wechat_test_account_id != '' or wechat_corp_account_id != ''").Find(&users).Error
  54. return users, err
  55. }
  56. func SearchUsers(keyword string) (users []*User, err error) {
  57. 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
  58. return users, err
  59. }
  60. func GetUserById(id int, selectAll bool) (*User, error) {
  61. if id == 0 {
  62. return nil, errors.New("id 为空!")
  63. }
  64. user := User{Id: id}
  65. var err error = nil
  66. if selectAll {
  67. err = DB.First(&user, "id = ?", id).Error
  68. } else {
  69. err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email", "wechat_id", "github_id",
  70. "channel", "token",
  71. "wechat_test_account_id", "wechat_test_account_template_id", "wechat_test_account_open_id",
  72. "wechat_corp_account_id", "wechat_corp_account_agent_id", "wechat_corp_account_user_id", "wechat_corp_account_client_type",
  73. "corp_webhook_url", "lark_webhook_url", "ding_webhook_url", "bark_server", "telegram_chat_id",
  74. }).First(&user, "id = ?", id).Error
  75. }
  76. return &user, err
  77. }
  78. func DeleteUserById(id int) (err error) {
  79. if id == 0 {
  80. return errors.New("id 为空!")
  81. }
  82. user := User{Id: id}
  83. return user.Delete()
  84. }
  85. func (user *User) Insert() error {
  86. var err error
  87. if user.Password != "" {
  88. user.Password, err = common.Password2Hash(user.Password)
  89. if err != nil {
  90. return err
  91. }
  92. }
  93. err = DB.Create(user).Error
  94. return err
  95. }
  96. func (user *User) Update(updatePassword bool) error {
  97. var err error
  98. if updatePassword {
  99. user.Password, err = common.Password2Hash(user.Password)
  100. if err != nil {
  101. return err
  102. }
  103. }
  104. err = DB.Model(user).Updates(user).Error
  105. return err
  106. }
  107. func (user *User) Delete() error {
  108. if user.Id == 0 {
  109. return errors.New("id 为空!")
  110. }
  111. err := DB.Delete(user).Error
  112. return err
  113. }
  114. // ValidateAndFill check password & user status
  115. func (user *User) ValidateAndFill() (err error) {
  116. // When querying with struct, GORM will only query with non-zero fields,
  117. // that means if your field’s value is 0, '', false or other zero values,
  118. // it won’t be used to build query conditions
  119. password := user.Password
  120. if user.Username == "" || password == "" {
  121. return errors.New("用户名或密码为空")
  122. }
  123. DB.Where(User{Username: user.Username}).First(user)
  124. okay := common.ValidatePasswordAndHash(password, user.Password)
  125. if !okay || user.Status != common.UserStatusEnabled {
  126. return errors.New("用户名或密码错误,或用户已被封禁")
  127. }
  128. return nil
  129. }
  130. func (user *User) FillUserById() error {
  131. if user.Id == 0 {
  132. return errors.New("id 为空!")
  133. }
  134. DB.Where(User{Id: user.Id}).First(user)
  135. return nil
  136. }
  137. func (user *User) FillUserByEmail() error {
  138. if user.Email == "" {
  139. return errors.New("email 为空!")
  140. }
  141. DB.Where(User{Email: user.Email}).First(user)
  142. return nil
  143. }
  144. func (user *User) FillUserByGitHubId() error {
  145. if user.GitHubId == "" {
  146. return errors.New("GitHub id 为空!")
  147. }
  148. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  149. return nil
  150. }
  151. func (user *User) FillUserByWeChatId() error {
  152. if user.WeChatId == "" {
  153. return errors.New("WeChat id 为空!")
  154. }
  155. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  156. return nil
  157. }
  158. func (user *User) FillUserByUsername() error {
  159. if user.Username == "" {
  160. return errors.New("username 为空!")
  161. }
  162. DB.Where(User{Username: user.Username}).First(user)
  163. return nil
  164. }
  165. func ValidateUserToken(token string) (user *User) {
  166. if token == "" {
  167. return nil
  168. }
  169. token = strings.Replace(token, "Bearer ", "", 1)
  170. user = &User{}
  171. if DB.Where("token = ?", token).First(user).RowsAffected == 1 {
  172. return user
  173. }
  174. return nil
  175. }
  176. func IsEmailAlreadyTaken(email string) bool {
  177. return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
  178. }
  179. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  180. return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  181. }
  182. func IsGitHubIdAlreadyTaken(githubId string) bool {
  183. return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  184. }
  185. func IsUsernameAlreadyTaken(username string) bool {
  186. return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
  187. }
  188. func ResetUserPasswordByEmail(email string, password string) error {
  189. if email == "" || password == "" {
  190. return errors.New("邮箱地址或密码为空!")
  191. }
  192. hashedPassword, err := common.Password2Hash(password)
  193. if err != nil {
  194. return err
  195. }
  196. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  197. return err
  198. }