mongostore

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2019 License: MIT Imports: 13 Imported by: 3

README

mongostore

GoDoc Build Status Go Report Card codecov

Gopher Share

An implementation of Store using Gorilla web toolkit and the MongoDB Go Driver

Packages Imported

Installation

The recommended way to get started using github.com/go-stuff/mongostore is by using 'go get' to install the dependency in your project.

go get "github.com/go-stuff/mongostore"

Usage

The github.com/go-stuff/web repository uses github.com/go-stuff/mongostore you can browse this example code to see how it is used.

import "github.com/go-stuff/mongostore"
// create a session store using rotating keys
mongoStore, err := mongostore.NewStore(
    client.Database(DatabaseName).Collection("sessions"),
    http.Cookie{
        Path:     "/",
        Domain:   "",
        MaxAge:   20 * 60, // 20 mins
        Secure:   false,
        HttpOnly: true,
        SameSite: http.SameSiteStrictMode,
    },
    []byte("new-authentication-key"),
    []byte("new-encryption-key"),
    []byte("old-authentication-key"),
    []byte("old-encryption-key"),
)
if err != nil {
    return fmt.Errorf("[ERROR] creating mongo store: %w", err)
}
const CookieName = "session-id"

// new sessions
session, err := s.Store.New(r, CookieName)
if err != nil {
    log.Printf("[ERROR] new session: %s", err.Error())
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

// add values to the session
session.Values["username"] = r.FormValue("username")

// save session
err = session.Save(r, w)
if err != nil {
    log.Printf("[ERROR] saving session: %s", err.Error())
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
const CookieName = "session-id"

// existing sessions
session, err := s.Store.Get(r, CookieName)
if err != nil {
    log.Printf("[ERROR] getting session: %s", err.Error())
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

// add values to the session
session.Values["username"] = r.FormValue("username")

// save session
err = session.Save(r, w)
if err != nil {
    log.Printf("[ERROR] saving session: %s", err.Error())
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

Example MongoDB Entries

> db.sessions.find().pretty()
{
	"_id" : ObjectId("5db388c21256d9f65e6ccf7e"),
	"data" : {
		"username" : "test"
	},
	"modified_at" : ISODate("2019-10-25T23:44:03.558Z"),
	"expires_at" : ISODate("2019-10-26T00:04:03.558Z"),
	"ttl" : ISODate("2019-10-25T23:44:03.558Z")
}
{
	"_id" : ObjectId("5db388cb1256d9f65e6ccf7f"),
	"data" : {
		"username" : "user1"
	},
	"modified_at" : ISODate("2019-10-25T23:44:11.485Z"),
	"expires_at" : ISODate("2019-10-26T00:04:11.485Z"),
	"ttl" : ISODate("2019-10-25T23:44:11.485Z")
}

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MongoSession added in v1.0.0

type MongoSession struct {
	ID       primitive.ObjectID `bson:"_id,omitempty"`
	Data     primitive.M        `bson:"data,omitempty"`
	Modified primitive.DateTime `bson:"modified_at,omitempty"`
	Expires  primitive.DateTime `bson:"expires_at,omitempty"`
	TTL      primitive.DateTime `bson:"ttl,omitemtpy"`
}

MongoSession is how sessions are stored in MongoDB.

type MongoStore

type MongoStore struct {
	*Options
}

MongoStore stores sessions in MongoDB

type Options added in v1.0.0

type Options struct {
	Context    context.Context
	Collection *mongo.Collection
}

Options required for storing data in MongoDB.

type Store added in v1.0.0

type Store struct {
	sessions.CookieStore
	MongoStore
	// contains filtered or unexported fields
}

Store stores sessions in Secure Cookies and MongoDB.

func NewStore added in v1.0.0

func NewStore(col *mongo.Collection, cookie http.Cookie, keyPairs ...[]byte) (*Store, error)

NewStore uses cookies and mongo to store sessions.

Keys are defined in pairs to allow key rotation, but the common case is to set a single authentication key and optionally an encryption key.

The first key in a pair is used for authentication and the second for encryption. The encryption key can be set to nil or omitted in the last pair, but the authentication key is required in all pairs.

It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.

func (*Store) Get added in v1.0.0

func (s *Store) Get(r *http.Request, name string) (*sessions.Session, error)

Get returns a session for the given name after adding it to the registry.

It returns a new session if the sessions doesn't exist. Access IsNew on the session to check if it is an existing session or a new one.

It returns a new session and an error if the session exists but could not be decoded.

func (*Store) New added in v1.0.0

func (s *Store) New(r *http.Request, name string) (*sessions.Session, error)

New returns a session for the given name without adding it to the registry.

The difference between New() and Get() is that calling New() twice will decode the session data twice, while Get() registers and reuses the same decoded session after the first call.

func (*Store) Save added in v1.0.0

func (s *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error

Save adds a single session to the response.

Jump to

Keyboard shortcuts

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