使用计算/操纵的用户名参数设计登录 [英] Devise login with computed / manipulated username param

查看:161
本文介绍了使用计算/操纵的用户名参数设计登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用devise创建一个使用我计算的用户名的登录名。例如,假设我们要命名我们的用户名 - 并且我想从登录表单中接收一个用户名,并使用namespaced_username进行实际身份验证。



所以在我的 User :: SessionsController#create 中,我可能有:

  def create 
params [:user] [:namespaced_username] =namespace /#{params [:user] [:mobile_number]}
super
end

即使devise正在监听namespaced_username(在初始化程序或模型本身中配置了authentication_keys),并且用户设置为 namespace / username ,我仍然被告知无效的命名空间用户名或密码无效



/ p>

解决方案

事实证明,这是一个Rails 5的问题。基本上,Warden(由devise使用)被传递请求对象,可能是在中间件中,然后控制器提交请求的params哈希的副本。



简单的方法是在 User :: SessionsController#create 中,我们需要添加一行:

  def create 
#这里我们改变参数 - 但这不会被看守策略看到
params [:user] [:namespaced_username] = =namespace / #{params [:user] [:mobile_number]}
#将请求中的更改注入副本
request.params [:user] .merge!(params [:user])
#现在我们的变化将被看守 - 继续设计:
超级
结束


I'm trying to create a login using devise with a username that I've computed. As an example, let's assume we want to namespace our usernames - and I want to receive a username from the login form, and use namespaced_username to do the actual authentication.

So in my User::SessionsController#create, I might have:

def create
  params[:user][:namespaced_username] = "namespace/#{params[:user][:mobile_number]}"
  super
end

Even though devise is listening for namespaced_username (configured with authentication_keys in either initializers or the model itself), and with a user setup as namespace/username, I still get told Invalid Namespaced username or password is not valid

How can I get devise (the warden strategies, specifically) to read the new param?

解决方案

It turns out this is a Rails 5 problem. Basically, Warden (which is used by devise) is handed the request object, probably in middleware, and then the controller is handed a copy of the request's params hash.

The easy way to fix it is, within User::SessionsController#create, we need to add a line:

def create
  # Here we change params - but this won't be seen by the warden strategy
  params[:user][:namespaced_username] =  = "namespace/#{params[:user][:mobile_number]}"
  # Inject our changes into the copy in request
  request.params[:user].merge!(params[:user])
  # now our changes will be seen by warden - continue with devise:
  super
end

这篇关于使用计算/操纵的用户名参数设计登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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