|
| 1 | +package jwt |
| 2 | + |
| 3 | +import ( |
| 4 | + "agones-minecraft/resource/api/v1/errors" |
| 5 | + "agones-minecraft/services/auth/jwt" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/gin-gonic/gin" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + HeaderKey string = "Authorization" |
| 14 | + ContextKey string = "JWT_SUBJECT" |
| 15 | +) |
| 16 | + |
| 17 | +// returns middleware that will parse JWT token in Authorization header, validate it, verify it |
| 18 | +// and set the userId in the current context as "JWT_SUBJECT" |
| 19 | +func Authorizer() gin.HandlerFunc { |
| 20 | + return func(c *gin.Context) { |
| 21 | + v := c.GetHeader(HeaderKey) |
| 22 | + tokenString := strings.TrimSpace(strings.TrimPrefix(v, "Bearer")) |
| 23 | + |
| 24 | + if tokenString == "" { |
| 25 | + c.Errors = append(c.Errors, errors.NewUnauthorizedError(fmt.Errorf("missing access token in Authorization header"))) |
| 26 | + c.Abort() |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + token, err := jwt.ParseToken(tokenString) |
| 31 | + if err != nil { |
| 32 | + c.Errors = append(c.Errors, errors.NewUnauthorizedError(fmt.Errorf("unable to parse token"))) |
| 33 | + c.Abort() |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + val, _ := token.Get(jwt.RefreshKey) |
| 38 | + |
| 39 | + if val.(bool) { |
| 40 | + c.Errors = append(c.Errors, errors.NewUnauthorizedError(fmt.Errorf("token identified as refresh token"))) |
| 41 | + c.Abort() |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + if err := jwt.ValidateToken(token); err != nil { |
| 46 | + c.Errors = append(c.Errors, errors.NewUnauthorizedError(err)) |
| 47 | + c.Abort() |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + if err := jwt.VerifyAccessToken(tokenString); err != nil { |
| 52 | + c.Errors = append(c.Errors, errors.NewUnauthorizedError(fmt.Errorf("unable to verify access token"))) |
| 53 | + c.Abort() |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + // Set userId for request context |
| 58 | + c.Set(ContextKey, token.Subject()) |
| 59 | + |
| 60 | + c.Next() |
| 61 | + } |
| 62 | +} |
0 commit comments