homebox/backend/app/api/middleware.go

35 lines
1.1 KiB
Go
Raw Normal View History

2022-08-30 02:30:36 +00:00
package main
import (
"errors"
2022-08-30 02:30:36 +00:00
"net/http"
"strings"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/sys/validate"
"github.com/hay-kot/homebox/backend/pkgs/server"
2022-08-30 02:30:36 +00:00
)
// mwAuthToken is a middleware that will check the database for a stateful token
// and attach it to the request context with the user, or return a 401 if it doesn't exist.
func (a *app) mwAuthToken(next server.Handler) server.Handler {
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
2022-08-30 02:30:36 +00:00
requestToken := r.Header.Get("Authorization")
if requestToken == "" {
return validate.NewRequestError(errors.New("Authorization header is required"), http.StatusUnauthorized)
2022-08-30 02:30:36 +00:00
}
requestToken = strings.TrimPrefix(requestToken, "Bearer ")
2022-08-31 02:11:23 +00:00
usr, err := a.services.User.GetSelf(r.Context(), requestToken)
2022-08-30 02:30:36 +00:00
// Check the database for the token
if err != nil {
return validate.NewRequestError(errors.New("Authorization header is required"), http.StatusUnauthorized)
2022-08-30 02:30:36 +00:00
}
r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))
return next.ServeHTTP(w, r)
2022-08-30 02:30:36 +00:00
})
}