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-08-07 03:50:35 +02:00
|
|
|
"github.com/jordanknott/taskcafe/internal/auth"
|
2020-08-22 06:08:30 +02:00
|
|
|
"github.com/jordanknott/taskcafe/internal/utils"
|
2020-04-10 04:40:22 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2020-08-21 01:11:24 +02:00
|
|
|
// AuthenticationMiddleware is a middleware that requires a valid JWT token to be passed via the Authorization header
|
2020-09-13 01:03:17 +02:00
|
|
|
type AuthenticationMiddleware struct {
|
|
|
|
jwtKey []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// Middleware returns the middleware handler
|
|
|
|
func (m *AuthenticationMiddleware) Middleware(next http.Handler) http.Handler {
|
2020-04-10 04:40:22 +02:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2020-10-21 01:52:09 +02:00
|
|
|
requestID := uuid.New()
|
2020-04-10 04:40:22 +02:00
|
|
|
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-09-13 01:03:17 +02:00
|
|
|
accessClaims, err := auth.ValidateAccessToken(accessTokenString, m.jwtKey)
|
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-07-17 02:40:23 +02:00
|
|
|
var userID uuid.UUID
|
|
|
|
if accessClaims.Restricted == auth.InstallOnly {
|
|
|
|
userID = uuid.New()
|
|
|
|
} else {
|
|
|
|
userID, err = uuid.Parse(accessClaims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("middleware access token userID parse")
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2020-04-20 05:02:55 +02:00
|
|
|
}
|
2020-08-22 06:08:30 +02:00
|
|
|
ctx := context.WithValue(r.Context(), utils.UserIDKey, userID)
|
|
|
|
ctx = context.WithValue(ctx, utils.RestrictedModeKey, accessClaims.Restricted)
|
|
|
|
ctx = context.WithValue(ctx, utils.OrgRoleKey, accessClaims.OrgRole)
|
2020-10-21 01:52:09 +02:00
|
|
|
ctx = context.WithValue(ctx, utils.ReqIDKey, requestID)
|
2020-04-10 04:40:22 +02:00
|
|
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
}
|