英文:
How to extend clearance's back door to allow for 2FA
问题
我有一个应用程序,它使用Clearance gem进行身份验证,但也实现了两步验证(2FA)。我想在测试中使用Clearance的“后门”功能,但不确定如何与2FA结合使用。
是否有一种方式可以“挂钩”到Clearance的后门功能,并在每次使用它进行登录时设置所需的2FA值?
英文:
I have an application which uses the Clearance gem for authentication, but also implements 2FA. I want to use the "Backdoor" functionality of Clearance for tests, but am unsure how to do this in conjunction with 2FA.
Is there a way I can "hook into" Clearance's Backdoor functionality and set the required 2FA values whenever it is used to sign in?
答案1
得分: 0
基于Clearance::Backdoor
的源代码,如果你想在用户模型上设置额外的值,这可能会起作用:
# config/environments/test.rb
MyRailsApp::Application.configure do
# ...
config.middleware.use Clearance::BackDoor do |username|
user = User.find_by(username: username) # 或者你找到用户的方式
# 设置你的额外值
user.x = 'x'
user.y = 'y'
# 返回用户
user
end
end
如果你想修改请求,我认为你不能使用Clearance::Backdoor
,但你可以在它之后添加另一个Rack中间件,使用config.middleware.insert_after(Clearance::Backdoor)
(你需要编写自己的中间件)。
作为替代方案,我见过很多测试只是模拟检查用户是否已登录的代码片段,并始终返回true
(或者表示成功的任何值)。
英文:
Based on the source of Clearance::Backdoor
, if you're trying to set extra values on a user model, this might work:
# config/environments/test.rb
MyRailsApp::Application.configure do
# ...
config.middleware.use Clearance::BackDoor do |username|
user = User.find_by(username: username) # or however you'd find a user
# set your extra values
user.x = 'x'
user.y = 'y'
# return the user
user
end
end
If you want to mess with the request I don't think you can use Clearance::Backdoor
, but you could add another Rack middleware after it using config.middleware.insert_after(Clearance::Backdoor)
(you would have to write your own middleware).
As an alternative, a lot of tests I've seen just mock the piece of code that checks whether a user is signed in, and make it always return true
(or whatever indicates success).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论