Hapi js API基本身份验证错误

时间:2018-02-05 08:36:53

标签: node.js hapijs

我正在研究hapi js API基本身份验证,并且我正在使用有关身份验证的Hapi文档。我相信我做的一切都是正确的,但我得到关于UnhandledPromiseRejectionWarning的关注错误。请帮忙

index.js

TypeError: 'float' object cannot be interpreted as an integer.

的package.json

'use strict';

const Bcrypt = require('bcrypt');
const Hapi = require('hapi');
const Basic = require('hapi-auth-basic');

const server = new Hapi.Server({
  host: 'localhost',
  port: 3000
})

const users = {
    john: {
        username: 'john',
        password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',  
        name: 'John Doe',
        id: '2133d32a'
    }
};

const validate = function (request, username, password, callback) {
    const user = users[username];
    if (!user) {
        return callback(null, false);
    }

Bcrypt.compare(password, user.password, (err, isValid) => {
    callback(err, isValid, { id: user.id, name: user.name });
});
};

server.register(Basic, (err) => {

if (err) {
    throw err;
}

server.auth.strategy('simple', 'basic', { validateFunc: validate });
server.route({
    method: 'GET',
    path: '/',
    config: {
        auth: 'simple',
        handler: function (request, reply) {
            reply('hello, ' + request.auth.credentials.name);
        }
    }
});

server.start((err) => {

    if (err) {
        throw err;
    }

    console.log('server running at: ' + server.info.uri);
});
});

错误

    "bcrypt": "^1.0.3",
    "hapi-auth-basic": "^5.0.0",
    "hapi": "^17.1.0"

1 个答案:

答案 0 :(得分:2)

如果您希望该代码有效,则必须使用低于17的版本,即(16.6.2),或者查找更新为您正在使用的hapi版本的代码。

const Bcrypt = require('bcrypt');
const Hapi = require('hapi');

const users = {
john: {
    username: 'john',
    password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',   // 'secret'
    name: 'John Doe',
    id: '2133d32a'
}
};

const validate = async (request, username, password, h) => {

if (username === 'help') {
    return { response: h.redirect('https://hapijs.com/help') };     // custom response
}

const user = users[username];
if (!user) {
    return { credentials: null, isValid: false };
}

const isValid = await Bcrypt.compare(password, user.password);
const credentials = { id: user.id, name: user.name };

return { isValid, credentials };
};

const main = async () => {

const server = Hapi.server({ port: 4000 });

await server.register(require('hapi-auth-basic'));

server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');

server.route({
    method: 'GET',
    path: '/',
    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);
});