设计before_authenticate? [英] Devise before_authenticate?

查看:49
本文介绍了设计before_authenticate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Devise进行身份验证,并且具有可以管理用户的管理员角色.

I use Devise for authentication and I have an admin role who can manage users.

除此之外,管理员还可以锁定用户,以防止他以后登录.我在用户"模型内创建了一个布尔字段,称为"is_locked?".当管理员锁定用户时,此布尔字段设置为true.根据此信息,我可以知道用户是否被锁定.

Apart from this the admin can also lock a user preventing him from logging in the future. I have created a Boolean field inside 'User' model called 'is_locked?'. When the admin locks a user this boolean field is set to true. Based on this info I can know if a user is locked or not.

现在,当用户尝试登录时,在设置会话之前,我必须检查此逻辑.我对在何处添加此逻辑一无所知.或者这是设计提供的任何自定义方法或事件,以便我可以在此处添加.

Now when user tries to log in, before setting up his session, I have to check this logic. I'm clueless about where to add this logic. Or this any custom methods or events which devise provides, so that I can add it there.

推荐答案

我发现您可以在控制器中堆叠before_filter,因此,如果要检查authenticate_user!,也可以使用before_filter(在authenticate_user!之后)以检查锁定的用户.如果用户模型具有布尔属性locked,则可以像下面这样在控制器(或帮助器)中编写私有方法:

I've found that you can stack before_filters in the controller, so if you wanted to check for an authenticate_user!, you could also use a before_filter (after authenticate_user!) to check for a locked user. If the user model has a boolean attribute locked, you can simply write a private method in your controller (or helper) like this:

#top of controller
before_filter authenticate_user!
before_filter user_active!

#bottom of controller
private
def user_active!
  unless current_user.locked?
    return true
  end
  redirect_to root_url, :notice => "Your account is locked."
  return false
end

如果您是未锁定的用户,这将为您提供所需的页面,如果用户被锁定,则会将您重定向至带有错误消息的根页面.

This will give you the page you want if you're an unlocked user, and redirect you to the root page with an error message if the user is locked.

这篇关于设计before_authenticate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆