Make auth a hupper (jwtsecret can be reconfigured and HUPped)
This commit is contained in:
parent
51c105a1f9
commit
5b5b02b5fd
3 changed files with 23 additions and 3 deletions
|
@ -33,10 +33,17 @@ type Auth struct {
|
||||||
|
|
||||||
// NewAuthenticator creates a new Authenticator with the provided config.
|
// NewAuthenticator creates a new Authenticator with the provided config.
|
||||||
func NewAuthenticator(cfg config.Auth) *Auth {
|
func NewAuthenticator(cfg config.Auth) *Auth {
|
||||||
return &Auth{
|
a := &Auth{
|
||||||
jwt: jwtauth.New("HS256", []byte(cfg.JWTSecret), nil),
|
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
}
|
}
|
||||||
|
a.initJWT()
|
||||||
|
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Auth) HUP(cfg *config.Config) {
|
||||||
|
a.cfg = cfg.Auth
|
||||||
|
a.initJWT()
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
|
@ -46,13 +46,25 @@ func (a *Auth) Authenticated(r *http.Request) (claims, bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Auth) VerifyMiddleware() func(http.Handler) http.Handler {
|
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 {
|
func (a *Auth) AuthMiddleware() func(http.Handler) http.Handler {
|
||||||
return jwtauth.Authenticator(a.jwt)
|
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) {
|
func (a *Auth) Login(ctx context.Context, username, password string) (token string, err error) {
|
||||||
q := database.New(database.FromCtx(ctx))
|
q := database.New(database.FromCtx(ctx))
|
||||||
users, err := q.GetUsers(ctx)
|
users, err := q.GetUsers(ctx)
|
||||||
|
|
|
@ -16,6 +16,7 @@ type hupper interface {
|
||||||
func (s *Server) huppers() []hupper {
|
func (s *Server) huppers() []hupper {
|
||||||
return []hupper{
|
return []hupper{
|
||||||
s.logger,
|
s.logger,
|
||||||
|
s.auth,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue