Potion/internal/app/handlers/auth_handler.go
Hayden Hargreaves 1e6a06e8ed (FEAT): Added errors to each of the handlers.
I think this is really the only place we need them. For now at least.
2025-09-04 20:25:12 -07:00

51 lines
1.8 KiB
Go

package handlers
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
domain "github.com/haydenhargreaves/Potion/internal/domain/server"
"github.com/haydenhargreaves/Potion/internal/templates/components"
)
// 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.
//
// 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")
)
if jwt, err := deps.AuthService.GoogleAuthSuccess(state, code); err != nil {
components.RenderErrorBanner(ctx, err.Error())
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
} else {
domain.SetCookie(ctx, "jwt_token", jwt, time.Hour*24*7)
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)
}