Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upgrade to official mongo go driver #12 #13

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ _cgo_export.*
_testmain.go

*.exe
go.mod
go.sum
21 changes: 17 additions & 4 deletions mgostore_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
// Copyright (c) 2013 Gregor Robinson.
// Copyright (c) 2013 Brian Jones.
// Copyright (c) 2021 Oyewol Samuel.
// All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package mongostore

import (
"context"
"encoding/gob"
"net/http"
"net/http/httptest"
"os"
"testing"

"github.com/globalsign/mgo"
"github.com/gorilla/sessions"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

type FlashMessage struct {
Expand All @@ -36,13 +40,22 @@ func TestMongoStore(t *testing.T) {
// license that can be found in the LICENSE file.

// Round 1 ----------------------------------------------------------------
dbsess, err := mgo.Dial("localhost")
mongosrv := os.Getenv("<MONGODB_URI>")
client, err := mongo.NewClient(options.Client().ApplyURI(mongosrv))
if err != nil {
panic(err)
}
defer dbsess.Close()

store := NewMongoStore(dbsess.DB("test").C("test_session"), 3600, true,
if err := client.Connect(context.Background()); err != nil {
panic(err)
}

defer client.Disconnect(context.Background())

store := NewMongoStore(
client.Database("test").Collection("test_session"),
3600,
true,
[]byte("secret-key"))

req, _ = http.NewRequest("GET", "http://localhost:8080/", nil)
Expand Down
78 changes: 44 additions & 34 deletions mongostore.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,26 @@
package mongostore

import (
"context"
"errors"
"net/http"
"time"

"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

var (
ErrInvalidId = errors.New("mgostore: invalid session id")
ErrInvalidId = errors.New("mongostore: invalid session id")
)

// Session object store in MongoDB
type Session struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Id primitive.ObjectID `bson:"_id,omitempty"`
Data string
Modified time.Time
}
Expand All @@ -31,13 +34,12 @@ type MongoStore struct {
Codecs []securecookie.Codec
Options *sessions.Options
Token TokenGetSeter
coll *mgo.Collection
coll *mongo.Collection
}

// NewMongoStore returns a new MongoStore.
// Set ensureTTL to true let the database auto-remove expired object by maxAge.
func NewMongoStore(c *mgo.Collection, maxAge int, ensureTTL bool,
keyPairs ...[]byte) *MongoStore {
func NewMongoStore(c *mongo.Collection, maxAge int, ensureTTL bool, keyPairs ...[]byte) *MongoStore {
store := &MongoStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Expand All @@ -51,27 +53,30 @@ func NewMongoStore(c *mgo.Collection, maxAge int, ensureTTL bool,
store.MaxAge(maxAge)

if ensureTTL {
c.EnsureIndex(mgo.Index{
Key: []string{"modified"},
Background: true,
Sparse: true,
ExpireAfter: time.Duration(maxAge) * time.Second,
})
expireAfter := time.Duration(maxAge) * time.Second

indexModel := mongo.IndexModel{
Keys: bson.M{"modified": 1},
Options: options.Index().SetExpireAfterSeconds(int32(expireAfter.Seconds())),
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

c.Indexes().CreateOne(ctx, indexModel)
}

return store
}

// Get registers and returns a session for the given name and session store.
// It returns a new session if there are no sessions registered for the name.
func (m *MongoStore) Get(r *http.Request, name string) (
*sessions.Session, error) {
func (m *MongoStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(m, name)
}

// New returns a session for the given name without adding it to the registry.
func (m *MongoStore) New(r *http.Request, name string) (
*sessions.Session, error) {
func (m *MongoStore) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(m, name)
session.Options = &sessions.Options{
Path: m.Options.Path,
Expand All @@ -97,8 +102,7 @@ func (m *MongoStore) New(r *http.Request, name string) (
}

// Save saves all sessions registered for the current request.
func (m *MongoStore) Save(r *http.Request, w http.ResponseWriter,
session *sessions.Session) error {
func (m *MongoStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
if session.Options.MaxAge < 0 {
if err := m.delete(session); err != nil {
return err
Expand All @@ -115,8 +119,7 @@ func (m *MongoStore) Save(r *http.Request, w http.ResponseWriter,
return err
}

encoded, err := securecookie.EncodeMulti(session.Name(), session.ID,
m.Codecs...)
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, m.Codecs...)
if err != nil {
return err
}
Expand All @@ -139,30 +142,31 @@ func (m *MongoStore) MaxAge(age int) {
}
}

func (m *MongoStore) load(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
func (m *MongoStore) load(session *sessions.Session) error {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}

s := Session{}
err := m.coll.FindId(bson.ObjectIdHex(session.ID)).One(&s)
if err != nil {
if err := m.coll.FindOne(context.Background(), bson.M{"_id": objID}).Decode(&s); err != nil {
return err
}

if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values,
m.Codecs...); err != nil {
if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values, m.Codecs...); err != nil {
return err
}

return nil
}

func (m *MongoStore) upsert(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}


var modified time.Time
if val, ok := session.Values["modified"]; ok {
modified, ok = val.(time.Time)
Expand All @@ -173,30 +177,36 @@ func (m *MongoStore) upsert(session *sessions.Session) error {
modified = time.Now()
}

encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
m.Codecs...)
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, m.Codecs...)
if err != nil {
return err
}

s := Session{
Id: bson.ObjectIdHex(session.ID),
Id: objID,
Data: encoded,
Modified: modified,
}

_, err = m.coll.UpsertId(s.Id, &s)
if err != nil {
opts := options.Update().SetUpsert(true)
filter := bson.M{"_id": s.Id}
updateData := bson.M{"$set": s}

if _, err = m.coll.UpdateOne(context.Background(), filter, updateData, opts); err != nil {
return err
}

return nil
}

func (m *MongoStore) delete(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}

return m.coll.RemoveId(bson.ObjectIdHex(session.ID))
if _, err = m.coll.DeleteOne(context.Background(), bson.M{"_id": objID}); err != nil {
return err
}
return nil
}