另客网go项目公用的代码库

auth.go 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. package auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/gin-gonic/gin"
  7. )
  8. const (
  9. CtxRequestHeaderUserId = "user_id"
  10. CtxRequestHeaderTeamId = "team_id"
  11. CtxRequestHeaderRoleId = "role_id"
  12. ctxRequestHeaderAuthorization = "Authorization"
  13. ctxRequestCookieAuthorization = "ak"
  14. ctxRequestTokenExpired = "expired"
  15. )
  16. func Auth(authKey string, session Session) gin.HandlerFunc {
  17. return func(ctx *gin.Context) {
  18. var tokenFromCookie, tokenFromHeader string
  19. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  20. if err == http.ErrNoCookie {
  21. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  22. }
  23. if tokenFromHeader == "" {
  24. tokenFromHeader = "Bearer " + tokenFromCookie
  25. }
  26. if len(tokenFromHeader) < 8 {
  27. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  28. return
  29. }
  30. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  31. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  32. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  33. }
  34. return []byte(authKey), nil
  35. })
  36. if err != nil || !token.Valid {
  37. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  38. return
  39. }
  40. if !session.IsExistsJwtToken(token.Raw) {
  41. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token expired by server"})
  42. return
  43. }
  44. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  45. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  46. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  47. } else {
  48. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderUserId].(float64) error"})
  49. return
  50. }
  51. } else {
  52. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
  53. return
  54. }
  55. }
  56. }
  57. func CloudTeamAuth(authKey string, session Session) gin.HandlerFunc {
  58. return func(ctx *gin.Context) {
  59. var tokenFromCookie, tokenFromHeader string
  60. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  61. if err == http.ErrNoCookie {
  62. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  63. }
  64. if tokenFromHeader == "" {
  65. tokenFromHeader = "Bearer " + tokenFromCookie
  66. }
  67. if len(tokenFromHeader) < 8 {
  68. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  69. return
  70. }
  71. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  72. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  73. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  74. }
  75. return []byte(authKey), nil
  76. })
  77. if err != nil || !token.Valid {
  78. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  79. return
  80. }
  81. if !session.IsExistsJwtToken(token.Raw) {
  82. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token expired by server"})
  83. return
  84. }
  85. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  86. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  87. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  88. } else {
  89. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderUserId].(float64) error"})
  90. return
  91. }
  92. if tid, ok := mapClaims[CtxRequestHeaderTeamId].(float64); ok {
  93. ctx.Set(CtxRequestHeaderTeamId, int64(tid))
  94. } else {
  95. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderTeamId].(float64) error"})
  96. return
  97. }
  98. if rid, ok := mapClaims[CtxRequestHeaderRoleId].(float64); ok {
  99. ctx.Set(CtxRequestHeaderRoleId, int64(rid))
  100. } else {
  101. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderRoleId].(float64) error"})
  102. return
  103. }
  104. } else {
  105. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
  106. return
  107. }
  108. }
  109. }