51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package rest
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/domain"
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/router/rest/internal/model"
|
|
)
|
|
|
|
type authCtxKey struct{}
|
|
|
|
func authMiddleware(verifier APIKeyVerifier) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
key := r.Header.Get("X-API-Key")
|
|
if key == "" {
|
|
renderJSON(w, http.StatusUnauthorized, model.ErrorResp{
|
|
Error: model.APIError{
|
|
Code: "unauthorized",
|
|
Message: "invalid API key",
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
u, err := verifier.Verify(r.Context(), key)
|
|
if err != nil {
|
|
renderJSON(w, http.StatusUnauthorized, model.ErrorResp{
|
|
Error: model.APIError{
|
|
Code: "unauthorized",
|
|
Message: "invalid API key",
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r.WithContext(userToContext(r.Context(), u)))
|
|
})
|
|
}
|
|
}
|
|
|
|
func userToContext(ctx context.Context, u domain.User) context.Context {
|
|
return context.WithValue(ctx, authCtxKey{}, u)
|
|
}
|
|
|
|
func userFromContext(ctx context.Context) (domain.User, bool) {
|
|
u, ok := ctx.Value(authCtxKey{}).(domain.User)
|
|
return u, ok
|
|
}
|