Logto Integration Attempt 1.

This commit is contained in:
2025-05-07 22:53:15 +08:00
parent 8252a4bb14
commit 4682fe3eb4
18 changed files with 487 additions and 37 deletions
+110
View File
@@ -0,0 +1,110 @@
package handlers
import (
"net/http"
"os"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
)
// SessionStorage implements Logto's Storage interface using Gin sessions
// Avoid cookie-based sessions due to size limits; use memory-based sessions for demo
// In production, use Redis/MongoDB
type SessionStorage struct {
session sessions.Session
}
func (s *SessionStorage) GetItem(key string) string {
value := s.session.Get(key)
if value == nil {
return ""
}
str, ok := value.(string)
if !ok {
return ""
}
return str
}
func (s *SessionStorage) SetItem(key, value string) {
s.session.Set(key, value)
s.session.Save()
}
// getLogtoConfig returns Logto config from environment variables
func getLogtoConfig() *client.LogtoConfig {
return &client.LogtoConfig{
Endpoint: os.Getenv("LOGTO_ENDPOINT"),
AppId: os.Getenv("LOGTO_APP_ID"),
AppSecret: os.Getenv("LOGTO_APP_SECRET"),
}
}
// HomeHandler shows auth state and sign-in/sign-out links
func HomeHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
authState := "You are not logged in to this website. :("
if logtoClient.IsAuthenticated() {
authState = "You are logged in to this website! :)"
}
homePage := "<h1>Hello Logto</h1>" +
"<div>" + authState + "</div>" +
`<div><a href="/service/auth/sign-in">Sign In</a></div>` +
`<div><a href="/service/auth/sign-out">Sign Out</a></div>`
ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
}
// SignInHandler starts the Logto sign-in flow
func SignInHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
redirectUri := os.Getenv("LOGTO_REDIRECT_URI")
signInUri, err := logtoClient.SignIn(redirectUri)
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}
ctx.Redirect(http.StatusTemporaryRedirect, signInUri)
}
// CallbackHandler handles the Logto sign-in callback
func CallbackHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
err := logtoClient.HandleSignInCallback(ctx.Request)
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}
// Redirect to the frontend page instead of the backend auth page
ctx.Redirect(http.StatusTemporaryRedirect, os.Getenv("BASE_URL"))
}
// SignOutHandler starts the Logto sign-out flow
func SignOutHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
postSignOutRedirectUri := os.Getenv("LOGTO_POST_SIGN_OUT_REDIRECT_URI")
signOutUri, err := logtoClient.SignOut(postSignOutRedirectUri)
if err != nil {
ctx.String(http.StatusOK, err.Error())
return
}
ctx.Redirect(http.StatusTemporaryRedirect, signOutUri)
}
// UserIdTokenClaimsHandler returns the user's ID token claims as JSON
func UserIdTokenClaimsHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
idTokenClaims, err := logtoClient.GetIdTokenClaims()
if err != nil {
ctx.String(http.StatusOK, err.Error())
return
}
ctx.JSON(http.StatusOK, idTokenClaims)
}
+29
View File
@@ -0,0 +1,29 @@
package middleware
import (
"os"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// CORS returns a middleware that handles CORS requests
// It only enables CORS in development mode
func CORS() gin.HandlerFunc {
// Check if we're in development mode (you can use an environment variable for this)
if os.Getenv("GIN_MODE") != "release" {
// CORS configuration for development
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://localhost:3000"} // Frontend URL
config.AllowCredentials = true // Important for cookies/auth
config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization"}
return cors.New(config)
}
// In production, no CORS middleware is needed if frontend and backend are served from the same domain
return func(c *gin.Context) {
c.Next()
}
}
+14 -1
View File
@@ -9,6 +9,19 @@ import (
// RegisterRoutes registers all API routes under the given group
func RegisterRoutes(rg *gin.RouterGroup) {
// Apply CORS middleware first (before any other middleware)
rg.Use(middleware.CORS())
// Then apply other middlewares
rg.Use(middleware.Logger())
// Define routes
rg.GET("/health", handlers.HealthCheck)
}
// Logto authentication routes
rg.GET("/auth/", handlers.HomeHandler)
rg.GET("/auth/sign-in", handlers.SignInHandler)
rg.GET("/auth/callback", handlers.CallbackHandler)
rg.GET("/auth/sign-out", handlers.SignOutHandler)
rg.GET("/auth/user-id-token-claims", handlers.UserIdTokenClaimsHandler)
}