add initial auth0 module
This commit is contained in:
89
auth/auth0/auth0.go
Normal file
89
auth/auth0/auth0.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package auth0
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"dstar/auth0/authenticator"
|
||||
)
|
||||
|
||||
type Logger interface {
|
||||
Debug(msg string, args ...any)
|
||||
Info(msg string, args ...any)
|
||||
Error(msg string, args ...any)
|
||||
}
|
||||
|
||||
type SessionManager interface {
|
||||
Get(ctx context.Context, key string) any
|
||||
Put(ctx context.Context, key string, value any) error
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Logger Logger
|
||||
Sessions SessionManager
|
||||
}
|
||||
|
||||
type Option func(deps *Config)
|
||||
|
||||
func WithLogger(l Logger) Option {
|
||||
return func(cfg *Config) {
|
||||
cfg.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessions(s SessionManager) Option {
|
||||
return func(cfg *Config) {
|
||||
cfg.Sessions = s
|
||||
}
|
||||
}
|
||||
|
||||
type deps struct {
|
||||
auth *authenticator.Authenticator
|
||||
logoutBase *url.URL
|
||||
log Logger
|
||||
sessions SessionManager
|
||||
}
|
||||
|
||||
func New(opts ...Option) (func(chi.Router), Middleware, error) {
|
||||
cfg := Config{}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
|
||||
if cfg.Logger == nil {
|
||||
return nil, nil, ErrNilLogger
|
||||
}
|
||||
if cfg.Sessions == nil {
|
||||
return nil, nil, ErrNilSessions
|
||||
}
|
||||
|
||||
auth, err := authenticator.New()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
logoutURL, err := url.Parse(auth.LogoutURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("unable to parse logout URL: %w", err)
|
||||
}
|
||||
|
||||
d := &deps{
|
||||
log: cfg.Logger,
|
||||
logoutBase: logoutURL,
|
||||
sessions: cfg.Sessions,
|
||||
auth: auth,
|
||||
}
|
||||
|
||||
mw := func(next http.Handler) http.Handler {
|
||||
return authenticatedMiddleware(d, next)
|
||||
}
|
||||
|
||||
return func(r chi.Router) {
|
||||
Register(r, d)
|
||||
}, mw, nil
|
||||
}
|
||||
Reference in New Issue
Block a user