sys_user.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package models
  2. import (
  3. "go-admin/common/models"
  4. "golang.org/x/crypto/bcrypt"
  5. "gorm.io/gorm"
  6. )
  7. type SysUser struct {
  8. UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
  9. Username string `json:"username" gorm:"size:64;comment:用户名"`
  10. Password string `json:"-" gorm:"size:128;comment:密码"`
  11. NickName string `json:"nickName" gorm:"size:128;comment:昵称"`
  12. Phone string `json:"phone" gorm:"size:11;comment:手机号"`
  13. RoleId int `json:"roleId" gorm:"size:20;comment:角色ID"`
  14. Salt string `json:"-" gorm:"size:255;comment:加盐"`
  15. Avatar string `json:"avatar" gorm:"size:255;comment:头像"`
  16. Sex string `json:"sex" gorm:"size:255;comment:性别"`
  17. Email string `json:"email" gorm:"size:128;comment:邮箱"`
  18. DeptId int `json:"deptId" gorm:"size:20;comment:部门"`
  19. PostId int `json:"postId" gorm:"size:20;comment:岗位"`
  20. Remark string `json:"remark" gorm:"size:255;comment:备注"`
  21. Status string `json:"status" gorm:"size:4;comment:状态"`
  22. DeptIds []int `json:"deptIds" gorm:"-"`
  23. PostIds []int `json:"postIds" gorm:"-"`
  24. RoleIds []int `json:"roleIds" gorm:"-"`
  25. Dept *SysDept `json:"dept"`
  26. models.ControlBy
  27. models.ModelTime
  28. }
  29. func (SysUser) TableName() string {
  30. return "sys_user"
  31. }
  32. func (e *SysUser) Generate() models.ActiveRecord {
  33. o := *e
  34. return &o
  35. }
  36. func (e *SysUser) GetId() interface{} {
  37. return e.UserId
  38. }
  39. //加密
  40. func (e *SysUser) Encrypt() (err error) {
  41. if e.Password == "" {
  42. return
  43. }
  44. var hash []byte
  45. if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
  46. return
  47. } else {
  48. e.Password = string(hash)
  49. return
  50. }
  51. }
  52. func (e *SysUser) BeforeCreate(_ *gorm.DB) error {
  53. return e.Encrypt()
  54. }
  55. func (e *SysUser) BeforeUpdate(_ *gorm.DB) error {
  56. var err error
  57. if e.Password != "" {
  58. err = e.Encrypt()
  59. }
  60. return err
  61. }
  62. func (e *SysUser) AfterFind(_ *gorm.DB) error {
  63. e.DeptIds = []int{e.DeptId}
  64. e.PostIds = []int{e.PostId}
  65. e.RoleIds = []int{e.RoleId}
  66. return nil
  67. }