Potion/internal/app/handlers/auth_handler.go
Hayden Hargreaves dbf8470195 (FIX): More auth issues solved.
If a user is logged into an account that cannot be found, they will be
silently logged out, so they can log back into their account. In the
event that the data becomes stale.
2025-07-27 13:00:03 -07:00

56 lines
2.0 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 {
domain.SetCookie(ctx, "jwt_token", jwt, time.Hour*24*7)
// 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) {
domain.SetCookie(ctx, "jwt_token", "", -1)
domain.SetCookie(ctx, "search-filters", "", -1)
ctx.Redirect(http.StatusSeeOther, domain.WEB_HOME)
}