Skip to content

Instantly share code, notes, and snippets.

@nxadm
Created July 1, 2021 20:31
Show Gist options
  • Save nxadm/fa84f6bfb1b5fcee6108d15ca858a2dc to your computer and use it in GitHub Desktop.
Save nxadm/fa84f6bfb1b5fcee6108d15ca858a2dc to your computer and use it in GitHub Desktop.
// jwtInspectMiddleware checks if a token is valid (signature and not issued before
// a not-before date) and sets requester and owners in the context.
func (client *Client) jwtInspectMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
var (
ok bool
claims jwt.MapClaims
)
token, ok := c.Get("user").(*jwt.Token)
if !ok || token == nil {
reason := "no token"
outputJSONSStatus(fmt.Sprintf("failed login (%s)", reason), false)
return echo.NewHTTPError(http.StatusUnauthorized, reason)
}
ok = false
if token.Claims != nil {
claims, ok = token.Claims.(jwt.MapClaims)
}
if !ok {
reason := "no claims"
outputJSONSStatus(fmt.Sprintf("failed login (%s)", reason), false)
return echo.NewHTTPError(http.StatusUnauthorized, reason)
}
requester, owners, err := client.getRequestInfo(claims)
if err != nil {
reason := err.Error()
outputJSONSStatus(fmt.Sprintf("failed login (%s)", reason), false)
return echo.NewHTTPError(http.StatusUnauthorized, reason)
}
c.Set("requester", requester)
c.Set("owners", owners)
outputJSONSStatus(fmt.Sprintf("successful login for %#v", claims), false)
return next(c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment