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

auth.go 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if tid, ok := mapClaims[CtxRequestHeaderTeamId].(float64); ok {
  52. ctx.Set(CtxRequestHeaderTeamId, int64(tid))
  53. } else {
  54. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderTeamId].(float64) error"})
  55. return
  56. }
  57. if rid, ok := mapClaims[CtxRequestHeaderRoleId].(float64); ok {
  58. ctx.Set(CtxRequestHeaderRoleId, int64(rid))
  59. } else {
  60. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderRoleId].(float64) error"})
  61. return
  62. }
  63. } else {
  64. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
  65. return
  66. }
  67. }
  68. }