diff --git a/auth/middleware.go b/auth/middleware.go index ac5a7a2..d5e6237 100644 --- a/auth/middleware.go +++ b/auth/middleware.go @@ -3,27 +3,31 @@ package auth import ( "crypto/subtle" + "html/template" "net/http" "time" ) type AuthMiddleware struct { - username string - password string - sessions *SessionManager + username string + password string + sessions *SessionManager + templates *template.Template } -func NewAuthMiddleware(username, password string, sessions *SessionManager) *AuthMiddleware { +func NewAuthMiddleware(username, password string, sessions *SessionManager, templates *template.Template) *AuthMiddleware { return &AuthMiddleware{ - username: username, - password: password, - sessions: sessions, + username: username, + password: password, + sessions: sessions, + templates: templates, } } func (a *AuthMiddleware) Login(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { - a.serveLoginPage(w) + showError := r.URL.Query().Get("error") == "1" + a.serveLoginPage(w, showError) return } @@ -47,7 +51,7 @@ func (a *AuthMiddleware) Login(w http.ResponseWriter, r *http.Request) { Value: sessionID, Path: "/", HttpOnly: true, - Secure: true, + Secure: r.TLS != nil, // 只在 HTTPS 时设置 Secure SameSite: http.SameSiteStrictMode, MaxAge: 1800, }) @@ -72,7 +76,7 @@ func (a *AuthMiddleware) Logout(w http.ResponseWriter, r *http.Request) { Value: "", Path: "/", HttpOnly: true, - Secure: true, + Secure: r.TLS != nil, MaxAge: -1, }) @@ -90,98 +94,15 @@ func (a *AuthMiddleware) Require(next http.Handler) http.Handler { }) } -func (a *AuthMiddleware) serveLoginPage(w http.ResponseWriter) { - html := ` - - - - Login - Secure Site Proxy - - - -
-

🔒 Secure Login

-
-
- - -
-
- - -
- -
-
- -` +func (a *AuthMiddleware) serveLoginPage(w http.ResponseWriter, showError bool) { + data := struct { + Error bool + }{ + Error: showError, + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Write([]byte(html)) + if err := a.templates.ExecuteTemplate(w, "login.html", data); err != nil { + http.Error(w, "Internal server error", http.StatusInternalServerError) + } }