[英]Devise: Log user out after the confirmation period ends
Devise 有一种方法允许用户登录而无需通过设置 allow_unconfirmed_access_for 配置变量立即确认其 email。
我有一个设置,用于在确认期结束后将用户从应用程序中注销。 另外,我需要用户只在晚上 2 点注销。
为此,我覆盖了confirmation_period_valid? devise 的可确认模块中的一些自定义逻辑的方法 -
原装 Devise 方法 -
def confirmation_period_valid?
return true if self.class.allow_unconfirmed_access_for.nil?
return false if self.class.allow_unconfirmed_access_for == 0.days
confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago
end
我在用户 model 文件中定义的覆盖方法。
def confirmation_period_valid?
confirmation_time = confirmation_sent_at.in_time_zone(time_zone).end_of_day + 2.hours
unconfirmed_access_time = self.class.allow_unconfirmed_access_for.ago.in_time_zone(time_zone)
confirmation_sent_at && confirmation_time >= unconfirmed_access_time
end
但是当我在到期后检查时,我仍然可以使用该应用程序。 用户未注销。
检查 rails 控制台显示确认期对用户无效,因此可以正常工作。
好的...仔细查看您的逻辑,我认为有几个问题。
我不知道您将allow_unconfirmed_access_for
设置为什么值,因为您没有告诉我们,但是为了这个答案,我们任意假设它是1 day 。 现在,您的代码如下所示:
def confirmation_period_valid?
# This is a confusing variable name.
# It's more like an unconfirmed access *expiry* time
confirmation_time = confirmation_sent_at.in_time_zone(time_zone).end_of_day + 2.hours
# This makes no sense. Why is the user always "unconfirmed" 1 day ago?
unconfirmed_access_time = self.class.allow_unconfirmed_access_for.ago.in_time_zone(time_zone)
# if confirmation_sent_at == nil then the method would have blown up in line 1
# so this check is poorly placed. And the second part is just wrong --
# you're asking if the user was supposed to be logged out more than a day ago, not now!
confirmation_sent_at && confirmation_time >= unconfirmed_access_time
end
所以...这就是我认为您实际上要写的内容:
def confirmation_period_valid?
# Note: allow_unconfirmed_access_for is completely redundant in the logic now!
return false unless confirmation_sent_at
unconfirmed_access_expires_at = confirmation_sent_at.in_time_zone(time_zone).end_of_day + 2.hours
unconfirmed_access_expires_at > Time.current
end
话虽如此,我确实认为这是一个过度设计的解决方案,您可能只是坚持使用allow_unconfirmed_access_for = 1.day
的默认行为,而不是添加这个任意的凌晨 2 点逻辑,但是您喜欢它...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.