Compare commits

..

No commits in common. "18033667d3fdb8213c1f9c1413000c28dd2f40d4" and "357097bb2b67a75d43494dfb476433ccf82a5ccc" have entirely different histories.

9 changed files with 126 additions and 164 deletions

View File

@ -7,7 +7,6 @@ This is to kick start a web project with nextjs as frontend and go server as bac
```
starter/
├── .env
├── .env.dev
├── sh/ # Shell scripts for development and deployment automation
│ ├── dev.sh
│ └── prod.sh
@ -43,7 +42,3 @@ All environmental variables should be managed in a centralized `.env` in the roo
- API prefix: `/service/`
- Next.js 15.3.2 (App Router, Turbopack enabled, Import alias: `@/*`)
- Logto 1.27.0
## Rules
- Frontend and backend should communicate with standard JSON.

View File

@ -1,7 +1,6 @@
package handlers
import (
"fmt"
"net/http"
"os"
@ -15,11 +14,11 @@ import (
// In production, use Redis/MongoDB
type SessionStorage struct {
Session sessions.Session
session sessions.Session
}
func (s *SessionStorage) GetItem(key string) string {
value := s.Session.Get(key)
value := s.session.Get(key)
if value == nil {
return ""
}
@ -31,12 +30,12 @@ func (s *SessionStorage) GetItem(key string) string {
}
func (s *SessionStorage) SetItem(key, value string) {
s.Session.Set(key, value)
s.Session.Save()
s.session.Set(key, value)
s.session.Save()
}
// GetLogtoConfig returns Logto config from environment variables
func GetLogtoConfig() *client.LogtoConfig {
// 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"),
@ -45,107 +44,28 @@ func GetLogtoConfig() *client.LogtoConfig {
}
// HomeHandler shows auth state and sign-in/sign-out links
// Note: The /service/auth endpoint is for debugging purposes only
func HomeHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(GetLogtoConfig(), &SessionStorage{Session: session})
var debugInfo string
debugInfo = "<h1>Logto Auth Debugging Page</h1>"
// Basic auth state
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
authState := "You are not logged in to this website. :("
if logtoClient.IsAuthenticated() {
debugInfo += "<div style='color: green; font-weight: bold;'>Authentication Status: Logged In ✓</div>"
// Get ID Token claims
idTokenClaims, err := logtoClient.GetIdTokenClaims()
if err != nil {
debugInfo += "<div style='color: red;'>Error fetching ID token claims: " + err.Error() + "</div>"
} else {
debugInfo += "<h2>ID Token Claims</h2>"
debugInfo += "<pre style='background-color: #f5f5f5; padding: 10px; overflow: auto; max-height: 400px;'>"
// Display claims in a simpler format
debugInfo += "<table style='width: 100%; border-collapse: collapse;'>"
debugInfo += "<tr><th style='text-align: left; padding: 5px; border-bottom: 1px solid #ddd;'>Claim</th><th style='text-align: left; padding: 5px; border-bottom: 1px solid #ddd;'>Value</th></tr>"
// Display the raw claims directly without any checks that might cause linter errors
debugInfo += fmt.Sprintf("<tr><td>sub</td><td>%v</td></tr>", idTokenClaims.Sub)
debugInfo += fmt.Sprintf("<tr><td>name</td><td>%v</td></tr>", idTokenClaims.Name)
debugInfo += fmt.Sprintf("<tr><td>email</td><td>%v</td></tr>", idTokenClaims.Email)
debugInfo += fmt.Sprintf("<tr><td>issuer</td><td>%v</td></tr>", idTokenClaims.Iss)
debugInfo += fmt.Sprintf("<tr><td>audience</td><td>%v</td></tr>", idTokenClaims.Aud)
debugInfo += fmt.Sprintf("<tr><td>expires at</td><td>%v</td></tr>", idTokenClaims.Exp)
debugInfo += fmt.Sprintf("<tr><td>issued at</td><td>%v</td></tr>", idTokenClaims.Iat)
debugInfo += "</table>"
debugInfo += "</pre>"
authState = "You are logged in to this website! :)"
}
// Try to get access token info
hasAccessToken := false
var accessTokenErr error
_, accessTokenErr = logtoClient.GetAccessToken("")
if accessTokenErr == nil {
hasAccessToken = true
}
debugInfo += "<h2>Access Token Information</h2>"
if hasAccessToken {
debugInfo += "<div><strong>Access Token:</strong> Present (not displayed for security)</div>"
} else {
debugInfo += "<div>No resource-specific access token available</div>"
}
// Session information
debugInfo += "<h2>Session Information</h2>"
debugInfo += "<pre style='background-color: #f5f5f5; padding: 10px;'>"
// Get all keys from the session
for _, key := range []string{"idToken", "accessToken", "refreshToken", "expiresAt"} {
value := session.Get(key)
debugInfo += "<div><strong>" + key + ":</strong> "
if value == nil {
debugInfo += "Not set"
} else if strValue, ok := value.(string); ok {
if len(strValue) > 100 {
debugInfo += strValue[:100] + "..."
} else {
debugInfo += strValue
}
} else {
debugInfo += "Set (non-string value)"
}
debugInfo += "</div>"
}
debugInfo += "</pre>"
} else {
debugInfo += "<div style='color: red; font-weight: bold;'>Authentication Status: Not Logged In ✗</div>"
debugInfo += "<div>Sign in to see detailed authentication information</div>"
}
// Config information (excluding secrets)
debugInfo += "<h2>Logto Configuration</h2>"
debugInfo += "<div><strong>Endpoint:</strong> " + os.Getenv("LOGTO_ENDPOINT") + "</div>"
debugInfo += "<div><strong>App ID:</strong> " + os.Getenv("LOGTO_APP_ID") + "</div>"
debugInfo += "<div><strong>Redirect URI:</strong> " + os.Getenv("LOGTO_REDIRECT_URI") + "</div>"
// Add links for authentication actions
debugInfo += "<h2>Authentication Actions</h2>"
debugInfo += `<div><a href="/service/auth/sign-in" style="display: inline-block; margin: 10px 0; padding: 8px 16px; background-color: #4285f4; color: white; text-decoration: none; border-radius: 4px;">Sign In</a></div>`
debugInfo += `<div><a href="/service/auth/sign-out" style="display: inline-block; margin: 10px 0; padding: 8px 16px; background-color: #f44336; color: white; text-decoration: none; border-radius: 4px;">Sign Out</a></div>`
ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(debugInfo))
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})
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
redirectUri := os.Getenv("LOGTO_REDIRECT_URI")
signInUri, err := logtoClient.SignIn(redirectUri)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
ctx.String(http.StatusInternalServerError, err.Error())
return
}
ctx.Redirect(http.StatusTemporaryRedirect, signInUri)
@ -154,10 +74,10 @@ func SignInHandler(ctx *gin.Context) {
// CallbackHandler handles the Logto sign-in callback
func CallbackHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(GetLogtoConfig(), &SessionStorage{Session: session})
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
err := logtoClient.HandleSignInCallback(ctx.Request)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
ctx.String(http.StatusInternalServerError, err.Error())
return
}
// Redirect to the frontend page instead of the backend auth page
@ -167,11 +87,11 @@ func CallbackHandler(ctx *gin.Context) {
// SignOutHandler starts the Logto sign-out flow
func SignOutHandler(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(GetLogtoConfig(), &SessionStorage{Session: session})
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.JSON(http.StatusOK, gin.H{"error": err.Error()})
ctx.String(http.StatusOK, err.Error())
return
}
ctx.Redirect(http.StatusTemporaryRedirect, signOutUri)
@ -180,10 +100,10 @@ func SignOutHandler(ctx *gin.Context) {
// 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})
logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session})
idTokenClaims, err := logtoClient.GetIdTokenClaims()
if err != nil {
ctx.JSON(http.StatusOK, gin.H{"error": err.Error()})
ctx.String(http.StatusOK, err.Error())
return
}
ctx.JSON(http.StatusOK, idTokenClaims)

View File

@ -1,24 +0,0 @@
package middleware
import (
"net/http"
"starter/backend/internal/handlers"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
)
// AuthRequired 是 Logto 认证中间件,未认证用户返回 401
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
logtoClient := client.NewLogtoClient(handlers.GetLogtoConfig(), &handlers.SessionStorage{Session: session})
if !logtoClient.IsAuthenticated() {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
c.Next()
}
}

View File

@ -16,7 +16,7 @@ func RegisterRoutes(rg *gin.RouterGroup) {
rg.Use(middleware.Logger())
// Define routes
rg.GET("/health", middleware.AuthRequired(), handlers.HealthCheck)
rg.GET("/health", handlers.HealthCheck)
// Logto authentication routes
rg.GET("/auth/", handlers.HomeHandler)

View File

@ -41,6 +41,58 @@ export default function AuthStatus() {
</button>
)}
</div>
<style jsx>{`
.auth-status {
margin: 2rem 0;
padding: 1.5rem;
border-radius: 8px;
background-color: #f8f9fa;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.auth-info {
margin-bottom: 1rem;
}
.user-info {
margin-top: 0.5rem;
padding: 0.75rem;
background-color: #e9ecef;
border-radius: 4px;
}
.auth-actions {
margin-top: 1rem;
}
button {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
transition: background-color 0.2s;
}
.login-button {
background-color: #4285f4;
color: white;
}
.logout-button {
background-color: #ea4335;
color: white;
}
button:hover {
opacity: 0.9;
}
.loading {
opacity: 0.7;
}
`}</style>
</div>
);
}

View File

@ -10,22 +10,13 @@ export default function HealthStatus() {
const checkHealth = async () => {
try {
setLoading(true);
const response = await fetch(`${process.env.BACKEND_URL}/health`, {
credentials: "include",
});
const response = await fetch(`${process.env.BACKEND_URL}/health`);
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
let data;
try {
data = await response.json();
} catch {
setError("Response is not valid JSON");
setHealth({});
return;
}
const data = await response.json();
setHealth(data);
} catch (err) {
setError(
@ -60,6 +51,25 @@ export default function HealthStatus() {
</p>
</div>
)}
<style jsx>{`
.health-status {
padding: 1rem;
border-radius: 0.5rem;
border: 1px solid #eaeaea;
margin-top: 1rem;
}
.status-ok {
color: green;
font-weight: bold;
}
.status-error {
color: red;
font-weight: bold;
}
.error {
color: red;
}
`}</style>
</div>
);
}

View File

@ -43,24 +43,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
);
if (response.ok) {
let userData;
try {
userData = await response.json();
} catch {
// 不是 JSON降级处理
setUser(null);
setIsAuthenticated(false);
setLoading(false);
return;
}
// 处理后端返回 { error: ... }
if (userData && userData.error) {
setUser(null);
setIsAuthenticated(false);
} else {
const userData = await response.json();
setUser(userData);
setIsAuthenticated(true);
}
} else {
setUser(null);
setIsAuthenticated(false);

View File

@ -1,3 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@ -16,6 +16,33 @@ export default function Home() {
<h2>Backend Health</h2>
<HealthStatus />
</section>
<style jsx>{`
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
h1 {
margin-bottom: 2rem;
color: #333;
font-size: 2.5rem;
text-align: center;
}
h2 {
color: #555;
margin-bottom: 1rem;
border-bottom: 1px solid #eee;
padding-bottom: 0.5rem;
}
section {
margin-bottom: 2rem;
background-color: white;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
`}</style>
</main>
);
}