feat(auth,local_handler): cookie configuration

This commit is contained in:
wpetit 2023-03-28 20:37:57 +02:00
parent e09de0b0a4
commit 1996f4dc56
2 changed files with 31 additions and 11 deletions

View File

@ -30,10 +30,12 @@ func init() {
} }
type LocalHandler struct { type LocalHandler struct {
router chi.Router router chi.Router
algo jwa.KeyAlgorithm algo jwa.KeyAlgorithm
key jwk.Key key jwk.Key
accounts map[string]LocalAccount cookieDomain string
cookieDuration time.Duration
accounts map[string]LocalAccount
} }
func (h *LocalHandler) initRouter(prefix string) { func (h *LocalHandler) initRouter(prefix string) {
@ -119,7 +121,9 @@ func (h *LocalHandler) handleForm(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{ cookie := http.Cookie{
Name: auth.CookieName, Name: auth.CookieName,
Value: string(token), Value: string(token),
Domain: h.cookieDomain,
HttpOnly: false, HttpOnly: false,
Expires: time.Now().Add(h.cookieDuration),
Path: "/", Path: "/",
} }
@ -134,6 +138,7 @@ func (h *LocalHandler) handleLogout(w http.ResponseWriter, r *http.Request) {
Value: "", Value: "",
HttpOnly: false, HttpOnly: false,
Expires: time.Unix(0, 0), Expires: time.Unix(0, 0),
Domain: h.cookieDomain,
Path: "/", Path: "/",
}) })
@ -165,9 +170,11 @@ func NewLocalHandler(algo jwa.KeyAlgorithm, key jwk.Key, funcs ...LocalHandlerOp
} }
handler := &LocalHandler{ handler := &LocalHandler{
algo: algo, algo: algo,
key: key, key: key,
accounts: toAccountsMap(opts.Accounts), accounts: toAccountsMap(opts.Accounts),
cookieDomain: opts.CookieDomain,
cookieDuration: opts.CookieDuration,
} }
handler.initRouter(opts.RoutePrefix) handler.initRouter(opts.RoutePrefix)

View File

@ -1,16 +1,22 @@
package http package http
import "time"
type LocalHandlerOptions struct { type LocalHandlerOptions struct {
RoutePrefix string RoutePrefix string
Accounts []LocalAccount Accounts []LocalAccount
CookieDomain string
CookieDuration time.Duration
} }
type LocalHandlerOptionFunc func(*LocalHandlerOptions) type LocalHandlerOptionFunc func(*LocalHandlerOptions)
func defaultLocalHandlerOptions() *LocalHandlerOptions { func defaultLocalHandlerOptions() *LocalHandlerOptions {
return &LocalHandlerOptions{ return &LocalHandlerOptions{
RoutePrefix: "", RoutePrefix: "",
Accounts: make([]LocalAccount, 0), Accounts: make([]LocalAccount, 0),
CookieDomain: "",
CookieDuration: 24 * time.Hour,
} }
} }
@ -25,3 +31,10 @@ func WithRoutePrefix(prefix string) LocalHandlerOptionFunc {
opts.RoutePrefix = prefix opts.RoutePrefix = prefix
} }
} }
func WithCookieOptions(domain string, duration time.Duration) LocalHandlerOptionFunc {
return func(opts *LocalHandlerOptions) {
opts.CookieDomain = domain
opts.CookieDuration = duration
}
}