user.go 8.2 KB

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