Skip to content

Commit

Permalink
cookie scheme
Browse files Browse the repository at this point in the history
  • Loading branch information
Eran Hammer committed Apr 20, 2013
1 parent 19f3060 commit a8fce5e
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 30 deletions.
104 changes: 99 additions & 5 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -669,17 +669,111 @@ anyone in possession of the cookie content can use it to imperssonate its true o
- `ttl` - sets the cookie expires time in milliseconds. Defaults to single browser session (ends when browser closes).
- `clearInvalid` - if `true`, any authentication cookie that fails validation will be marked as expired in the response and cleared. Defaults to `false`.
- `isSecure` - if `false`, the cookie is allowed to be transmitted over insecure connections which exposes it to attacts. Defaults to `false`.
- `redirectTo` - optional login URI to redirect unauthenticated requests to. Defaults to no redirection.
- `appendNext` - if `true` and `redirectTo` is `true`, appends the current request path to the query component of the `redirectTo` URI using the
parameter name `'next'`. Set to a string to use a different parameter name. Defaults to `false`.
- `validateFunc` - an optional session validation function used to validate the content of the session cookie on each request. Used to verify that the
internal session state is still valid (e.g. user account still exists). The function has the signature `function(session, callback)` where:
- `session` - is the session object set via `request.auth.session.set()`.
- `callback` - the callback function with signature `(err, override)` where:
- `err` - indicates that authentication failed.
- `override` - object will change any cookie properties when setting state on the response.
- `callback` - a callback function with the signature `function(err, isValid, credentials)` where:
- `err` - an internal error.
- `isValid` - `true` if the content of the session is valid, otherwise `false`.
- `credentials` - a crendetials object passed back to the application in `request.auth.credentials`. If value is `null` or `undefined`,
defaults to `session`. If set, will override the current cookie as if `request.auth.session.set()` was called.

When the cookie scheme is enabled on a route, the `request.auth.session` objects is decorated with two methods:
- `set(session)` -
- `clear()` -
- `set(session)` - sets the current session. Must be called after a successful login to begin the session. `session` must be a non-null object,
which is set on successful subsequent authentications in `request.auth.credentials`.
- `clear()` - clears the current session. Used to logout a user.

```javascript
var Hapi = require('../lib');

var users = {
john: {
id: 'john',
password: 'password',
name: 'John Doe'
}
};

var home = function () {

this.reply('<html><head><title>Login page</title></head><body><h3>Welcome '
+ this.auth.credentials.name
+ '!</h3><br/><form method="get" action="/logout">'
+ '<input type="submit" value="Logout">'
+ '</form></body></html>');
};


var login = function () {

if (this.auth.isAuthenticated) {
return this.reply.redirect('/');
}

var message = '';
var account = null;

if (this.method === 'post') {

if (!this.payload.username ||
!this.payload.password) {

message = 'Missing username or password';
}
else {
account = users[this.payload.username];
if (!account ||
account.password !== this.payload.password) {

message = 'Invalid username or password';
}
}
}

if (this.method === 'get' ||
message) {

return this.reply('<html><head><title>Login page</title></head><body>'
+ (message ? '<h3>' + message + '</h3><br/>' : '')
+ '<form method="post" action="/login">'
+ 'Username: <input type="text" name="username"><br>'
+ 'Password: <input type="password" name="password"><br/>'
+ '<input type="submit" value="Login"></form></body></html>');
}

this.auth.session.set(account);
return this.reply.redirect('/');
};


var logout = function () {

this.auth.session.clear();
return this.reply.redirect('/');
};


var http = new Hapi.Server('localhost', 8000, config);

server.auth('session', {
scheme: 'cookie',
password: 'secret',
cookie: 'sid-example',
redirectTo: '/login'
});

http.route([
{ method: 'GET', path: '/', config: { handler: home, auth: true } },
{ method: 'GET', path: '/login', config: { handler: login, auth: { mode: 'try' } } },
{ method: 'POST', path: '/login', config: { handler: login, auth: { mode: 'try' } } },
{ method: 'GET', path: '/logout', config: { handler: logout, auth: true } }
]);

http.start();
```

##### Hawk Authentication

Expand Down
20 changes: 2 additions & 18 deletions examples/cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,6 @@ internals.users = {
};


internals.validateCookie = function (session, callback) {

// Validate session if needed to ensure session is still valid

callback(null, null);
};


internals.home = function (request) {

request.reply('<html><head><title>Login page</title></head><body><h3>Welcome ' + request.auth.credentials.name + '!</h3><br/><form method="get" action="/logout"><input type="submit" value="Logout"></form></body></html>');
Expand Down Expand Up @@ -81,17 +73,9 @@ internals.main = function () {
auth: {
scheme: 'cookie',
password: 'secret',
ttl: 60 * 1000, // Expire after a minute
cookie: 'sid', // Cookie name
clearInvalid: true,
validateFunc: internals.validateCookie,
cookie: 'sid-example',
redirectTo: '/login',
allowInsecure: true
},
state: {
cookies: {
clearInvalid: true
}
isSecure: false
}
};

Expand Down
15 changes: 9 additions & 6 deletions lib/auth/cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,23 @@ internals.Scheme.prototype.authenticate = function (request, callback) {
return callback(null, session);
}

self.settings.validateFunc(session, function (err, override) {
self.settings.validateFunc(session, function (err, isValid, credentials) {

if (err ||
!isValid) {

if (err) {
if (self.settings.clearInvalid) {
request.clearState(self.settings.cookie);
}

return unauthenticated(Boom.unauthorized('Invalid cookie'), session, { log: { data: err } });
return unauthenticated(Boom.unauthorized('Invalid cookie'), session, { log: (err ? { data: err } : 'Failed validation') });
}

if (override) {
request.setState(self.settings.cookie, override);
if (credentials) {
request.setState(self.settings.cookie, credentials);
}

return callback(null, override || session);
return callback(null, credentials || session);
});
};

Expand Down Expand Up @@ -117,6 +119,7 @@ internals.Scheme.prototype.extend = function (request) {
request.auth.session = {
set: function (session) {

Utils.assert(session && typeof session === 'object', 'Invalid session');
request.setState(self.settings.cookie, session);
},
clear: function () {
Expand Down
2 changes: 1 addition & 1 deletion test/integration/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,7 @@ describe('Auth', function () {
var override = Hapi.utils.clone(session);
override.something = 'new';

return callback(session.user === 'valid' ? null : new Error('bad user'), override);
return callback(null, session.user === 'valid', override);
}
};

Expand Down

0 comments on commit a8fce5e

Please sign in to comment.