clamis.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package utils
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/gofrs/uuid/v5"
  5. "github.com/sirupsen/logrus"
  6. systemReq "lcfns/model/system/request"
  7. )
  8. func GetClaims(c *gin.Context) (*systemReq.CustomClaims, error) {
  9. token := c.Request.Header.Get("x-token")
  10. j := NewJWT()
  11. claims, err := j.ParseToken(token)
  12. if err != nil {
  13. logrus.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构")
  14. }
  15. return claims, err
  16. }
  17. // GetUserID 从Gin的Context中获取从jwt解析出来的用户ID
  18. func GetUserID(c *gin.Context) uint {
  19. if claims, exists := c.Get("claims"); !exists {
  20. if cl, err := GetClaims(c); err != nil {
  21. return 0
  22. } else {
  23. return cl.BaseClaims.ID
  24. }
  25. } else {
  26. waitUse := claims.(*systemReq.CustomClaims)
  27. return waitUse.BaseClaims.ID
  28. }
  29. }
  30. // GetUserUuid 从Gin的Context中获取从jwt解析出来的用户UUID
  31. func GetUserUuid(c *gin.Context) uuid.UUID {
  32. if claims, exists := c.Get("claims"); !exists {
  33. if cl, err := GetClaims(c); err != nil {
  34. return uuid.UUID{}
  35. } else {
  36. return cl.UUID
  37. }
  38. } else {
  39. waitUse := claims.(*systemReq.CustomClaims)
  40. return waitUse.UUID
  41. }
  42. }
  43. // GetUserAuthorityId 从Gin的Context中获取从jwt解析出来的用户角色id
  44. func GetUserAuthorityId(c *gin.Context) uint {
  45. if claims, exists := c.Get("claims"); !exists {
  46. if cl, err := GetClaims(c); err != nil {
  47. return 0
  48. } else {
  49. return cl.AuthorityId
  50. }
  51. } else {
  52. waitUse := claims.(*systemReq.CustomClaims)
  53. return waitUse.AuthorityId
  54. }
  55. }
  56. // GetUserInfo 从Gin的Context中获取从jwt解析出来的用户角色id
  57. func GetUserInfo(c *gin.Context) *systemReq.CustomClaims {
  58. if claims, exists := c.Get("claims"); !exists {
  59. if cl, err := GetClaims(c); err != nil {
  60. return nil
  61. } else {
  62. return cl
  63. }
  64. } else {
  65. waitUse := claims.(*systemReq.CustomClaims)
  66. return waitUse
  67. }
  68. }
  69. // GetUserName 从Gin的Context中获取从jwt解析出来的用户名
  70. func GetUserName(c *gin.Context) string {
  71. if claims, exists := c.Get("claims"); !exists {
  72. if cl, err := GetClaims(c); err != nil {
  73. return ""
  74. } else {
  75. return cl.Username
  76. }
  77. } else {
  78. waitUse := claims.(*systemReq.CustomClaims)
  79. return waitUse.Username
  80. }
  81. }