Skip to content

Commit

Permalink
Fix redirectTo function w/ blank to behave like blank redirectTo (#183)
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip Lanclos authored and mrlannigan committed Feb 8, 2018
1 parent d3e0d83 commit 3361ea6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ The `'cookie`' scheme takes the following options:
- `isSecure` - if `false`, the cookie is allowed to be transmitted over insecure connections which
exposes it to attacks. Defaults to `true`.
- `isHttpOnly` - if `false`, the cookie will not include the 'HttpOnly' flag. Defaults to `true`.
- `redirectTo` - optional login URI to redirect unauthenticated requests to. Note that using
- `redirectTo` - optional login URI or function `function(request)` that returns a URI to redirect unauthenticated requests to. Note that using
`redirectTo` with authentication mode `'try'` will cause the protected endpoint to always
redirect, voiding `'try'` mode. To set an individual route to use or disable redirections, use
the route `plugins` config (`{ options: { plugins: { 'hapi-auth-cookie': { redirectTo: false } } } }`).
Expand Down
5 changes: 3 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,12 @@ internals.implementation = (server, options) => {
redirectTo = request.route.settings.plugins['hapi-auth-cookie'].redirectTo;
}

if (!redirectTo) {
let uri = (typeof (redirectTo) === 'function') ? redirectTo(request) : redirectTo;

if (!uri) {
return h.unauthenticated(err);
}

let uri = (typeof (redirectTo) === 'function') ? redirectTo(request) : redirectTo;
if (settings.appendNext) {
if (uri.indexOf('?') !== -1) {
uri += '&';
Expand Down
27 changes: 27 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,33 @@ describe('scheme', () => {
expect(res.statusCode).to.equal(401);
});

it('skips when redirectTo is set to function that returns falsey value', async () => {

const server = Hapi.server();
await server.register(require('../'));

server.auth.strategy('default', 'cookie', {
password: 'password-should-be-32-characters',
ttl: 60 * 1000,
redirectTo: () => false,
appendNext: true
});
server.auth.default('default');

server.route({
method: 'GET',
path: '/',
handler: function (request, h) {

return h.response('never');
}
});

const res = await server.inject('/');

expect(res.statusCode).to.equal(401);
});

it('skips when route override', async () => {

const server = Hapi.server();
Expand Down

0 comments on commit 3361ea6

Please sign in to comment.