Merge pull request 'FEAT: Environment and Cookie Update' (#31) from dev into master
Some checks failed
Deploy application with Docker / build_and_deploy (push) Has been cancelled

Reviewed-on: #31

Seems to be working properly.
This commit is contained in:
Hayden Hargreaves 2025-07-23 18:22:42 -07:00
commit b98bf5ce39
4 changed files with 95 additions and 32 deletions

View File

@ -37,15 +37,16 @@ func GoogleCallback(ctx *gin.Context) {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
} else { } else {
// TODO: Update these values when using a real domain. Maybe an ENV? // TODO: Update these values when using a real domain. Maybe an ENV?
ctx.SetCookie( domain.SetCookie(ctx, "jwt_token", jwt, time.Hour*24*7)
"jwt_token", // ctx.SetCookie(
jwt, // "jwt_token",
int(time.Now().Add(7*24*time.Hour).Sub(time.Now()).Seconds()), // jwt,
"/", // int(time.Now().Add(7*24*time.Hour).Sub(time.Now()).Seconds()),
"", // TODO: Real live domain // "/",
false, // TODO: True in prod // "", // TODO: Real live domain
true, // false, // TODO: True in prod
) // true,
// )
// ctx.JSON(http.StatusOK, gin.H{"jwt": jwt, "googleUserInfo": googleUserInfo, "dbUser": dbUser}) // ctx.JSON(http.StatusOK, gin.H{"jwt": jwt, "googleUserInfo": googleUserInfo, "dbUser": dbUser})
_ = dbUser _ = dbUser
@ -60,8 +61,10 @@ func GoogleCallback(ctx *gin.Context) {
// This route will direct the user back to the home page. // This route will direct the user back to the home page.
func Logout(ctx *gin.Context) { func Logout(ctx *gin.Context) {
// TODO: Use same values as the GoogleCallback function // TODO: Use same values as the GoogleCallback function
ctx.SetCookie("jwt_token", "", -1, "/", "", false, true) // TODO: Update settings domain.SetCookie(ctx, "jwt_token", "", -1)
ctx.SetCookie("search-filters", "", -1, "/", "", false, true) domain.SetCookie(ctx, "search-filters", "", -1)
// ctx.SetCookie("jwt_token", "", -1, "/", "", false, true) // TODO: Update settings
// ctx.SetCookie("search-filters", "", -1, "/", "", false, true)
ctx.Redirect(http.StatusSeeOther, domain.WEB_HOME) ctx.Redirect(http.StatusSeeOther, domain.WEB_HOME)
} }

View File

@ -58,15 +58,16 @@ func SearchRecipes(ctx *gin.Context) {
// Set the filters into the cookies, so they can be reloaded // Set the filters into the cookies, so they can be reloaded
if bytes, err := json.Marshal(filters); err == nil { if bytes, err := json.Marshal(filters); err == nil {
ctx.SetCookie( domain.SetCookie(ctx, "search-filters", string(bytes), time.Hour*24)
"search-filters", // ctx.SetCookie(
string(bytes), // "search-filters",
int(time.Now().Add(24*time.Hour).Sub(time.Now()).Seconds()), // string(bytes),
"/", // int(time.Now().Add(24*time.Hour).Sub(time.Now()).Seconds()),
"", // TODO: Need an actual domain // "/",
false, // TODO: True in prod // "", // TODO: Need an actual domain
true, // false, // TODO: True in prod
) // true,
// )
} }
redirect := ctx.PostForm("redirect") redirect := ctx.PostForm("redirect")
@ -108,15 +109,16 @@ func SearchRecipesFavorites(ctx *gin.Context) {
// Set the filters into the cookies, so they can be reloaded // Set the filters into the cookies, so they can be reloaded
if bytes, err := json.Marshal(filters); err == nil { if bytes, err := json.Marshal(filters); err == nil {
ctx.SetCookie( domain.SetCookie(ctx, "search-filters", string(bytes), time.Hour*24)
"search-filters", // ctx.SetCookie(
string(bytes), // "search-filters",
int(time.Now().Add(24*time.Hour).Sub(time.Now()).Seconds()), // string(bytes),
"/", // int(time.Now().Add(24*time.Hour).Sub(time.Now()).Seconds()),
"", // TODO: Need an actual domain // "/",
false, // TODO: True in prod // "", // TODO: Need an actual domain
true, // false, // TODO: True in prod
) // true,
// )
} }
// TODO: Error here if they're not logged in? // TODO: Error here if they're not logged in?

View File

@ -28,9 +28,6 @@ type Server struct {
// Init initializes the server with the provided port. CORS settings are defined here. // Init initializes the server with the provided port. CORS settings are defined here.
// A pointer to a server object is returned which allows for method chaining. // A pointer to a server object is returned which allows for method chaining.
func Init(port int) *Server { func Init(port int) *Server {
// TODO: Set this to release in prod
gin.SetMode(gin.DebugMode)
server := &Server{ server := &Server{
Router: gin.Default(), Router: gin.Default(),
port: port, port: port,
@ -66,6 +63,14 @@ func (s *Server) Setup() *Server {
panic("Environment configuration is nil, crashing.") panic("Environment configuration is nil, crashing.")
} }
if cfg.Environment == "dev" {
gin.SetMode(gin.DebugMode)
} else if cfg.Environment == "prod" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.TestMode)
}
// SETUP GOOGLE AUTH // SETUP GOOGLE AUTH
var ( var (
redirectUrl string = fmt.Sprintf("%s%s", cfg.Domain, domain.API_AUTH_CALLBACK) redirectUrl string = fmt.Sprintf("%s%s", cfg.Domain, domain.API_AUTH_CALLBACK)

View File

@ -3,6 +3,7 @@ package domain
import ( import (
"fmt" "fmt"
"os" "os"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
@ -50,6 +51,10 @@ func IsLoggedIn(ctx *gin.Context) bool {
return id && email return id && email
} }
// LoadEnvironment loads the environment values from either an .env file or docker environment. In
// the event that required fields are not provided, an error will return and the caller should handle
// the missing value or panic. Toggles between 'dev', 'prod', etc are also handled by this method,
// the values can be access assuming they are the proper values based on the provided environment.
func LoadEnvironment() (*EnvironmentConfig, error) { func LoadEnvironment() (*EnvironmentConfig, error) {
err := godotenv.Load(".env") err := godotenv.Load(".env")
if err != nil { if err != nil {
@ -117,3 +122,51 @@ func LoadEnvironment() (*EnvironmentConfig, error) {
return cfg, nil return cfg, nil
} }
// 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 SetCookie(ctx *gin.Context, name, value string, duration time.Duration) {
deps := ctx.MustGet("deps").(*InjectedDependencies)
var (
path string = "/"
httpOnly bool = true
maxAge int
secure bool
domain string
)
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.Now().Add(duration).Sub(time.Now()).Seconds())
}
if deps.EnvironmentConfig.Environment == "prod" {
secure = true
domain = deps.EnvironmentConfig.Domain
} else if deps.EnvironmentConfig.Environment == "dev" {
secure = false
domain = deps.EnvironmentConfig.Domain
} else {
// Defaults
secure = false
domain = ""
}
ctx.SetCookie(name, value, maxAge, path, domain, secure, httpOnly)
}