2022-08-30 02:30:36 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2022-10-30 02:15:35 +00:00
|
|
|
"errors"
|
2022-08-30 02:30:36 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2022-10-30 04:05:38 +00:00
|
|
|
"github.com/hay-kot/homebox/backend/internal/core/services"
|
2022-10-30 02:15:35 +00:00
|
|
|
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
2022-09-24 19:33:38 +00:00
|
|
|
"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.
|
2022-10-30 02:15:35 +00:00
|
|
|
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 == "" {
|
2022-10-30 02:15:35 +00:00
|
|
|
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 {
|
2022-10-30 02:15:35 +00:00
|
|
|
return validate.NewRequestError(errors.New("Authorization header is required"), http.StatusUnauthorized)
|
2022-08-30 02:30:36 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 23:52:13 +00:00
|
|
|
r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))
|
2022-10-30 02:15:35 +00:00
|
|
|
return next.ServeHTTP(w, r)
|
2022-08-30 02:30:36 +00:00
|
|
|
})
|
|
|
|
}
|