admin_common.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package handler
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/sirupsen/logrus"
  6. "go-micro.dev/v4/auth"
  7. "go-micro.dev/v4/metadata"
  8. "golang.org/x/crypto/bcrypt"
  9. "sghgogs.com/sghblog/authorization-service/domain/service"
  10. pb "sghgogs.com/sghblog/authorization-service/proto"
  11. "sghgogs.com/sghblog/authorization-service/utils/authutil"
  12. "sghgogs.com/sghblog/common"
  13. "sghgogs.com/sghblog/common/errorcode"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. type AdminCommon struct {
  19. Service service.IService
  20. }
  21. func ConvertTimeToInt64(t time.Time) int64 {
  22. return t.Unix()
  23. }
  24. // checkPasswordHash 验证用户输入的密码是否与存储的哈希值匹配
  25. func checkPasswordHash(password, hash string) bool {
  26. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
  27. return err == nil
  28. }
  29. func (svc *AdminCommon) AdminLogin(ctx context.Context, loginUser *pb.AdminLoginRequest, rsp *pb.AdminLoginResponse) error {
  30. // 1. 查询
  31. if user, uErr := svc.Service.AdminLogin(loginUser.Username, loginUser.Password); uErr != nil {
  32. return uErr
  33. } else {
  34. rsp.User = &user
  35. md := map[string]string{}
  36. md["username"] = user.Username
  37. md["user_id"] = fmt.Sprintf("%d", user.Id)
  38. md["phone_number"] = user.PhoneNumber
  39. md["password"] = loginUser.Password
  40. var roles []string
  41. for _, role := range user.Roles {
  42. roles = append(roles, strings.ToLower(role.Key))
  43. }
  44. generate, err := authutil.JWTAuthService.GenerateToken(
  45. user.Id,
  46. "system",
  47. "user",
  48. loginUser.Password,
  49. roles,
  50. md,
  51. )
  52. if err != nil {
  53. return errorcode.BadRequest("authorization service", common.ErrorMessage[common.FailedToGenerateTokenErrorCode])
  54. }
  55. token, err := authutil.JWTAuthService.Token(user.Id, generate.Secret)
  56. if err != nil {
  57. return errorcode.BadRequest("authorization service", common.ErrorMessage[common.FailedToGenerateTokenErrorCode])
  58. }
  59. if err = authutil.JWTAuthService.StoreToken(ctx, user.Id, user.Username, token.AccessToken); err != nil {
  60. return errorcode.BadRequest("authorization service", common.ErrorMessage[common.FailedToStoreTokenErrorCode])
  61. }
  62. rsp.Token = token.AccessToken
  63. }
  64. return nil
  65. }
  66. func (svc *AdminCommon) AdminLogout(ctx context.Context, logoutRequest *pb.AdminLogoutRequest, rsp *pb.AdminLogoutResponse) error {
  67. md, b := metadata.FromContext(ctx)
  68. if !b {
  69. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.UnauthorizedErrorCode])
  70. }
  71. authHeader, ok := md["Authorization"]
  72. if !ok || !strings.HasPrefix(authHeader, auth.BearerScheme) {
  73. logrus.Error("no auth token provided")
  74. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.UnauthorizedErrorCode])
  75. }
  76. // Extract auth token.
  77. token := strings.TrimPrefix(authHeader, auth.BearerScheme)
  78. token = strings.TrimSpace(token)
  79. if err := authutil.JWTAuthService.Blacklist(token); err != nil {
  80. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.FailedRedisInternalServerErrorCode])
  81. }
  82. return nil
  83. }
  84. func (svc *AdminCommon) AdminProfile(ctx context.Context, profileRequest *pb.AdminProfileRequest, rsp *pb.AdminProfileResponse) error {
  85. md, b := metadata.FromContext(ctx)
  86. if !b {
  87. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.UnauthorizedErrorCode])
  88. // errors.New("no metadata found")
  89. }
  90. authHeader, ok := md["Authorization"]
  91. if !ok || !strings.HasPrefix(authHeader, auth.BearerScheme) {
  92. logrus.Error("no auth token provided")
  93. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.UnauthorizedErrorCode])
  94. }
  95. // Extract auth token.
  96. token := strings.TrimPrefix(authHeader, auth.BearerScheme)
  97. token = strings.TrimSpace(token)
  98. inspect, err := authutil.JWTAuthService.Inspect(token)
  99. if err != nil {
  100. return errorcode.Unauthorized("authorization service", common.ErrorMessage[common.TokenInvalidErrorCode])
  101. }
  102. if value, ok := inspect.Metadata["user_id"]; ok {
  103. userId, _ := strconv.ParseInt(value, 10, 64)
  104. user, err := svc.Service.GetAdminUser(userId)
  105. if err != nil {
  106. return err
  107. }
  108. rsp.User = user
  109. }
  110. return nil
  111. }