路由器中的Hapijs会话

时间:2015-08-12 10:24:32

标签: javascript node.js authentication session-cookies hapijs

有没有办法在Hapijs服务器路由中的不同路由上使用会话信息,这些会话信息在用户成功登录时从数据库加载了用户数据?

index.js

var Hapi = require('hapi');
var server = new Hapi.Server();

var routeManager = require('./routes/manager');
server.connection({ host: "localhost", port: 8000 });

server.register(require('hapi-auth-cookie'), function (err) {
    server.auth.strategy('base', 'cookie', {
        password: 'somesecret',
        cookie: 'app-cookie',
        isSecure: false
    });
});

server.route(routeManager.loginRoutes);

server.start(function(){
    console.log('application started running on: '+JSON.stringify(server.info.uri));
});`

manager.js

`var users = {
    john: {
        id: 'john',
        password: 'pass',
        name: 'John Doe',
        scope: "admin"
    }
};

var loginRoutes = [
    {
        method: 'GET',
        path: '/',
        config: {
            auth: false,
            handler: function homePageHandler(request, reply) {
                return reply('Home Page');
            }
        }
    },
    {
        method: ['GET', 'POST'],
        path: '/login/{user}',
        config: {
            auth: false,
            handler: function(request, reply){
                if(request.params.user === users[request.params.user].id) {
                    request.auth.session.set(users[request.params.user]);
                    console.log("login auth info: "+JSON.stringify(request.auth))
                    reply("Hello, "+users[request.params.user].name);
                }
            }
        }
    },
    {
        method: ['GET', 'POST'],
        path: '/logout/{user}',
        config: {
            auth: {
                strategy: 'base'
            },
            handler: function(request, reply){
                console.log("logout auth info: "+JSON.stringify(request.auth))
                request.auth.session.clear();
                return reply("You are logged out");
            }
        }
    }
];

exports.loginRoutes = loginRoutes;`

1 个答案:

答案 0 :(得分:2)

我建议您使用hapi-auth-cookie

在您的应用设置中,您可以像这样配置:

server.register(require('hapi-auth-cookie'), function (err) {
    if (err) {
        console.error(err);
    }
    server.auth.strategy('session', 'cookie', {
        password: 'aReallyBigSecret',
        cookie: 'sid-ws',
        redirectTo: '/login',
        isSecure: false
    });
});

然后在您的路线中,您可以将它们配置为使用身份验证:

method: 'GET',
path: '/aRoute',
handler: function (request, reply) {
    console.log('request.auth.credentials');
},
config: {
    auth: 'session'
}

要初步创建会话,您需要为会话设置一些数据:

method: 'POST',
path: '/sessions',
handler: function (request, reply) {
    var account = {id: 'userId', username:"hapiUser", accountType:"admin"};
    request.auth.session.set(account);
    return reply(account);
}

这显然不安全;您希望对某种类型的数据库进行某种查找以实际验证您的用户。