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

@ -33,6 +33,8 @@ type LocalHandler struct {
router chi.Router router chi.Router
algo jwa.KeyAlgorithm algo jwa.KeyAlgorithm
key jwk.Key key jwk.Key
cookieDomain string
cookieDuration time.Duration
accounts map[string]LocalAccount accounts map[string]LocalAccount
} }
@ -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: "/",
}) })
@ -168,6 +173,8 @@ func NewLocalHandler(algo jwa.KeyAlgorithm, key jwk.Key, funcs ...LocalHandlerOp
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,8 +1,12 @@
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)
@ -11,6 +15,8 @@ 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
}
}