如果用户使用 Hapi.js 登录,则禁用登录路由
Disable login route if a user is logged in with Hapi.js
基本上我的应用程序有一个 login/register 登录页面。用户登录或注册后,我不希望他们能够再访问这条路线。我不确定如何使用 Hapi.js 实现此目的。登录页面不使用任何身份验证策略,因此它不知道用户是否登录。
我通常使用的方法不是禁用路由本身,而是将登录用户从登录路由重定向。
正如您正确指出的那样,如果没有配置身份验证策略,您的登录路由目前不知道用户是否已登录。解决方案是在登录路由中添加一个auth策略,但是使用try模式。这意味着无论身份验证是否成功,都会执行处理程序。诀窍是您可以检查用户是否已通过身份验证(通过检查 request.auth.isAuthenticated
的值)并做出相应的反应。
因此您的路线可能如下所示:
server.route({
config: {
auth: {
strategy: 'session',
mode: 'try'
}
},
method: 'GET',
path: '/login',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
return reply.redirect('/'); // user is logged-in send 'em away
}
return reply.view('login'); // do the login thing
}
});
具有相同结果的另一种方法是将您的身份验证策略设置为 try 模式作为所有路由的默认模式:
server.auth.strategy('session', 'cookie', 'try', {
password: 'password-that-is-longer-than-32-chars',
isSecure: true
});
注意第三个参数 try
。使用这种方法,您不需要向路由本身添加任何身份验证配置,因为默认情况下它会尝试这种策略。根据 server.auth.strategy
文档:
mode
- if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
在 hapi 站点的 Authentication tutorial 中有一些关于模式的更多信息。
基本上我的应用程序有一个 login/register 登录页面。用户登录或注册后,我不希望他们能够再访问这条路线。我不确定如何使用 Hapi.js 实现此目的。登录页面不使用任何身份验证策略,因此它不知道用户是否登录。
我通常使用的方法不是禁用路由本身,而是将登录用户从登录路由重定向。
正如您正确指出的那样,如果没有配置身份验证策略,您的登录路由目前不知道用户是否已登录。解决方案是在登录路由中添加一个auth策略,但是使用try模式。这意味着无论身份验证是否成功,都会执行处理程序。诀窍是您可以检查用户是否已通过身份验证(通过检查 request.auth.isAuthenticated
的值)并做出相应的反应。
因此您的路线可能如下所示:
server.route({
config: {
auth: {
strategy: 'session',
mode: 'try'
}
},
method: 'GET',
path: '/login',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
return reply.redirect('/'); // user is logged-in send 'em away
}
return reply.view('login'); // do the login thing
}
});
具有相同结果的另一种方法是将您的身份验证策略设置为 try 模式作为所有路由的默认模式:
server.auth.strategy('session', 'cookie', 'try', {
password: 'password-that-is-longer-than-32-chars',
isSecure: true
});
注意第三个参数 try
。使用这种方法,您不需要向路由本身添加任何身份验证配置,因为默认情况下它会尝试这种策略。根据 server.auth.strategy
文档:
mode
- if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
在 hapi 站点的 Authentication tutorial 中有一些关于模式的更多信息。