Coder Social home page Coder Social logo

session-manager's Introduction

Session Manager

Table of Contents

About

Light-weight session in-memory session manager for golang

Install

$ go get github.com/vpatel95/session-manager

Usage

  1. Import the package using

    import sm "github.com/vpatel95/session-manager"
  2. Create a SessionManager object

    manager := sm.New()
    
    // The default configs for session manager and cookie will be as follow
    Config: SessionManagerConfig{
    	CleanerInterval:    1 * time.Minute,
    	MaxLifetime:        24 * time.Hour,
    	EnableHttpHeader:   false,
    	SessionHeader:      "",
    	AutoRefreshSession: false,
    },
    Cookie: SessionCookie{
    	Name:     "sessionid",
    	Domain:   "",
    	HTTPOnly: true,
    	Secure:   false,
    	Lifetime: 24 * time.Hour,
    },
  3. SessionManager Operations

    func (sm *SessionManager) GetSessionId(r *http.Request) (string, error) 		// extract session ID from request
    func (sm *SessionManager) ListSessions() 				    		// Print all the sessions in the manager
    func (sm *SessionManager) SessionCount() int			    		// returns number of sessions in the manager
    func (sm *SessionManager) SessionRefresh(oldSid, sid string) (*Session, error)	// change the session Id for the session
    func (sm *SessionManager) SessionExist(sid string) bool				// check if session with session Id exists
    func (sm *SessionManager) SessionUpdate(sid string) error 				// update last access time for the session
    func (sm *SessionManager) SessionDestroy(sid string) error 				// delete session with given session Id
    func (sm *SessionManager) SessionRead(r *http.Request) (*Session, error) 		// retreive the session
    func (sm *SessionManager) SessionCreate(sid string) (*Session, error) 		// create a new session
    func (sm *SessionManager) SessionReadOrCreate(r *http.Request) (*Session, error)    // retreive the session, if not existing create a new session
  4. Session operations

    func (s *Session) Get(key interface{}) interface{}	// to get value for 'key' from the session
    func (s *Session) Set(key, sd interface{}) error    // to set value for 'key in the session
    func (s *Session) Exist(key interface{}) bool      	// returns bool if 'key' exists in the session
    func (s *Session) Delete(key interface{}) error     // delete 'key' from the session
    

Example

This is an example of a middleware that verifies the session and sets "user" key in the session

func ValidateSessionID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sessId, err := sessManager.GetSessionId(r)
		if err != nil {
			next.ServeHTTP(w, r)
			return
		}

		data, err := getTokenData(sessId)
		if err != nil {
			next.ServeHTTP(w, r)
			return
		}

		var user User
		user.Load(data["user"].(JSON))

		sess, err := sessManager.SessionReadOrCreate(r)
		if err != nil {
			log.Println("[ValidateSessionID] ::: Failed to get session : " + err.Error())
			next.ServeHTTP(w, r)
			return
		}

		sess.Set("user", user)
		next.ServeHTTP(w, r)
	})
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.