2020-07-05 01:02:57 +02:00
|
|
|
package route
|
2020-04-10 04:40:22 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
|
2020-04-20 05:02:55 +02:00
|
|
|
"github.com/google/uuid"
|
2021-04-29 04:32:19 +02:00
|
|
|
"github.com/jordanknott/taskcafe/internal/db"
|
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 {
|
2021-04-29 04:32:19 +02:00
|
|
|
repo db.Repository
|
2020-09-13 01:03:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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()
|
2021-04-29 04:32:19 +02:00
|
|
|
foundToken := true
|
|
|
|
tokenRaw := ""
|
2021-11-02 20:45:05 +01:00
|
|
|
|
|
|
|
token := r.Header.Get("Authorization")
|
|
|
|
if token != "" {
|
|
|
|
tokenRaw = token
|
|
|
|
} else {
|
|
|
|
foundToken = false
|
2021-04-29 04:32:19 +02:00
|
|
|
}
|
2021-11-02 20:45:05 +01:00
|
|
|
|
2021-04-29 04:32:19 +02:00
|
|
|
if !foundToken {
|
2021-11-02 20:45:05 +01:00
|
|
|
c, err := r.Cookie("authToken")
|
|
|
|
if err != nil {
|
|
|
|
if err == http.ErrNoCookie {
|
|
|
|
log.WithError(err).Error("error while fetching authToken")
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
log.WithError(err).Error("error while fetching authToken")
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
2021-04-29 04:32:19 +02:00
|
|
|
}
|
|
|
|
tokenRaw = c.Value
|
2020-04-10 04:40:22 +02:00
|
|
|
}
|
2021-05-01 05:55:37 +02:00
|
|
|
authTokenID, err := uuid.Parse(tokenRaw)
|
|
|
|
ctx := r.Context()
|
|
|
|
if err == nil {
|
|
|
|
token, err := m.repo.GetAuthTokenByID(r.Context(), authTokenID)
|
|
|
|
if err == nil {
|
2021-11-02 20:45:05 +01:00
|
|
|
log.WithField("tokenID", authTokenID).WithField("userID", token.UserID).Info("setting auth token")
|
2021-05-01 05:55:37 +02:00
|
|
|
ctx = context.WithValue(ctx, utils.UserIDKey, token.UserID)
|
|
|
|
}
|
2020-04-10 04:40:22 +02:00
|
|
|
}
|
|
|
|
|
2021-04-29 04:32:19 +02:00
|
|
|
// 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))
|
|
|
|
})
|
|
|
|
}
|