user.go 8.5 KB

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