Skip to main content

Getting Started

Installation

npm install gatekeeper-authentication

Initialization

Initializing your session module

Gatekeeper uses sessions to store the user data, thus, it is very important that you initialize the session module of your preference before initializing Gatekeeper. Throughout this documentation we will be using express-session.

In case you are using express-session, these are our recommended settings:

app.use(session({
secret: '<YOUR SESSION SECRET>',
resave: true,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10, // session max age in millisecond
},
sameSite: 'lax' // or 'strict' if your client and server have the same origin url
}));

Initializing Gatekeeper

To initialize Gatekeeper you just have to pass gatekeeper.initialize({ userSerializer, userDeserializer }) as an express middleware (make sure to do it after you initialize your session module). Let's see an example:

import gatekeeper from 'gatekeeper-authentication';
import express from 'express';
import session from 'express-session';

const app = express();

app.use(session({
secret: 'I love Grothendieck Universes!'
}));

app.use(gatekeeper.initialize({
userSerializer: (user) => user.id,
userDeserializer: (id) => {
/* Here we are returning an arbitrary user
for the sake of the example */
return { id: id, username: 'David Hilbert' };
}
}));

And with this, Gatekeeper is already initialized! Nonetheless, as you saw, we had to pass an object with two properties: userSerializer and userDeserealizer.

But... What is a User Serializer?

A user serializer is a function that accepts a user object and returns a key that should be stored in the session. The key will then be used by the User Deserealizer to retrieve the user.

Example

function userSerializer(user) {
/* For example, the user's id will allow us to
retrieve the user later when the user deserializer
gets called internally by gatekeeper */
return user.id;
}

User Deserealizer

A user deserealizer is a function that accepts a key and returns a user object.

Example

function userDeserializer(key) {
/* Use the key (in this particular case, the user id)
to retrieve the user */
const user = User.findOne({ id: key });
return user;
}

Now that Gatekeeper is initialized, we can start learning about, and implementing, the concept of Provider