service-user.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package service
  2. import (
  3. "exam_system/dao"
  4. "exam_system/entity"
  5. "exam_system/middleware/claims"
  6. "exam_system/result"
  7. "exam_system/vo"
  8. "github.com/gin-gonic/gin"
  9. "golang.org/x/crypto/bcrypt"
  10. "strings"
  11. )
  12. func Login(u *vo.UserVo) *result.Result {
  13. // 1、查询
  14. res := dao.FindUserbySid(u.Sid)
  15. if res.Data == nil {
  16. return res
  17. }
  18. // 2、查询角色
  19. userVo := res.Data.(vo.UserVo)
  20. roleNames := strings.Split(*userVo.RoleName, ",")
  21. // 3、解密
  22. err := bcrypt.CompareHashAndPassword([]byte(userVo.Password), []byte(u.Password))
  23. if err != nil {
  24. return result.PASSWORD_ERROR
  25. }
  26. // 4、判断角色是否存在
  27. roleExist := false
  28. for _, roleName := range roleNames {
  29. if roleName == *u.RoleName {
  30. roleExist = true
  31. break
  32. }
  33. }
  34. if !roleExist {
  35. return result.USER_IS_NOT_EXISTED
  36. }
  37. if *userVo.Status != entity.NORMAL {
  38. return result.USER_PENDING_REVIEW
  39. }
  40. // 4、生产token
  41. token, err := claims.GenToken(userVo.ID, userVo.Username, userVo.Sid, roleNames)
  42. if err != nil {
  43. return result.UNKNOW_ERROR
  44. }
  45. userVo.Password = ""
  46. return result.SUCCESS.SetData(gin.H{
  47. "token": token,
  48. "user": userVo,
  49. })
  50. }
  51. // AddUser 管理员,用户公用
  52. func AddUser(u *entity.User, userTypes string) *result.Result {
  53. // 1、加密
  54. hash, _ := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
  55. u.Password = string(hash)
  56. // 2、插入用户表
  57. res := dao.InsertUser(u, userTypes)
  58. if res != result.SUCCESS {
  59. return res
  60. }
  61. return res
  62. }