Files
prompt-generator/internal/auth/middleware.go
T

47 lines
976 B
Go
Raw Normal View History

package auth
import (
"crypto/rand"
"encoding/hex"
"net/http"
"sync"
"github.com/gorilla/sessions"
)
var (
Store *sessions.CookieStore
mu sync.Mutex
)
func Init(secret string) {
Store = sessions.NewCookieStore([]byte(secret))
Store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7 days
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}
func GenerateToken() string {
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
// AuthMiddleware checks if the user is authenticated
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := Store.Get(r, "session")
auth, ok := session.Values["authenticated"].(bool)
if !ok || !auth {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"code":401,"message":"未登录"}`))
return
}
next.ServeHTTP(w, r)
})
}