sys_user.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package system
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/sirupsen/logrus"
  6. systemReq "lc-base-frame/model/system/request"
  7. "lc-base-frame/model/system/response"
  8. "time"
  9. "github.com/gofrs/uuid/v5"
  10. "gorm.io/gorm"
  11. "lc-base-frame/global"
  12. "lc-base-frame/model/common/request"
  13. "lc-base-frame/model/system"
  14. "lc-base-frame/utils"
  15. )
  16. //@author: [piexlmax](https://github.com/piexlmax)
  17. //@function: Register
  18. //@description: 用户注册
  19. //@param: u model.SysUser
  20. //@return: userInter system.SysUser, err error
  21. type UserService struct{}
  22. func (userService *UserService) Register(u system.SysUser) (userInter system.SysUser, err error) {
  23. var user system.SysUser
  24. if !errors.Is(global.Db.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
  25. return userInter, errors.New("用户名已注册")
  26. }
  27. // 否则 附加uuid 密码hash加密 注册
  28. u.Password = utils.BcryptHash(u.Password)
  29. u.UUID = uuid.Must(uuid.NewV4())
  30. err = global.Db.Create(&u).Error
  31. return u, err
  32. }
  33. //@author: [piexlmax](https://github.com/piexlmax)
  34. //@author: [SliverHorn](https://github.com/SliverHorn)
  35. //@function: Login
  36. //@description: 用户登录
  37. //@param: u *model.SysUser
  38. //@return: err error, userInter *model.SysUser
  39. func (userService *UserService) Login(u *system.SysUser) (userInter *system.SysUser, err error) {
  40. if nil == global.Db {
  41. return nil, fmt.Errorf("db not init")
  42. }
  43. var user system.SysUser
  44. err = global.Db.Where("username = ?", u.Username).Preload("Authorities").Preload("Authority").First(&user).Error
  45. if err == nil {
  46. if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
  47. return nil, errors.New("密码错误")
  48. }
  49. MenuServiceApp.UserAuthorityDefaultRouter(&user)
  50. }
  51. return &user, err
  52. //return nil, err
  53. }
  54. //@author: [piexlmax](https://github.com/piexlmax)
  55. //@function: ChangePassword
  56. //@description: 修改用户密码
  57. //@param: u *model.SysUser, newPassword string
  58. //@return: userInter *model.SysUser,err error
  59. func (userService *UserService) ChangePassword(u *system.SysUser, newPassword string) (userInter *system.SysUser, err error) {
  60. var user system.SysUser
  61. if err = global.Db.Where("id = ?", u.ID).First(&user).Error; err != nil {
  62. return nil, err
  63. }
  64. if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
  65. return nil, errors.New("原密码错误")
  66. }
  67. user.Password = utils.BcryptHash(newPassword)
  68. err = global.Db.Save(&user).Error
  69. return &user, err
  70. }
  71. //@author: [piexlmax](https://github.com/piexlmax)
  72. //@function: GetUserInfoList
  73. //@description: 分页获取数据
  74. //@param: info request.PageInfo
  75. //@return: err error, list interface{}, total int64
  76. func (userService *UserService) GetUserInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
  77. limit := info.PageSize
  78. offset := info.PageSize * (info.Page - 1)
  79. db := global.Db.Model(&system.SysUser{})
  80. var userList []system.SysUser
  81. err = db.Count(&total).Error
  82. if err != nil {
  83. return
  84. }
  85. err = db.Limit(limit).Offset(offset).Preload("Authorities").Preload("Authority").Find(&userList).Error
  86. return userList, total, err
  87. }
  88. //@author: [piexlmax](https://github.com/piexlmax)
  89. //@function: SetUserAuthority
  90. //@description: 设置一个用户的权限
  91. //@param: uuid uuid.UUID, authorityId string
  92. //@return: err error
  93. func (userService *UserService) SetUserAuthority(id uint, authorityId uint) (err error) {
  94. assignErr := global.Db.Where("sys_user_id = ? AND sys_authority_authority_id = ?", id, authorityId).First(&system.SysUserAuthority{}).Error
  95. if errors.Is(assignErr, gorm.ErrRecordNotFound) {
  96. return errors.New("该用户无此角色")
  97. }
  98. err = global.Db.Where("id = ?", id).First(&system.SysUser{}).Update("authority_id", authorityId).Error
  99. return err
  100. }
  101. //@author: [piexlmax](https://github.com/piexlmax)
  102. //@function: SetUserAuthorities
  103. //@description: 设置一个用户的权限
  104. //@param: id uint, authorityIds []string
  105. //@return: err error
  106. func (userService *UserService) SetUserAuthorities(id uint, authorityIds []uint) (err error) {
  107. return global.Db.Transaction(func(tx *gorm.DB) error {
  108. TxErr := tx.Delete(&[]system.SysUserAuthority{}, "sys_user_id = ?", id).Error
  109. if TxErr != nil {
  110. return TxErr
  111. }
  112. var useAuthority []system.SysUserAuthority
  113. for _, v := range authorityIds {
  114. useAuthority = append(useAuthority, system.SysUserAuthority{
  115. SysUserId: id, SysAuthorityAuthorityId: v,
  116. })
  117. }
  118. TxErr = tx.Create(&useAuthority).Error
  119. if TxErr != nil {
  120. return TxErr
  121. }
  122. TxErr = tx.Where("id = ?", id).First(&system.SysUser{}).Update("authority_id", authorityIds[0]).Error
  123. if TxErr != nil {
  124. return TxErr
  125. }
  126. // 返回 nil 提交事务
  127. return nil
  128. })
  129. }
  130. //@author: [piexlmax](https://github.com/piexlmax)
  131. //@function: DeleteUser
  132. //@description: 删除用户
  133. //@param: id float64
  134. //@return: err error
  135. func (userService *UserService) DeleteUser(id int) (err error) {
  136. var user system.SysUser
  137. err = global.Db.Where("id = ?", id).Delete(&user).Error
  138. if err != nil {
  139. return err
  140. }
  141. err = global.Db.Delete(&[]system.SysUserAuthority{}, "sys_user_id = ?", id).Error
  142. return err
  143. }
  144. //@author: [piexlmax](https://github.com/piexlmax)
  145. //@function: SetUserInfo
  146. //@description: 设置用户信息
  147. //@param: reqUser model.SysUser
  148. //@return: err error, user model.SysUser
  149. func (userService *UserService) SetUserInfo(req system.SysUser) error {
  150. return global.Db.Model(&system.SysUser{}).
  151. Select("updated_at", "nick_name", "header_img", "phone", "email", "sideMode", "enable").
  152. Where("id=?", req.ID).
  153. Updates(map[string]interface{}{
  154. "updated_at": time.Now(),
  155. "nick_name": req.NickName,
  156. "header_img": req.HeaderImg,
  157. "phone": req.Phone,
  158. "email": req.Email,
  159. "side_mode": req.SideMode,
  160. "enable": req.Enable,
  161. }).Error
  162. }
  163. //@author: [piexlmax](https://github.com/piexlmax)
  164. //@function: SetUserInfo
  165. //@description: 设置用户信息
  166. //@param: reqUser model.SysUser
  167. //@return: err error, user model.SysUser
  168. func (userService *UserService) SetSelfInfo(req system.SysUser) error {
  169. return global.Db.Model(&system.SysUser{}).
  170. Where("id=?", req.ID).
  171. Updates(req).Error
  172. }
  173. //@author: [piexlmax](https://github.com/piexlmax)
  174. //@author: [SliverHorn](https://github.com/SliverHorn)
  175. //@function: GetUserInfo
  176. //@description: 获取用户信息
  177. //@param: uuid uuid.UUID
  178. //@return: err error, user system.SysUser
  179. func (userService *UserService) GetUserInfo(uuid uuid.UUID) (user system.SysUser, err error) {
  180. var reqUser system.SysUser
  181. err = global.Db.Preload("Authorities").Preload("Authority").First(&reqUser, "uuid = ?", uuid).Error
  182. if err != nil {
  183. return reqUser, err
  184. }
  185. MenuServiceApp.UserAuthorityDefaultRouter(&reqUser)
  186. return reqUser, err
  187. }
  188. //@author: [SliverHorn](https://github.com/SliverHorn)
  189. //@function: FindUserById
  190. //@description: 通过id获取用户信息
  191. //@param: id int
  192. //@return: err error, user *model.SysUser
  193. func (userService *UserService) FindUserById(id int) (user *system.SysUser, err error) {
  194. var u system.SysUser
  195. err = global.Db.Where("`id` = ?", id).First(&u).Error
  196. return &u, err
  197. }
  198. //@author: [SliverHorn](https://github.com/SliverHorn)
  199. //@function: FindUserByUuid
  200. //@description: 通过uuid获取用户信息
  201. //@param: uuid string
  202. //@return: err error, user *model.SysUser
  203. func (userService *UserService) FindUserByUuid(uuid string) (user *system.SysUser, err error) {
  204. var u system.SysUser
  205. if err = global.Db.Where("`uuid` = ?", uuid).First(&u).Error; err != nil {
  206. return &u, errors.New("用户不存在")
  207. }
  208. return &u, nil
  209. }
  210. //@author: [piexlmax](https://github.com/piexlmax)
  211. //@function: resetPassword
  212. //@description: 修改用户密码
  213. //@param: ID uint
  214. //@return: err error
  215. func (userService *UserService) ResetPassword(ID uint) (err error) {
  216. err = global.Db.Model(&system.SysUser{}).Where("id = ?", ID).Update("password", utils.BcryptHash("123456")).Error
  217. return err
  218. }
  219. func (userService *UserService) UserId(ID uint) (ids []response.IdName, err error) {
  220. db := global.Db.Select("id, username").Model(&system.SysUser{})
  221. if ID > 1 {
  222. db.Where("id = ?", ID)
  223. }
  224. err = db.Find(&ids).Error
  225. return
  226. }
  227. func (userService *UserService) SetAlarmEmail(uid uint, emails []systemReq.Email) string {
  228. var html = `
  229. <!DOCTYPE html>
  230. <html>
  231. <head><title>邮箱确认</title></head>
  232. <body><h1>
  233. <a href="%s">点击链接绑定龙弛防溺水报警邮箱通知,10分钟内有效</a>
  234. </h1></body>
  235. </html>`
  236. //todo 修改ip
  237. var result string //已绑定的邮箱
  238. v4, _ := uuid.NewV4()
  239. for _, v := range emails {
  240. //已绑定,continue
  241. var id uint
  242. global.Db.Select("id").Table("sys_user_email").Where("uid = ? AND email = ?", uid, v.Email).Scan(&id)
  243. if id != 0 {
  244. result += v.Email
  245. continue
  246. }
  247. //未绑定,发送确认邮件
  248. s := v4.String()
  249. global.BlackCache.Set(s, v.Email, time.Minute*10)
  250. url := fmt.Sprintf(`http://192.168.110.69:8889/user/confirm?id=%d&code=%s`, uid, s)
  251. utils.Email(v.Email, "邮箱确认", fmt.Sprintf(html, url))
  252. }
  253. return result
  254. }
  255. func (userService *UserService) ConfirmEmail(id string, code string) string {
  256. var html = `
  257. <!DOCTYPE html>
  258. <html>
  259. <head>
  260. <title>成功页面</title>
  261. </head>
  262. <body>
  263. <h1>邮箱绑定成功!</h1>
  264. </body>
  265. </html>`
  266. var fail = `
  267. <!DOCTYPE html>
  268. <html>
  269. <body>
  270. <p>绑定失败,请联系管理员。</p>
  271. </body>
  272. </html>`
  273. v, ok := global.BlackCache.Get(code)
  274. if !ok {
  275. return fail
  276. }
  277. email := v.(string)
  278. err := global.Db.Table("sys_user_email").Create(map[string]interface{}{"uid": id, "email": email, "enable": 0}).Error
  279. if err != nil {
  280. logrus.Error("邮箱绑定失败", err)
  281. return fail
  282. }
  283. return html
  284. }
  285. // UnbindEmail 解绑邮箱
  286. func (userService *UserService) UnbindEmail(uid uint, emails []systemReq.Email) string {
  287. var errStr string
  288. for _, email := range emails {
  289. err := global.Db.Table("sys_user_email").Where("uid = ? AND email = ?", uid, email.Email).Update("enable", 1).Error
  290. if err != nil {
  291. errStr += email.Email + " "
  292. }
  293. }
  294. return errStr
  295. }