jwt.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2020 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package utils
  4. import (
  5. "access-control-monitor/errors"
  6. "strconv"
  7. "github.com/tidwall/gjson"
  8. "github.com/dgrijalva/jwt-go"
  9. "github.com/gin-gonic/gin"
  10. "github.com/jaryhe/gopkgs/logger"
  11. "go.uber.org/zap"
  12. )
  13. // GetJwtIdFromCtx 从 gin 上下文中获取 id
  14. func GetJwtIdFromCtx(ctx *gin.Context) (int64, error) {
  15. // 从上下文获取信息
  16. value, ok := ctx.Get("claims")
  17. if !ok {
  18. logger.Error("func",
  19. zap.String("call", "ctx.Get"),
  20. zap.String("error", "no claims data"))
  21. return 0, errors.ParamsError
  22. }
  23. // 解析数据
  24. claims, ok := value.(*jwt.StandardClaims)
  25. if !ok {
  26. logger.Error("func",
  27. zap.String("call", "Claims assert"),
  28. zap.String("error", "NOT Claims type"))
  29. return 0, errors.ParamsError
  30. }
  31. // 类型转换
  32. id, _ := strconv.ParseInt(claims.Id, 10, 64)
  33. return id, nil
  34. }
  35. func GetSupper(ctx *gin.Context) (bool, error) {
  36. value, ok := ctx.Get("claims")
  37. if !ok {
  38. logger.Error("func",
  39. zap.String("call", "ctx.Get"),
  40. zap.String("error", "no claims data"))
  41. return false, errors.ParamsError
  42. }
  43. // 解析数据
  44. claims, ok := value.(*jwt.StandardClaims)
  45. if !ok {
  46. logger.Error("func",
  47. zap.String("call", "Claims assert"),
  48. zap.String("error", "NOT Claims type"))
  49. return false, errors.ParamsError
  50. }
  51. supper := gjson.GetBytes(StrToBytes(claims.Subject), "supper").Bool()
  52. return supper, nil
  53. }
  54. // GetJwtIdFromCtx 从 gin 上下文中获取 id
  55. func GetJwtProjectIdFromCtx(ctx *gin.Context) (int64, error) {
  56. // 从上下文获取信息
  57. value, ok := ctx.Get("claims")
  58. if !ok {
  59. logger.Error("func",
  60. zap.String("call", "ctx.Get"),
  61. zap.String("error", "no claims data"))
  62. return 0, errors.ParamsError
  63. }
  64. // 解析数据
  65. claims, ok := value.(*jwt.StandardClaims)
  66. if !ok {
  67. logger.Error("func",
  68. zap.String("call", "Claims assert"),
  69. zap.String("error", "NOT Claims type"))
  70. return 0, errors.ParamsError
  71. }
  72. // 类型转换
  73. id := gjson.GetBytes(StrToBytes(claims.Subject), "project_id").Int()
  74. return id, nil
  75. }