feat: session verification
This commit is contained in:
@ -3,22 +3,27 @@ package middleware
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.local/admin/hspguard/internal/config"
|
"gitea.local/admin/hspguard/internal/config"
|
||||||
|
"gitea.local/admin/hspguard/internal/repository"
|
||||||
"gitea.local/admin/hspguard/internal/types"
|
"gitea.local/admin/hspguard/internal/types"
|
||||||
"gitea.local/admin/hspguard/internal/util"
|
"gitea.local/admin/hspguard/internal/util"
|
||||||
"gitea.local/admin/hspguard/internal/web"
|
"gitea.local/admin/hspguard/internal/web"
|
||||||
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthMiddleware struct {
|
type AuthMiddleware struct {
|
||||||
cfg *config.AppConfig
|
cfg *config.AppConfig
|
||||||
|
repo *repository.Queries
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAuthMiddleware(cfg *config.AppConfig) *AuthMiddleware {
|
func NewAuthMiddleware(cfg *config.AppConfig, repo *repository.Queries) *AuthMiddleware {
|
||||||
return &AuthMiddleware{
|
return &AuthMiddleware{
|
||||||
cfg,
|
cfg,
|
||||||
|
repo,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,6 +50,26 @@ func (m *AuthMiddleware) Runner(next http.Handler) http.Handler {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: redis caching
|
||||||
|
parsed, err := uuid.Parse(userClaims.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("ERR: Failed to parse token JTI '%s': %v\n", userClaims.ID, err)
|
||||||
|
web.Error(w, "failed to get session", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
session, err := m.repo.GetUserSessionByAccessJTI(r.Context(), &parsed)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("ERR: Failed to find session with '%s' JTI: %v\n", parsed.String(), err)
|
||||||
|
web.Error(w, "no session found", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !session.IsActive {
|
||||||
|
log.Printf("INFO: Inactive session trying to authorize: %s\n", session.AccessTokenID)
|
||||||
|
web.Error(w, "no session found", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
ctx := context.WithValue(r.Context(), types.UserIdKey, userClaims.Subject)
|
ctx := context.WithValue(r.Context(), types.UserIdKey, userClaims.Subject)
|
||||||
ctx = context.WithValue(ctx, types.JTIKey, userClaims.ID)
|
ctx = context.WithValue(ctx, types.JTIKey, userClaims.ID)
|
||||||
next.ServeHTTP(w, r.WithContext(ctx))
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
Reference in New Issue
Block a user