Skip to content

Research - session cache in memory #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions internal/app/handlers/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
DB *sql.DB
}

// ServerInterfaceWrapper wraps Handlers to conform to the generated interface
type ServerInterfaceWrapper struct {
handlers *Handlers
}
Expand All @@ -21,6 +20,16 @@
return &ServerInterfaceWrapper{handlers: handlers}
}

type SessionServerInterfaceWrapper struct {
sessionHandler *SessionHandler
}

func NewSessionServerInterfaceWrapper(handlers *Handlers) *SessionServerInterfaceWrapper {
return &SessionServerInterfaceWrapper{
sessionHandler: NewSessionHandler(handlers),
}
}

func (siw *ServerInterfaceWrapper) ListGames(w http.ResponseWriter, r *http.Request) {
siw.handlers.ListGames(w, r)
}
Expand All @@ -41,16 +50,16 @@
siw.handlers.UpdateGame(w, r, id)
}

func (siw *ServerInterfaceWrapper) PostApiV1AuthSignIn(w http.ResponseWriter, r *http.Request) {
siw.handlers.PostApiV1AuthSignIn(w, r)
func (siw *SessionServerInterfaceWrapper) PostApiV1AuthSignIn(w http.ResponseWriter, r *http.Request) {
siw.sessionHandler.PostApiV1AuthSignIn(w, r)
}

func (siw *ServerInterfaceWrapper) PostApiV1AuthSignOut(w http.ResponseWriter, r *http.Request) {
siw.handlers.PostApiV1AuthSignOut(w, r)
func (siw *SessionServerInterfaceWrapper) PostApiV1AuthSignOut(w http.ResponseWriter, r *http.Request) {
siw.sessionHandler.PostApiV1AuthSignOut(w, r)

Check failure on line 58 in internal/app/handlers/interface.go

View workflow job for this annotation

GitHub Actions / Lint with golangci-lint

[golangci] reported by reviewdog 🐶 siw.sessionHandler.PostApiV1AuthSignOut undefined (type *SessionHandler has no field or method PostApiV1AuthSignOut) (typecheck) Raw Output: internal/app/handlers/interface.go:58:21: siw.sessionHandler.PostApiV1AuthSignOut undefined (type *SessionHandler has no field or method PostApiV1AuthSignOut) (typecheck) package handlers

Check failure on line 58 in internal/app/handlers/interface.go

View workflow job for this annotation

GitHub Actions / Lint with golangci-lint

[golangci] reported by reviewdog 🐶 siw.sessionHandler.PostApiV1AuthSignOut undefined (type *SessionHandler has no field or method PostApiV1AuthSignOut)) (typecheck) Raw Output: internal/app/handlers/interface.go:58:21: siw.sessionHandler.PostApiV1AuthSignOut undefined (type *SessionHandler has no field or method PostApiV1AuthSignOut)) (typecheck) "ctf01d/internal/app/handlers" ^
}

func (siw *ServerInterfaceWrapper) ValidateSession(w http.ResponseWriter, r *http.Request) {
siw.handlers.ValidateSession(w, r)
func (siw *SessionServerInterfaceWrapper) ValidateSession(w http.ResponseWriter, r *http.Request) {
siw.sessionHandler.ValidateSession(w, r)
}

func (siw *ServerInterfaceWrapper) ListResults(w http.ResponseWriter, r *http.Request) {
Expand Down
72 changes: 66 additions & 6 deletions internal/app/handlers/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,53 @@
"encoding/json"
"log/slog"
"net/http"
"sync"

"ctf01d/internal/app/repository"
"ctf01d/internal/app/server"
api_helpers "ctf01d/internal/app/utils"
"ctf01d/internal/app/view"

"github.com/google/uuid"
openapi_types "github.com/oapi-codegen/runtime/types"
)

func (h *Handlers) PostApiV1AuthSignIn(w http.ResponseWriter, r *http.Request) {
type SessionCache struct {
cache sync.Map
}

func NewSessionCache() *SessionCache {
return &SessionCache{}
}

func (sc *SessionCache) GetSession(sessionID string) (openapi_types.UUID, bool) {
val, ok := sc.cache.Load(sessionID)
if !ok {
return uuid.Nil, false
}
return val.(openapi_types.UUID), true
}

func (sc *SessionCache) SetSession(sessionID string, userID uuid.UUID) {
sc.cache.Store(sessionID, userID)
}

func (sc *SessionCache) DeleteSession(sessionID string) {
sc.cache.Delete(sessionID)
}

type SessionHandler struct {
*Handlers
SessionCache *SessionCache
}

func NewSessionHandler(handlers *Handlers) *SessionHandler {
return &SessionHandler{
Handlers: handlers,
SessionCache: NewSessionCache(),
}
}

func (h *SessionHandler) PostApiV1AuthSignIn(w http.ResponseWriter, r *http.Request) {
var req server.PostApiV1AuthSignInJSONBody
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
slog.Warn(err.Error(), "handler", "PostApiV1AuthSignIn")
Expand All @@ -38,6 +75,9 @@
return
}

// Добавляем сессию в кэш
h.SessionCache.SetSession(sessionId, user.Id)

http.SetCookie(w, &http.Cookie{
Name: "session_id",
HttpOnly: true,
Expand All @@ -49,7 +89,7 @@
api_helpers.RespondWithJSON(w, http.StatusOK, map[string]string{"data": "User logged in"})
}

func (h *Handlers) PostApiV1AuthSignOut(w http.ResponseWriter, r *http.Request) {
func (h *Handler) PostApiV1AuthSignOut(w http.ResponseWriter, r *http.Request) {

Check failure on line 92 in internal/app/handlers/sessions.go

View workflow job for this annotation

GitHub Actions / Lint with golangci-lint

[golangci] reported by reviewdog 🐶 undefined: Handler Raw Output: internal/app/handlers/sessions.go:92:10: undefined: Handler

Check failure on line 92 in internal/app/handlers/sessions.go

View workflow job for this annotation

GitHub Actions / Lint with golangci-lint

[golangci] reported by reviewdog 🐶 undefined: Handler Raw Output: internal/app/handlers/sessions.go:92:10: undefined: Handler
cookie, err := r.Cookie("session_id")
if err != nil {
slog.Warn(err.Error(), "handler", "PostApiV1AuthSignOut")
Expand All @@ -63,6 +103,10 @@
api_helpers.RespondWithJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to delete session"})
return
}

// Удаляем сессию из кэша
h.SessionCache.DeleteSession(cookie.Value)

http.SetCookie(w, &http.Cookie{
Name: "session_id",
Value: "",
Expand All @@ -72,13 +116,20 @@
api_helpers.RespondWithJSON(w, http.StatusOK, map[string]string{"data": "User logout successful"})
}

func (h *Handlers) ValidateSession(w http.ResponseWriter, r *http.Request) {
func (h *SessionHandler) ValidateSession(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_id")
if err != nil {
slog.Warn(err.Error(), "handler", "ValidateSession")
api_helpers.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"error": "No session found"})
return
}

if userId, ok := h.SessionCache.GetSession(cookie.Value); ok {
slog.Debug("ValidateSession user.Id " + openapi_types.UUID(userId).String())
h.respondWithUserDetails(w, r, userId)
return
}

slog.Debug("cookie.Value, " + cookie.Value)
repo := repository.NewSessionRepository(h.DB)
var userId openapi_types.UUID
Expand All @@ -88,14 +139,23 @@
api_helpers.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"error": "No user or session found"})
return
}

h.SessionCache.SetSession(cookie.Value, userId)
slog.Debug("ValidateSession user.Id " + openapi_types.UUID(userId).String())
h.respondWithUserDetails(w, r, userId)
}

func (h *SessionHandler) respondWithUserDetails(w http.ResponseWriter, r *http.Request, userId openapi_types.UUID) {
userRepo := repository.NewUserRepository(h.DB)
user, err := userRepo.GetById(r.Context(), userId)
if err != nil {
slog.Warn(err.Error(), "handler", "ValidateSession")
slog.Warn(err.Error(), "handler", "respondWithUserDetails")
api_helpers.RespondWithJSON(w, http.StatusInternalServerError, map[string]string{"error": "Could not find user by user id"})
return
}
api_helpers.RespondWithJSON(w, http.StatusOK, view.NewSessionFromModel(user))
res := make(map[string]string)
res["name"] = user.DisplayName
res["role"] = api_helpers.ConvertUserRequestRoleToString(user.Role)

api_helpers.RespondWithJSON(w, http.StatusOK, res)
}
Loading