diff --git a/cookies/delete.go b/cookies/delete.go new file mode 100644 index 0000000..188d5ad --- /dev/null +++ b/cookies/delete.go @@ -0,0 +1,19 @@ +package cookies + +import ( + "net/http" + "time" +) + +// Tell the browser to delete the cookie matching the name provided +// Path must match the original set cookie for it to delete +func DeleteCookie(w http.ResponseWriter, name string, path string) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: "", + Path: path, + Expires: time.Unix(0, 0), // Expire in the past + MaxAge: -1, // Immediately expire + HttpOnly: true, + }) +} diff --git a/cookies/go.mod b/cookies/go.mod new file mode 100644 index 0000000..5caa714 --- /dev/null +++ b/cookies/go.mod @@ -0,0 +1,3 @@ +module git.haelnorr.com/h/golib/cookies + +go 1.25.5 diff --git a/cookies/pagefrom.go b/cookies/pagefrom.go new file mode 100644 index 0000000..fa4cb0b --- /dev/null +++ b/cookies/pagefrom.go @@ -0,0 +1,36 @@ +package cookies + +import ( + "net/http" + "net/url" +) + +// Check the value of "pagefrom" cookie, delete the cookie, and return the value +func CheckPageFrom(w http.ResponseWriter, r *http.Request) string { + pageFromCookie, err := r.Cookie("pagefrom") + if err != nil { + return "/" + } + pageFrom := pageFromCookie.Value + DeleteCookie(w, pageFromCookie.Name, pageFromCookie.Path) + return pageFrom +} + +// Check the referer of the request, and if it matches the trustedHost, set +// the "pagefrom" cookie as the Path of the referer +func SetPageFrom(w http.ResponseWriter, r *http.Request, trustedHost string) { + referer := r.Referer() + parsedURL, err := url.Parse(referer) + if err != nil { + return + } + var pageFrom string + if parsedURL.Path == "" || parsedURL.Host != trustedHost { + pageFrom = "/" + } else if parsedURL.Path == "/login" || parsedURL.Path == "/register" { + return + } else { + pageFrom = parsedURL.Path + } + SetCookie(w, "pagefrom", "/", pageFrom, 0) +} diff --git a/cookies/set.go b/cookies/set.go new file mode 100644 index 0000000..b5842cf --- /dev/null +++ b/cookies/set.go @@ -0,0 +1,23 @@ +package cookies + +import ( + "net/http" +) + +// Set a cookie with the given name, path and value. maxAge directly relates +// to cookie MaxAge (0 for no max age, >0 for TTL in seconds) +func SetCookie( + w http.ResponseWriter, + name string, + path string, + value string, + maxAge int, +) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: value, + Path: path, + HttpOnly: true, + MaxAge: maxAge, + }) +}