alai-server/backend/middlewares/auth.go

41 lines
988 B
Go
Raw Normal View History

2022-06-29 21:26:05 -04:00
package middlewares
import (
2023-02-09 01:07:31 -03:00
"context"
2022-06-29 21:26:05 -04:00
"errors"
"net/http"
"strings"
2022-07-22 23:00:31 -04:00
"git.cromer.cl/Proyecto-Titulo/alai-server/backend/utils"
2022-06-29 21:26:05 -04:00
"github.com/julienschmidt/httprouter"
)
2023-02-09 01:07:31 -03:00
type contextKey string
const JWTContextKey contextKey = "JWTClaims"
2022-06-29 21:26:05 -04:00
func Authenticate(handle httprouter.Handle) httprouter.Handle {
return func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
reqToken := request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
utils.JSONErrorOutput(writer, http.StatusUnauthorized, errors.New("no token received").Error())
return
}
tokenString := splitToken[1]
2023-02-09 01:07:31 -03:00
claims, err := utils.ValidateToken(tokenString)
2022-06-29 21:26:05 -04:00
if err != nil {
utils.JSONErrorOutput(writer, http.StatusUnauthorized, err.Error())
return
}
2023-02-09 01:07:31 -03:00
ctx := request.Context()
ctx = context.WithValue(ctx, JWTContextKey, claims)
request = request.WithContext(ctx)
2022-06-29 21:26:05 -04:00
handle(writer, request, params)
}
}