pegasus/backend/internal/session.go

67 lines
1.6 KiB
Go
Raw Normal View History

2025-09-16 00:05:16 -05:00
// backend/internal/session.go
2025-09-08 00:48:47 -05:00
package internal
import (
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
2026-04-11 00:02:59 -03:00
// Claims are the signed session fields Pegasus stores in the browser cookie.
2025-09-08 00:48:47 -05:00
type Claims struct {
Username string `json:"u"`
JFToken string `json:"t"`
2025-09-08 00:48:47 -05:00
jwt.RegisteredClaims
}
var sessionKey = []byte(os.Getenv("PEGASUS_SESSION_KEY"))
2025-09-15 12:09:02 -05:00
var cookieSecure = os.Getenv("PEGASUS_COOKIE_INSECURE") != "1"
2026-04-11 00:02:59 -03:00
var signJWT = func(tok *jwt.Token) (string, error) {
return tok.SignedString(sessionKey)
}
2025-09-08 00:48:47 -05:00
2026-04-11 00:02:59 -03:00
// CookieName is the session cookie name used by Pegasus.
2025-09-08 00:48:47 -05:00
const CookieName = "pegasus_session"
2026-04-11 00:02:59 -03:00
// SetSession signs and writes a Pegasus session cookie.
2025-09-08 00:48:47 -05:00
func SetSession(w http.ResponseWriter, username, jfToken string) error {
now := time.Now()
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
Username: username,
JFToken: jfToken,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(7 * 24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(now),
},
})
2026-04-11 00:02:59 -03:00
signed, err := signJWT(tok)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: signed,
Path: "/",
HttpOnly: true,
Secure: cookieSecure,
SameSite: http.SameSiteLaxMode,
})
2025-09-08 00:48:47 -05:00
return nil
}
2026-04-11 00:02:59 -03:00
// ClearSession expires the Pegasus session cookie immediately.
2025-09-08 00:48:47 -05:00
func ClearSession(w http.ResponseWriter) {
2025-09-16 00:05:16 -05:00
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: "",
Expires: time.Unix(0, 0),
MaxAge: -1,
Path: "/",
HttpOnly: true,
Secure: cookieSecure,
SameSite: http.SameSiteLaxMode,
2025-09-16 00:05:16 -05:00
})
2025-09-08 00:48:47 -05:00
}