Reputation: 14189
I have created this simple plugin:
import bcrypt from 'bcrypt';
import Joi from 'joi';
import DynamoDBClient from '../lib/DynamoDBClient';
exports.register = (server, options, next) => {
server.auth.strategy('simple', 'basic', {
validateFunc: (request, email, password, callback) => {
DynamoDBClient.findUserByEmail(email)
.then(user => {
if (!user) {
return callback(null, false);
}
bcrypt.compare(password, user.password, (err, isValid) => {
return callback(err, isValid, { id: user.id });
});
});
}
});
server.route({
method: 'POST',
path: '/api/login',
config: {
auth: 'simple',
validate: {
payload: {
email: Joi.string().required(),
password: Joi.string().required()
}
}
},
handler: (request, reply) => reply(request.auth.credentials.id)
});
next();
};
exports.register.attributes = {
name: 'login',
};
and loaded the manifest here:
import Glue from 'glue';
const manifest = {
server: {},
connections: [
{
port: process.env.PORT || 3001,
labels: ['api']
}
],
plugins: {
'hapi-auth-basic': {},
'./api/signup': {},
'./api/login': {},
'./api/products': {},
}
};
const options = {
relativeTo: __dirname
};
Glue.compose(manifest, options, (err, server) => {
if (err) {
throw err;
}
server.start(() => console.log(`Listening to ${server.info.uri}`));
});
but I get this error
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Missing authentication"
}
when I try to login passing a POST request with email and password as body params.
Upvotes: 1
Views: 1149
Reputation: 1545
I think that your /api/login
route should not be protected by an authentication scheme otherwise, you would have to be authenticated to authenticate. Chicken and egg problem... All your other routes should be.
In other words, the login (and like logout?) routes should not be secured.
Upvotes: 2