package handlers
import (
"net/http"
"tixe/auth"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
func AuthCallback(auth *auth.Auth) gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
if c.Query("state") != session.Get("state") {
c.String(http.StatusBadRequest, "Invalid state parameter!")
return
}
token, err := auth.Exchange(c.Request.Context(), c.Query("code"))
if err != nil {
c.String(http.StatusUnauthorized, "Failed to exchange authorization code for token!")
return
}
idToken, err := auth.VerifyIDToken(c.Request.Context(), token)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to verify ID token!")
return
}
var profile map[string]interface{}
if err := idToken.Claims(&profile); err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
session.Set("access_token", token.AccessToken)
session.Set("profile", profile)
if err := session.Save(); err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.Redirect(http.StatusTemporaryRedirect, "/")
}
}