我通過覆蓋設計的會話控制器來做到這一點。
項添加到自定義會話控制器路線:
devise_for :users, :controllers => {:sessions => 'sessions'}
並覆蓋會話控制器:
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是對同一主題的更多討論
如何使用post route/api/authenticate驗證用戶? – dcarneiro
Add route,devise_for:users do post「/ api/authenticate」=>「devise/sessions#create」end –