2020-07-05 01:02:57 +02:00
|
|
|
package route
|
2020-04-10 04:40:22 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2020-04-20 05:02:55 +02:00
|
|
|
"github.com/google/uuid"
|
2020-07-05 01:02:57 +02:00
|
|
|
"github.com/jordanknott/project-citadel/api/internal/auth"
|
2020-04-10 04:40:22 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
func AuthenticationMiddleware(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
bearerTokenRaw := r.Header.Get("Authorization")
|
|
|
|
splitToken := strings.Split(bearerTokenRaw, "Bearer")
|
|
|
|
if len(splitToken) != 2 {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
accessTokenString := strings.TrimSpace(splitToken[1])
|
2020-07-05 01:02:57 +02:00
|
|
|
accessClaims, err := auth.ValidateAccessToken(accessTokenString)
|
2020-04-10 04:40:22 +02:00
|
|
|
if err != nil {
|
2020-07-05 01:02:57 +02:00
|
|
|
if _, ok := err.(*auth.ErrExpiredToken); ok {
|
2020-06-13 00:21:58 +02:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2020-04-10 04:40:22 +02:00
|
|
|
w.Write([]byte(`{
|
2020-04-10 05:27:57 +02:00
|
|
|
"data": {},
|
2020-04-10 04:40:22 +02:00
|
|
|
"errors": [
|
|
|
|
{
|
|
|
|
"extensions": {
|
|
|
|
"code": "UNAUTHENTICATED"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}`))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Error(err)
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-20 05:02:55 +02:00
|
|
|
userID, err := uuid.Parse(accessClaims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), "userID", userID)
|
2020-04-10 04:40:22 +02:00
|
|
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
}
|