Make auth a hupper (jwtsecret can be reconfigured and HUPped)

This commit is contained in:
Daniel Ponte 2024-10-22 09:00:41 -04:00
parent 51c105a1f9
commit 5b5b02b5fd
3 changed files with 23 additions and 3 deletions

View file

@ -33,10 +33,17 @@ type Auth struct {
// NewAuthenticator creates a new Authenticator with the provided config.
func NewAuthenticator(cfg config.Auth) *Auth {
return &Auth{
jwt: jwtauth.New("HS256", []byte(cfg.JWTSecret), nil),
a := &Auth{
cfg: cfg,
}
a.initJWT()
return a
}
func (a *Auth) HUP(cfg *config.Config) {
a.cfg = cfg.Auth
a.initJWT()
}
var (

View file

@ -46,13 +46,25 @@ func (a *Auth) Authenticated(r *http.Request) (claims, bool) {
}
func (a *Auth) VerifyMiddleware() func(http.Handler) http.Handler {
return jwtauth.Verifier(a.jwt)
return func(next http.Handler) http.Handler {
hfn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token, err := jwtauth.VerifyRequest(a.jwt, r, jwtauth.TokenFromHeader, jwtauth.TokenFromCookie)
ctx = jwtauth.NewContext(ctx, token, err)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(hfn)
}
}
func (a *Auth) AuthMiddleware() func(http.Handler) http.Handler {
return jwtauth.Authenticator(a.jwt)
}
func (a *Auth) initJWT() {
a.jwt = jwtauth.New("HS256", []byte(a.cfg.JWTSecret), nil)
}
func (a *Auth) Login(ctx context.Context, username, password string) (token string, err error) {
q := database.New(database.FromCtx(ctx))
users, err := q.GetUsers(ctx)

View file

@ -16,6 +16,7 @@ type hupper interface {
func (s *Server) huppers() []hupper {
return []hupper{
s.logger,
s.auth,
}
}