Potion/internal/app/handlers/auth_handler.go
Hayden Hargreaves cf0e291dd9 (FEAT): Implemented a route constants domain file.
This file contains route constants so they can be changed dynamically.
However, they do not support changes to the router, those are still
manual.
2025-06-25 18:23:47 -07:00

66 lines
2.2 KiB
Go

package handlers
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
domain "github.com/haydenhargreaves/Potion/internal/domain/server"
)
// GoogleLogin directs the user to Googles select user login page. Once the user has selected an
// account, they will be directed to the GoogleCallback handler where the main logic resides.
func GoogleLogin(ctx *gin.Context) {
deps := ctx.MustGet("deps").(*domain.InjectedDependencies)
url := deps.AuthService.GetGoogleAuthUrl()
ctx.Redirect(http.StatusSeeOther, url)
}
// GoogleCallback is the callback handler when the user successfully logs in with their Google
// account. They will be directed here and a JWT is generated. This JWT is stored in the users
// cookies and will be used by protected routes to validate their login status.
//
// TODO: This route does not do the proper handling, need to work on the redirection or handling.
//
// We do not need to return all of this data, it is just for testing.
func GoogleCallback(ctx *gin.Context) {
deps := ctx.MustGet("deps").(*domain.InjectedDependencies)
var (
state string = ctx.Query("state")
code string = ctx.Query("code")
)
// TODO: Do something real, not just return data
if jwt, dbUser, googleUserInfo, err := deps.AuthService.GoogleAuthSuccess(state, code); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
} else {
// TODO: Update these values when using a real domain. Maybe an ENV?
ctx.SetCookie(
"jwt_token",
jwt,
int(time.Now().Add(7*24*time.Hour).Sub(time.Now()).Seconds()),
"/",
"localhost",
false, // TODO: True in prod
true,
)
// ctx.JSON(http.StatusOK, gin.H{"jwt": jwt, "googleUserInfo": googleUserInfo, "dbUser": dbUser})
_ = dbUser
_ = googleUserInfo
ctx.Redirect(http.StatusSeeOther, "/")
}
}
// Logout removes the token from the user's browser. Effectively "logging them out." Routes that
// require authentication will require the user to sign back in before accessing them again.
// This route will direct the user back to the home page.
func Logout(ctx *gin.Context) {
// TODO: Use same values as the GoogleCallback function
ctx.SetCookie("jwt_token", "", -1, "/", "localhost", false, true)
ctx.Redirect(http.StatusSeeOther, domain.WEB_HOME)
}