在我的项目设计中,为管理面板提供用户注册/身份验证。我需要添加API方法,该方法将sign_in用户并返回状态为+ session cookie的JSON。
的routes.rb
devise_for :user, :controllers => {sessions: 'sessions'}
会话控制器
class SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token
def create
resource = warden.authenticate!(:scrope => resource_name, :recall => "#{controller_path}#failure")
sign_in(resource_name, resource)
respond_to do |format|
format.html { respond_with resource, :location => after_sign_in_path_for(resource) }
format.json { render json: {:success => 1}}
end
end
如果我将数据发布到user / sign_in.json,它将呈现{“success”:1}这正是我需要的。
但问题是如何在某些自定义网址上移动user / sign_in.json,例如/ api / sign_in?
答案 0 :(得分:0)
在命名空间中包围路径:
namespace :api do
devise_for :user, :controllers => {sessions: 'sessions'}
end
答案 1 :(得分:0)
是这样的:
<强> api_controller.rb 强>
def create_session
resource = User.find_for_database_authentication(:email => params[:user][:email])
if resource.nil?
render :json=> {:success => 0, :error => "No Such User"}, :status=>401
else
if resource.valid_password?(params[:user][:password])
sign_in(:user, resource)
render :json=> {:success => 1}
else
render :json=> {:success => 0, :error => "Wrong Password"}, :status=>401
end
end
end
<强>的routes.rb 强>
namespace :api do
namespace :v1 do
get :sign_in, :to => 'api#create_session'
end
end