Skip to content

Commit

Permalink
✨ feat: add Delete method to Store struct in session middleware (#2655)
Browse files Browse the repository at this point in the history
* ✨ feat: add Delete method to Store struct in session middleware

* ♻ refactor: enhance Delete method and test cases in session middleware
  • Loading branch information
kaptinlin authored Oct 2, 2023
1 parent fa88733 commit d86c257
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/api/middleware/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
12 changes: 12 additions & 0 deletions middleware/session/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package session

import (
"encoding/gob"
"errors"
"fmt"
"sync"

Expand All @@ -12,6 +13,9 @@ import (
"github.com/valyala/fasthttp"
)

// ErrEmptySessionID is an error that occurs when the session ID is empty.
var ErrEmptySessionID = errors.New("session id cannot be empty")

type Store struct {
Config
}
Expand Down Expand Up @@ -140,3 +144,11 @@ func (s *Store) responseCookies(c *fiber.Ctx) (string, error) {
func (s *Store) Reset() error {
return s.Storage.Reset()
}

// Delete deletes a session by its id.
func (s *Store) Delete(id string) error {
if id == "" {
return ErrEmptySessionID
}
return s.Storage.Delete(id)
}
31 changes: 31 additions & 0 deletions middleware/session/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,34 @@ func TestStore_Get(t *testing.T) {
utils.AssertEqual(t, unexpectedID, acquiredSession.ID())
})
}

// go test -run TestStore_DeleteSession
func TestStore_DeleteSession(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)
utils.AssertEqual(t, err, nil)

// Save the session ID
sessionID := session.ID()

// Delete the session
err = store.Delete(sessionID)
utils.AssertEqual(t, err, nil)

// Try to get the session again
session, err = store.Get(ctx)
utils.AssertEqual(t, err, nil)

// The session ID should be different now, because the old session was deleted
utils.AssertEqual(t, session.ID() == sessionID, false)
}

0 comments on commit d86c257

Please sign in to comment.