package server import ( "net/http" "time" "github.com/gin-gonic/gin" ) // SetCookie sets a cookie value with a duration provided. This function handles setting the security // configuration as well as the domain. These values are based on the EnvironmentConfig, therefore // the value should be set. Nothing is returned by this function, but the cookie will be set. // // This function can also be used to clear cookies, if a blank value ("") and invalid duration (-1) // is provided. // // If 0 is provided as the duration, then a session cookie is created, which will be cleared when // the browser is closed. func (s *Server) SetCookie(ctx *gin.Context, name, value string, duration time.Duration) { var ( path string = "/" httpOnly bool = false // NOTE: Should use false so React can see it! maxAge int ) if duration < 0 { // Delete the cookie maxAge = -1 } else if duration == 0 { // Session cookie, clears when browser is closed maxAge = 0 } else { // Normal calculation maxAge = int(time.Until(time.Now().Add(duration)).Seconds()) } switch s.deps.EnvironmentConfig.Environment { case "prod": // Cross-site between subdomains, HTTPS only ctx.SetSameSite(http.SameSiteNoneMode) ctx.SetCookie( name, value, maxAge, path, ".gophernest.net", // or your backend domain / parent true, // secure httpOnly, ) case "dev": // Local dev on http://localhost:PORT ctx.SetSameSite(http.SameSiteLaxMode) ctx.SetCookie( name, value, maxAge, path, "", // no Domain → default to current host false, // not secure on plain HTTP httpOnly, ) } // TODO: This whole system is stupid now // if s.deps.EnvironmentConfig.Environment == "prod" { // secure = true // // domain = "potion.gophernest" // // domain = s.deps.EnvironmentConfig.Domain // domain = ".gophernest.net" // // } else if s.deps.EnvironmentConfig.Environment == "dev" { // secure = false // // domain = s.deps.EnvironmentConfig.Domain // domain = "localhost" // } // // ctx.SetSameSite(http.SameSiteNoneMode) // ctx.SetCookie(name, value, maxAge, path, domain, secure, httpOnly) }