|
package auth |
|
|
|
import ( |
|
"net/http" |
|
"net/url" |
|
"strings" |
|
"time" |
|
|
|
"github.com/target/goalert/config" |
|
) |
|
|
|
|
|
func SetCookie(w http.ResponseWriter, req *http.Request, name, value string, isSession bool) { |
|
SetCookieAge(w, req, name, value, 0, isSession) |
|
} |
|
|
|
|
|
func SetCookieAge(w http.ResponseWriter, req *http.Request, name, value string, age time.Duration, isSession bool) { |
|
cfg := config.FromContext(req.Context()) |
|
u, err := url.Parse(cfg.PublicURL()) |
|
if err != nil { |
|
panic(err) |
|
} |
|
|
|
cookiePath := "/" |
|
secure := req.URL.Scheme == "https" |
|
if cfg.ShouldUsePublicURL() { |
|
cookiePath = strings.TrimSuffix(u.Path, "/") + "/" |
|
secure = u.Scheme == "https" |
|
} |
|
|
|
|
|
|
|
sameSite := http.SameSiteLaxMode |
|
if isSession { |
|
sameSite = http.SameSiteStrictMode |
|
} |
|
|
|
http.SetCookie(w, &http.Cookie{ |
|
HttpOnly: true, |
|
Secure: secure, |
|
Name: name, |
|
|
|
Path: cookiePath, |
|
Value: value, |
|
MaxAge: int(age.Seconds()), |
|
|
|
SameSite: sameSite, |
|
}) |
|
} |
|
|
|
|
|
func ClearCookie(w http.ResponseWriter, req *http.Request, name string, isSession bool) { |
|
SetCookieAge(w, req, name, "", -time.Second, isSession) |
|
} |
|
|