// Copyright (C) 2026 Dcntrlized // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . package web import ( "net/http" "os" "strconv" ) const ( accessCookie = "dcntrlized_access" refreshCookie = "dcntrlized_refresh" cookiePath = "/web" ) func cookieSecure() bool { return os.Getenv(EnvCookieSecure) == "true" } func maxAge(env string, def int) int { if v := os.Getenv(env); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 0 { return n } } return def } func sessionCookie(name, value string, age int) *http.Cookie { return &http.Cookie{ Name: name, Value: value, Path: cookiePath, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: cookieSecure(), MaxAge: age, } } func setSessionCookies(w http.ResponseWriter, access, refresh string) { http.SetCookie(w, sessionCookie(accessCookie, access, maxAge(EnvAccessMaxAge, DefaultAccessMaxAge))) http.SetCookie(w, sessionCookie(refreshCookie, refresh, maxAge(EnvRefreshMaxAge, DefaultRefreshMaxAge))) } func clearSessionCookies(w http.ResponseWriter) { for _, name := range []string{accessCookie, refreshCookie} { http.SetCookie(w, &http.Cookie{ Name: name, Value: "", Path: cookiePath, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: cookieSecure(), MaxAge: -1, }) } }