I have a default auth setting and want to add a route with options.auth.mode = optional. This results in an error.
When scope is present in the default auth settings a route with auth options but without options.auth.access.scope will result in an error.
The scope of the default auth settings is stored in the expanded form, which is not compatible with how the routes are configured.
Example to provoke the error:
'use strict';
const Hapi = require('@hapi/hapi');
const validate = async (request, username, password, h) => {
return { isValid: true };
};
const main = async () => {
const server = Hapi.server({ port: 4000 });
await server.register(require('@hapi/basic'));
server.auth.strategy('simple', 'basic', { validate });
server.auth.default({
strategy: 'simple',
access: {
scope: [ 'user' ]
}
});
server.route({
method: 'GET',
path: '/',
options: {
auth: {
mode: 'optional'
}
},
handler: function (request, h) {
return 'welcome';
}
});
await server.start();
return server;
};
main()
.then((server) => console.log(`Server listening on ${server.info.uri}`))
.catch((err) => {
console.error(err);
process.exit(1);
});
I used an online editor to create this example, and it didn't support v19 of hapi, but looking at the code the result should be the same.
TypeError: access.scope is not iterable
at Object.internals.setupScope (/home/runner/LimeImpracticalStaff/node_modules/@hapi/hapi/lib/auth.js:424:32)
at module.exports.internals.Auth._setupRoute (/home/runner/LimeImpracticalStaff/node_modules/@hapi/hapi/lib/auth.js:172:42)
at new module.exports.internals.Route (/home/runner/LimeImpracticalStaff/node_modules/@hapi/hapi/lib/route.js:139:71)
at internals.Server._addRoute (/home/runner/LimeImpracticalStaff/node_modules/@hapi/hapi/lib/server.js:485:23)
at internals.Server.route (/home/runner/LimeImpracticalStaff/node_modules/@hapi/hapi/lib/server.js:478:22)
at main (/home/runner/LimeImpracticalStaff/index.js:23:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
The error happens because access.scope = { selection: [ 'user' ] } is not an array, here: https://github.com/hapijs/hapi/blob/v18.4.1/lib/auth.js#L424.
The route should use the default scope.
@hovmand Looking at the API reference, looks like the default scope should be specified as access.scope. Does that fix your issue?
Hi @jonathansamines That was a small inconsistency in my end. You are correct it should.
But, the result is the same.
I've updated the example. Please verify that was what you meant?
(Looks like this backwards compatibility helped me: https://github.com/hapijs/hapi/blob/v18.4.1/lib/auth.js#L165)
Resolved by #4089. Thanks for the contribution @jonathansamines!