Skip to content

Commit

Permalink
Refactor token extraction (#1334)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonAlling authored and Andres Martinez Gotor committed Dec 2, 2019
1 parent b1ec4f7 commit dfd03f8
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions pkg/auth/authgate.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ type contextKey int
// UserKey is the context key for the User data in the request context
const UserKey contextKey = 0

// tokenPrefix is the string preceding the token in the Authorization header.
const tokenPrefix = "Bearer "

// AuthGate implements middleware to check if the user is logged in before continuing
func AuthGate() negroni.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
authHeader := strings.Split(req.Header.Get("Authorization"), "Bearer ")
if len(authHeader) != 2 {
token := ExtractToken(req.Header.Get("Authorization"))
if token == "" {
response.NewErrorResponse(http.StatusUnauthorized, "Unauthorized").Write(w)
return
}
userAuth, err := NewAuth(authHeader[1])
userAuth, err := NewAuth(token)
if err != nil {
response.NewErrorResponse(http.StatusInternalServerError, err.Error()).Write(w)
return
Expand All @@ -37,3 +40,12 @@ func AuthGate() negroni.HandlerFunc {
next(w, req.WithContext(ctx))
}
}

// ExtractToken extracts the token from a correctly formatted Authorization header.
func ExtractToken(headerValue string) string {
if strings.HasPrefix(headerValue, tokenPrefix) {
return headerValue[len(tokenPrefix):]
} else {
return ""
}
}

0 comments on commit dfd03f8

Please sign in to comment.