fix: rolling session renewal
This commit is contained in:
@@ -3,7 +3,6 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"mal/internal/domain"
|
"mal/internal/domain"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -42,7 +41,7 @@ func (h *AuthHandler) HandleLogin(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.SetCookie("session_id", session.ID, int(24*time.Hour.Seconds()), "/", "", false, true)
|
c.SetCookie("session_id", session.ID, int(domain.SessionLifetime.Seconds()), "/", "", false, true)
|
||||||
if c.GetHeader("HX-Request") == "true" {
|
if c.GetHeader("HX-Request") == "true" {
|
||||||
c.Header("HX-Redirect", "/")
|
c.Header("HX-Redirect", "/")
|
||||||
c.Status(http.StatusOK)
|
c.Status(http.StatusOK)
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
|||||||
|
|
||||||
var user *domain.User
|
var user *domain.User
|
||||||
var err error
|
var err error
|
||||||
|
var sessionID string
|
||||||
|
var usesCookieSession bool
|
||||||
|
|
||||||
// API routes can authenticate via Bearer token OR cookie session.
|
// API routes can authenticate via Bearer token OR cookie session.
|
||||||
if strings.HasPrefix(path, "/api/") {
|
if strings.HasPrefix(path, "/api/") {
|
||||||
@@ -30,7 +32,9 @@ func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
|||||||
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
|
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
|
||||||
token := strings.TrimSpace(authHeader[7:])
|
token := strings.TrimSpace(authHeader[7:])
|
||||||
user, err = svc.ValidateAPIToken(c.Request.Context(), token)
|
user, err = svc.ValidateAPIToken(c.Request.Context(), token)
|
||||||
} else if sessionID, cookieErr := c.Cookie("session_id"); cookieErr == nil {
|
} else if cookieSessionID, cookieErr := c.Cookie("session_id"); cookieErr == nil {
|
||||||
|
sessionID = cookieSessionID
|
||||||
|
usesCookieSession = true
|
||||||
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
||||||
} else {
|
} else {
|
||||||
err = cookieErr
|
err = cookieErr
|
||||||
@@ -43,13 +47,15 @@ func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Non-API routes only use cookie sessions and redirect to /login.
|
// Non-API routes only use cookie sessions and redirect to /login.
|
||||||
sessionID, cookieErr := c.Cookie("session_id")
|
cookieSessionID, cookieErr := c.Cookie("session_id")
|
||||||
if cookieErr != nil {
|
if cookieErr != nil {
|
||||||
c.Redirect(http.StatusSeeOther, "/login")
|
c.Redirect(http.StatusSeeOther, "/login")
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sessionID = cookieSessionID
|
||||||
|
usesCookieSession = true
|
||||||
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
user, err = svc.ValidateSession(c.Request.Context(), sessionID)
|
||||||
if err != nil || user == nil {
|
if err != nil || user == nil {
|
||||||
c.Redirect(http.StatusSeeOther, "/login")
|
c.Redirect(http.StatusSeeOther, "/login")
|
||||||
@@ -58,6 +64,12 @@ func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if usesCookieSession {
|
||||||
|
if refreshErr := svc.RefreshSession(c.Request.Context(), sessionID); refreshErr == nil {
|
||||||
|
c.SetCookie("session_id", sessionID, int(domain.SessionLifetime.Seconds()), "/", "", false, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
c.Set("User", user)
|
c.Set("User", user)
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func (r *authRepository) CreateSession(ctx context.Context, userID string, sessi
|
|||||||
s, err := r.queries.CreateSession(ctx, db.CreateSessionParams{
|
s, err := r.queries.CreateSession(ctx, db.CreateSessionParams{
|
||||||
ID: sessionID,
|
ID: sessionID,
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
ExpiresAt: time.Now().Add(domain.SessionLifetime),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -64,6 +64,13 @@ func (r *authRepository) GetSession(ctx context.Context, sessionID string) (*dom
|
|||||||
return &s, nil
|
return &s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *authRepository) RefreshSession(ctx context.Context, sessionID string, expiresAt time.Time) error {
|
||||||
|
return r.queries.RefreshSession(ctx, db.RefreshSessionParams{
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
ID: sessionID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (r *authRepository) DeleteSession(ctx context.Context, sessionID string) error {
|
func (r *authRepository) DeleteSession(ctx context.Context, sessionID string) error {
|
||||||
return r.queries.DeleteSession(ctx, sessionID)
|
return r.queries.DeleteSession(ctx, sessionID)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,14 @@ func (s *authService) ValidateSession(ctx context.Context, sessionID string) (*d
|
|||||||
return s.repo.GetUserByID(ctx, session.UserID)
|
return s.repo.GetUserByID(ctx, session.UserID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *authService) RefreshSession(ctx context.Context, sessionID string) error {
|
||||||
|
if strings.TrimSpace(sessionID) == "" {
|
||||||
|
return errors.New("session id missing")
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.repo.RefreshSession(ctx, sessionID, time.Now().Add(domain.SessionLifetime))
|
||||||
|
}
|
||||||
|
|
||||||
func (s *authService) ValidateAPIToken(ctx context.Context, token string) (*domain.User, error) {
|
func (s *authService) ValidateAPIToken(ctx context.Context, token string) (*domain.User, error) {
|
||||||
trimmed := strings.TrimSpace(token)
|
trimmed := strings.TrimSpace(token)
|
||||||
if trimmed == "" {
|
if trimmed == "" {
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ SELECT * FROM session WHERE id = ? LIMIT 1;
|
|||||||
-- name: DeleteSession :exec
|
-- name: DeleteSession :exec
|
||||||
DELETE FROM session WHERE id = ?;
|
DELETE FROM session WHERE id = ?;
|
||||||
|
|
||||||
|
-- name: RefreshSession :exec
|
||||||
|
UPDATE session
|
||||||
|
SET expires_at = ?
|
||||||
|
WHERE id = ?;
|
||||||
|
|
||||||
-- name: CreateAPIToken :one
|
-- name: CreateAPIToken :one
|
||||||
INSERT INTO api_token (id, user_id, token_hash, name)
|
INSERT INTO api_token (id, user_id, token_hash, name)
|
||||||
VALUES (?, ?, ?, ?)
|
VALUES (?, ?, ?, ?)
|
||||||
|
|||||||
@@ -124,6 +124,22 @@ func (q *Queries) DeleteSession(ctx context.Context, id string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const refreshSession = `-- name: RefreshSession :exec
|
||||||
|
UPDATE session
|
||||||
|
SET expires_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
`
|
||||||
|
|
||||||
|
type RefreshSessionParams struct {
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) RefreshSession(ctx context.Context, arg RefreshSessionParams) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, refreshSession, arg.ExpiresAt, arg.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
const deleteWatchListEntry = `-- name: DeleteWatchListEntry :exec
|
const deleteWatchListEntry = `-- name: DeleteWatchListEntry :exec
|
||||||
DELETE FROM watch_list_entry
|
DELETE FROM watch_list_entry
|
||||||
WHERE user_id = ? AND anime_id = ?
|
WHERE user_id = ? AND anime_id = ?
|
||||||
|
|||||||
@@ -3,16 +3,20 @@ package domain
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"mal/internal/db"
|
"mal/internal/db"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type User = db.User
|
type User = db.User
|
||||||
type Session = db.Session
|
type Session = db.Session
|
||||||
type APIToken = db.ApiToken
|
type APIToken = db.ApiToken
|
||||||
|
|
||||||
|
const SessionLifetime = 90 * 24 * time.Hour
|
||||||
|
|
||||||
type AuthService interface {
|
type AuthService interface {
|
||||||
Login(ctx context.Context, username, password string) (*Session, error)
|
Login(ctx context.Context, username, password string) (*Session, error)
|
||||||
LoginForAPIToken(ctx context.Context, username, password, name string) (token string, user *User, err error)
|
LoginForAPIToken(ctx context.Context, username, password, name string) (token string, user *User, err error)
|
||||||
ValidateSession(ctx context.Context, sessionID string) (*User, error)
|
ValidateSession(ctx context.Context, sessionID string) (*User, error)
|
||||||
|
RefreshSession(ctx context.Context, sessionID string) error
|
||||||
ValidateAPIToken(ctx context.Context, token string) (*User, error)
|
ValidateAPIToken(ctx context.Context, token string) (*User, error)
|
||||||
Logout(ctx context.Context, sessionID string) error
|
Logout(ctx context.Context, sessionID string) error
|
||||||
RevokeAllAPITokensForUser(ctx context.Context, userID string) error
|
RevokeAllAPITokensForUser(ctx context.Context, userID string) error
|
||||||
@@ -23,6 +27,7 @@ type AuthRepository interface {
|
|||||||
GetUserByID(ctx context.Context, id string) (*User, error)
|
GetUserByID(ctx context.Context, id string) (*User, error)
|
||||||
CreateSession(ctx context.Context, userID string, sessionID string) (*Session, error)
|
CreateSession(ctx context.Context, userID string, sessionID string) (*Session, error)
|
||||||
GetSession(ctx context.Context, sessionID string) (*Session, error)
|
GetSession(ctx context.Context, sessionID string) (*Session, error)
|
||||||
|
RefreshSession(ctx context.Context, sessionID string, expiresAt time.Time) error
|
||||||
DeleteSession(ctx context.Context, sessionID string) error
|
DeleteSession(ctx context.Context, sessionID string) error
|
||||||
CreateAPIToken(ctx context.Context, userID, tokenHash, name string) (*APIToken, error)
|
CreateAPIToken(ctx context.Context, userID, tokenHash, name string) (*APIToken, error)
|
||||||
GetAPITokenByHash(ctx context.Context, tokenHash string) (*APIToken, error)
|
GetAPITokenByHash(ctx context.Context, tokenHash string) (*APIToken, error)
|
||||||
|
|||||||
Reference in New Issue
Block a user