diff --git a/docs/api/middleware/session.md b/docs/api/middleware/session.md index 9dc68f217d3..631599598c6 100644 --- a/docs/api/middleware/session.md +++ b/docs/api/middleware/session.md @@ -16,6 +16,7 @@ This middleware uses our [Storage](https://github.com/gofiber/storage) package t func New(config ...Config) *Store func (s *Store) RegisterType(i interface{}) func (s *Store) Get(c *fiber.Ctx) (*Session, error) +func (s *Store) Delete(id string) error func (s *Store) Reset() error func (s *Session) Get(key string) interface{} diff --git a/middleware/session/session.go b/middleware/session/session.go index ebe00f6057b..123748b3970 100644 --- a/middleware/session/session.go +++ b/middleware/session/session.go @@ -276,3 +276,11 @@ func (s *Session) delSession() { fasthttp.ReleaseCookie(fcookie) } } + +// Delete deletes a session by its id +func (s *Store) Delete(id string) error { + if len(id) == 0 { + return fmt.Errorf("session id cannot be empty") + } + return s.Storage.Delete(id) +} diff --git a/middleware/session/store_test.go b/middleware/session/store_test.go index 06c45f9b103..26e52719d61 100644 --- a/middleware/session/store_test.go +++ b/middleware/session/store_test.go @@ -85,3 +85,41 @@ func TestStore_Get(t *testing.T) { utils.AssertEqual(t, unexpectedID, acquiredSession.ID()) }) } + +// go test -run TestStore_Delete +func TestStore_Delete(t *testing.T) { + t.Parallel() + // fiber instance + app := fiber.New() + // session store + store := New() + + // fiber context + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) + + // Create a new session + session, err := store.Get(ctx) + if err != nil { + t.Fatal(err) + } + + // Save the session ID + sessionID := session.ID() + + // Delete the session + if err := store.Delete(sessionID); err != nil { + t.Fatal(err) + } + + // Try to get the session again + session, err = store.Get(ctx) + if err != nil { + t.Fatal(err) + } + + // The session ID should be different now, because the old session was deleted + if session.ID() == sessionID { + t.Errorf("The session was not deleted, the session ID is still the same") + } +}