func (csrf *CSRFMiddleware) Handle(next clevergo.Handler) clevergo.Handler { return clevergo.HandlerFunc(func(ctx *clevergo.Context) { var trueToken string if ctx.Session == nil { err := ctx.GetSession() if err != nil { panic(err) } } token, err := ctx.Session.Get(csrf.SessionKey) if (err != nil) || (token == nil) { trueToken = stringutil.GenerateRandomString(csrf.Len) } else { trueToken = token.(string) } if _, safe := csrf.SafeMethods[ctx.Request.Method]; !safe { if (len(trueToken) != csrf.MaskLen) && !ValidateCSRFToken(csrf.MaskLen, ctx.Request.PostFormValue(csrf.FormKey), trueToken) && !ValidateCSRFToken(csrf.MaskLen, ctx.Request.Header.Get(csrf.HeaderKey), trueToken) { ctx.Response.SetStatus(http.StatusBadRequest) ctx.Response.SetBody(csrf.ErrorInvalid) return } } else { csrfToken := GenerateCSRFToken(csrf.MaskLen, trueToken) ctx.Values[csrf.Key] = csrfToken ctx.Session.Set(csrf.SessionKey, trueToken) } next.Handle(ctx) }) }
func (jm *JWTMiddleware) Handle(next clevergo.Handler) clevergo.Handler { return clevergo.HandlerFunc(func(ctx *clevergo.Context) { if _, canSkip := ctx.SkipMiddlewares[JWTMiddlewareID]; canSkip { next.Handle(ctx) return } // Try to get JWT raw token from URL query string. rawToken := ctx.Request.FormValue(jm.urlKey) if len(rawToken) < 0 { // Try to get JWT raw token from POST FORM. rawToken = ctx.Request.PostFormValue(jm.formKey) if len(rawToken) < 0 { // Try to get JWT raw token from Header. if ah := ctx.Request.Header.Get("Authorization"); ah != "" { // Should be a bearer token if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " { rawToken = ah[7:] } } } } // Check raw token is valid. if len(rawToken) == 0 { ctx.Response.Unauthorized() return } // Get JWT by raw token token, err := jwt.NewTokenByRaw(ctx.JWT(), rawToken) if err != nil { ctx.Response.Unauthorized(err.Error()) return } // Validate JWT. if err = token.Validate(); err != nil { ctx.Response.Unauthorized(err.Error()) return } ctx.Token = token // Validate successfully. next.Handle(ctx) }) }