我们正在升级具有两种用户身份验证方式的应用程序。
- 具有
before_filter :authenticate_user!
回调并像标准 Rails 站点一样访问的 Controller 。 - 客户端应用程序通过 JSON 访问 API 模块内的 Controller 。除了仅具有前缀
/api
的身份验证操作外,所有路由都具有前缀/api/session_id/
。
这两种方式都使用 User
模型对用户进行身份验证。
有没有办法配置设计来支持它们?怎么办?
注意:我不想通过 JSON 创建用户。我只想验证它们。
最佳答案
我通过覆盖设备的 session Controller 来做到这一点。
为自定义 session Controller 添加路由条目:
devise_for :users, :controllers => {:sessions => 'sessions'}
并覆盖 session Controller :
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(:scope => resource_name, :recall => "sessions#failure")
return sign_in_and_redirect(resource_name, resource)
end
def sign_in_and_redirect(resource_or_scope, resource=nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource ||= resource_or_scope
sign_in(scope, resource) unless warden.user(scope) == resource
respond_with do |format|
format.json {render :json => {:success => true} }
format.any {super}
end
end
def failure
respond_with do |format|
format.json {render:json => {:success => false, :errors => ["Login failed."]} }
format.any {redirect_to :back, :notice => "Wrong Email / Password" }
end
#return render:json => {:success => false, :errors => ["Login failed."]}
end
end
"Rails & Devise: Override SessionsController 是对同一主题的更多讨论。
关于ruby-on-rails - 扩展设计以支持 JSON API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882412/