feat: add HTTP-only cookie for browser authentication

- Set HTTP-only cookie in login handler for SSR authentication
- Set HTTP-only cookie in registration handler
- Change default redirect from /bookshelf to /dashboard
- Cookie enables browser page navigation without JavaScript
This commit is contained in:
2026-02-15 21:36:42 -05:00
parent 6b3ccdfc55
commit b5156bbe16
+24 -2
View File
@@ -213,6 +213,17 @@ func (h *AuthHandler) Register(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate token"})
}
// Set HTTP-only cookie for browser-based authentication
cookie := &http.Cookie{
Name: "token",
Value: accessToken,
Path: "/",
HttpOnly: true,
Secure: false,
MaxAge: 3600,
}
c.SetCookie(cookie)
_, refreshToken, err := h.CreateRefreshToken(uuid.UUID(user.ID.Bytes))
if err != nil {
if c.Request().Header.Get("HX-Request") == "true" {
@@ -228,7 +239,7 @@ localStorage.setItem('token', '%s');
localStorage.setItem('refreshToken', '%s');
localStorage.setItem('user', JSON.stringify(%s));
document.cookie = 'token=%s; path=/; max-age=3600';
window.location.href = '/bookshelf';
window.location.href = '/dashboard';
</script>`, accessToken, refreshToken, fmt.Sprintf(`{"id":"%s","email":"%s","username":"%s"}`, uuid.UUID(user.ID.Bytes).String(), user.Email, user.Username), accessToken)
return c.HTML(http.StatusCreated, html)
}
@@ -348,6 +359,17 @@ func (h *AuthHandler) Login(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate token"})
}
// Set HTTP-only cookie for browser-based authentication
cookie := &http.Cookie{
Name: "token",
Value: accessToken,
Path: "/",
HttpOnly: true,
Secure: false,
MaxAge: 3600,
}
c.SetCookie(cookie)
_, refreshToken, err := h.CreateRefreshToken(uuid.UUID(user.ID.Bytes))
if err != nil {
if c.Request().Header.Get("HX-Request") == "true" {
@@ -359,7 +381,7 @@ func (h *AuthHandler) Login(c echo.Context) error {
if c.Request().Header.Get("HX-Request") == "true" {
redirect := c.FormValue("redirect")
if redirect == "" {
redirect = "/bookshelf"
redirect = "/dashboard"
}
html := fmt.Sprintf(`<div class="text-green-500">Login successful! Redirecting...</div>
<script>