guardian

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2023 License: MIT Imports: 7 Imported by: 0

README

Guardian: HTTP Session Management for Go

Introduction

Guardian is a Go package that provides HTTP session management functionality.
It allows you to create and manage user sessions in your Go web applications. With Guardian, you can easily store and retrieve session data, set session timeouts, and handle session-related tasks.

Features

  • In-Memory Session Store: Guardian comes with an in-memory session store, making it easy to get started. You can also implement custom session stores if needed.

  • Session Lifecycle Management: Guardian provides features like session expiration, renewal, and invalidation to ensure session data is secure and up-to-date.

  • Middleware Integration: You can easily integrate Guardian into your HTTP handlers using middleware, making session management a seamless part of your application.

  • Customizable: Guardian allows you to configure session timeouts, cookie settings, and more to fit your application's needs.

Installation

Guardian can be installed using Go modules:

$ go get github.com/1jack80/guardian

Basic Usage

Here's a basic example of how to use Guardian to manage sessions in your Go application:

package main

import (
    "net/http"
    "github.com/1jack80/guardian"
)

func main() {
    // Create a new instance of the Guardian session manager with an in-memory store.
    store := guardian.NewInMemoryStore()
    sessionManager := guardian.NewSessionManager("myapp", store)

    // Define your HTTP handlers.
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Create a new session.
        session := sessionManager.CreateSession()
        session.Data["username"] = "user123"
        sessionManager.Store.Save(&session)

        // Use the session.
        // ...

        w.WriteHeader(http.StatusOK)
    })

    // Wrap your handlers with the Guardian middleware.
    http.Handle("/protected", sessionManager.SessionMiddleware(func(w http.ResponseWriter, r *http.Request) {
        session := sessionManager.GetFromContext(r.Context())
        // Access session data and perform actions.
        // ...

        w.WriteHeader(http.StatusOK)
    }))

    // Start your HTTP server.
    http.ListenAndServe(":8080", nil)
}

Documentation

For detailed documentation and additional features, refer to the Guardian documentation.

License

Guardian is licensed under the MIT License. See the LICENSE file for details.

Contributing

We welcome contributions! Feel free to open issues or submit pull requests on the GitHub repository.

Acknowledgments

  • Guardian was inspired by various Go session management packages most especially that of Alex Edwards and the need to advance my go coding skills

  • A special thanks goes to the OWASP and their informative cheatsheet which helped immensely with providing me with a better understanding of how session managers work.

Documentation generated entirely by chatGPT

Documentation

Index

Constants

View Source
const (
	INVALID int = iota
	VALID
)

Variables

This section is empty.

Functions

func ValidateNamespace added in v0.2.0

func ValidateNamespace(name string) error

Types

type InMemoryStore

type InMemoryStore struct {
	// contains filtered or unexported fields
}

InMemoryStore is an in-memory implementation of the Storer interface.

func NewInMemoryStore

func NewInMemoryStore() *InMemoryStore

NewInMemoryStore creates a new instance of InMemoryStore.

func (*InMemoryStore) Delete

func (s *InMemoryStore) Delete(sessionID string) error

delete deletes session data from the in-memory store.

func (*InMemoryStore) Get

func (s *InMemoryStore) Get(sessionID string) (Session, error)

get retrieves session data from the in-memory store.

func (*InMemoryStore) Save

func (s *InMemoryStore) Save(session Session) error

save saves a session into the in-memory store.

func (*InMemoryStore) Update

func (s *InMemoryStore) Update(sessionID string, newSession Session) error

Update updates session data in the in-memory store.

type Manager added in v0.2.0

type Manager struct {
	// contains filtered or unexported fields
}

func NewManager added in v0.2.0

func NewManager(name string, store Storer) (Manager, error)

func (*Manager) ContextKey added in v0.2.0

func (man *Manager) ContextKey() contextKey

acts as an accessor to get the manager's context key as it must not be changed

func (*Manager) CreateCookie added in v0.2.0

func (man *Manager) CreateCookie(sessionID string) (http.Cookie, error)

creates and returns a new cookie using a session

func (*Manager) CreateSession added in v0.2.0

func (man *Manager) CreateSession() Session

create a new session and add it to the store.

func (*Manager) DeleteSession added in v0.2.0

func (man *Manager) DeleteSession(sessionID string) error

a wrapper over the delete method in the store

func (*Manager) GetSession added in v0.2.0

func (man *Manager) GetSession(sessionID string) (Session, error)

func (*Manager) InvalidateSession added in v0.2.0

func (man *Manager) InvalidateSession(sessionID string) error

mark the session as invalid but keep it around until the session expiry time elapses by this time the associated cookie should have also expired then the session can be deleted

func (*Manager) Middleware added in v0.2.0

func (man *Manager) Middleware(next http.Handler) http.Handler

populates the contexts of new requests with the sessions to which the request cookie points. The middleware also extends the session idle times after each request

func (*Manager) PopulateRequestContext added in v0.2.0

func (man *Manager) PopulateRequestContext(r *http.Request, session Session) *http.Request

fill the request context with the given session and returns the updated request

func (*Manager) RenewSession added in v0.2.0

func (man *Manager) RenewSession(sessionID string) (Session, error)

change the session id of the session but maintain the data therein

func (*Manager) SaveSession added in v0.2.0

func (man *Manager) SaveSession(sessonInstance Session) error

func (*Manager) UpdateSession added in v0.2.0

func (man *Manager) UpdateSession(sessionID string, sessionInstance Session) error

type Session

type Session struct {
	ID         string
	Data       map[string]interface{}
	Status     int
	IdleTime   time.Time
	ExpiryTime time.Time
}

type Storer

type Storer interface {
	// retrieve the sesison data from the underlying container
	// and decode it before returning it to the calling function
	Get(sessionID string) (Session, error)

	// save an encoded form of the given session data into
	// the underlying container
	Save(session Session) error

	// delete the session identified by the given sessionID
	Delete(sessionID string) error

	// update parts of the session that identifes with the given sessionID:
	// the new session is used to replace the old session hance,
	// using this function requires that a pointer to the updated
	// copy of the old session is created an passed to this function.
	Update(sessionID string, newSession Session) error
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL