Sign users in with the built-in session auth
Instead of a function, AUTH(options) accepts an options object and installs a complete cookie-session authentication:
secretsigns the cookie,cookieis its name andexpirehow long a session stays in memory without activityonread(meta, next, $)loads the user when a valid cookie arrives from a session that is not in memory (for example after a restart); callnext(null, user), ornext('not found')to refuse. Check that the session still exists in your own store here, otherwise a copied cookie keeps working after the user signed outonlogout(session)andonremove(sessionid)run when a session is removed: delete it from your storeoptions.authcookie($, sessionid, userid, expiration)signs the user in: it writes the signed cookie to the responseoptions.logout($)removes the session and the cookie
Keep the options object in a variable: it is the handle you use to sign users in and out. After that, $.user is set and + and - routes work as in the AUTH recipe.
var users = {
'1': { id: '1', name: 'Anna', password: 'secret' }
};
// sessionid -> userid. In a real app this is a database table.
MAIN.sessions = {};
MAIN.auth = {
secret: 'change-this-secret',
cookie: 'forge_session',
expire: '1 day',
onread: function(meta, next) {
var user = users[MAIN.sessions[meta.sessionid]];
user ? next(null, { id: user.id, name: user.name }) : next('session not found');
},
onlogout: function(session) {
delete MAIN.sessions[session.sessionid];
},
onremove: function(sessionid) {
delete MAIN.sessions[sessionid];
}
};
AUTH(MAIN.auth);exports.install = function() {
ROUTE('POST /login/', login);
ROUTE('+POST /logout/', logout);
ROUTE('+GET /me/', me);
};
function login($) {
var user = $.body.id && $.body.id === '1' && $.body.password === 'secret' ? { id: '1', name: 'Anna' } : null;
if (!user) {
$.invalid(401);
return;
}
var sessionid = UID();
MAIN.sessions[sessionid] = user.id;
MAIN.auth.authcookie($, sessionid, user.id, '1 day');
$.json({ name: user.name });
}
function logout($) {
MAIN.auth.logout($);
$.json({ ok: true });
}
function me($) {
$.json({ name: $.user.name });
}