An implementation of Store using Gorilla web toolkit and the MongoDB Go Driver
- Gorilla web tookit github.com/gorilla
- MongoDB Go Driver github.com/mongodb/mongo-go-driver
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"
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
}
> 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")
}