Potion/internal/app/handlers/user_handler.go
Hayden Hargreaves eccc4885cc (FIX): This should be the last of the user nil deref updates!
I believe this can mark the tasks about fixing the deref issues with
auth completed. Will test in production to find out!
2025-07-27 14:11:26 -07:00

86 lines
2.2 KiB
Go

package handlers
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
domain "github.com/haydenhargreaves/Potion/internal/domain/server"
)
func GetUserRecipes(ctx *gin.Context) {
deps := ctx.MustGet("deps").(*domain.InjectedDependencies)
// Ensure user is logged in with a valid account
user := deps.UserService.GetAuthenicatedUser(ctx)
if user == nil {
// Log (stale) user out
domain.SetCookie(ctx, "jwt_token", "", -1)
domain.SetCookie(ctx, "search-filters", "", -1)
}
// Ensure logged in
if !domain.IsLoggedIn(ctx) || user == nil {
ctx.JSON(http.StatusUnauthorized, gin.H{
"status": http.StatusUnauthorized,
"message": "User is not authorized to access this endpoint. Please login to continue.",
"recipes": nil,
})
return
}
recipes, err := deps.RecipeService.GetUserRecipes(user.Id)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"status": http.StatusBadRequest,
"message": fmt.Sprintf("Could not get user recipes. %s", err.Error()),
"recipes": nil,
})
return
}
ctx.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "User recipes successfully retrieved.",
"recipes": recipes,
})
}
func GetUserFavoriteRecipes(ctx *gin.Context) {
deps := ctx.MustGet("deps").(*domain.InjectedDependencies)
// Ensure user is logged in with a valid account
user := deps.UserService.GetAuthenicatedUser(ctx)
if user == nil {
// Log (stale) user out
domain.SetCookie(ctx, "jwt_token", "", -1)
domain.SetCookie(ctx, "search-filters", "", -1)
}
// Ensure logged in
if !domain.IsLoggedIn(ctx) || user == nil {
ctx.JSON(http.StatusUnauthorized, gin.H{
"status": http.StatusUnauthorized,
"message": "User is not authorized to access this endpoint. Please login to continue.",
"recipes": nil,
})
return
}
recipes, err := deps.RecipeService.GetUserFavoriteRecipes(user.Id)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"status": http.StatusBadRequest,
"message": fmt.Sprintf("Could not get user recipes. %s", err.Error()),
"recipes": nil,
})
return
}
ctx.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "User recipes successfully retrieved.",
"recipes": recipes,
})
}