guardian

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2023 License: MIT Imports: 10 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

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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 Session

type Session struct {
	ID          string
	Status      SessionStatus          // true = valid false = invalid
	Data        map[string]interface{} // does not map to a strict type because of user preferences
	IdleTime    time.Time
	LifeTime    time.Time
	RenewalTime time.Time
	Cookie      http.Cookie
}

type SessionManager

type SessionManager struct {
	Store Storer

	Infologger     log.Logger    // set as private; public use will come later
	ErrLogger      log.Logger    // set as private; public use will come later
	IdleTimeout    time.Duration //
	Lifetime       time.Duration
	RenewalTimeout time.Duration
	// contains filtered or unexported fields
}

func NewSessionManager

func NewSessionManager(namespace string, store Storer) (SessionManager, error)

create a new session manager using default parameters the namespace given is to ensure things like the context key and session ids are well scoped to session manager instance.

func (*SessionManager) ContextKey

func (s *SessionManager) ContextKey() contextKey

return the context key of the session manager

func (*SessionManager) CreateSession

func (s *SessionManager) CreateSession() Session

create a new session in which data can be stored, the session created is automatically saved in the sessionManager store

func (*SessionManager) InvalidateSession

func (s *SessionManager) InvalidateSession(session Session) Session

delete session from store and set cookie to a time value in the past set session cookie to a time in the past

func (*SessionManager) PopulateRequestContext

func (s *SessionManager) PopulateRequestContext(r *http.Request, session Session) *http.Request

given a request and a session, ensure that the request context contains the session using the context key of the session manager as the key. Also ensure that the values in the already existing context are not affected

func (*SessionManager) RenewSession

func (s *SessionManager) RenewSession(session Session) Session

set a new session id for both the session and the session cookie value and ensure that the store is also updated with the changes

func (*SessionManager) SessionMiddleware

func (s *SessionManager) SessionMiddleware(next http.Handler) http.Handler

what we do in the session middleware: - check the request context if there is a session cookie under the session manager's cookieName - validate the cookie if there exists a corresponding session in the store - watch timeouts of the session - populate the request context with the session data

// when the response is about to be sent - log request context and the response cookie

func (*SessionManager) WatchTimeouts

func (s *SessionManager) WatchTimeouts(session Session) Session

watch timeouts in the order: renewalTime, idleTime and lifeTime; the sessionID is renewed whenever the renewal time is up and the idleTime or lifetime have not elapsed yet for every request, the idletime if not elapsed yet is reset; The idle time however is reset only if it has elapsed the after the idletime and lifetimes have elapsed, the session is invalidated and the session cookie is removed.

type SessionStatus

type SessionStatus int

***** * * SESSION RELATED CODE * *****

const (
	Valid SessionStatus = iota
	Invalid
)

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