我正在尝试使用devise配置:token_authenticatable来通过json在我的项目中添加身份验证。
我有sessions_controller#create的可行代码,该代码取自这篇文章-http://blog.codebykat.com/2012/07/23/remote-api-authentication-with-rails-3-using-activeresource-and-devise/
问题在于原生的Devise sessions_controller#create看起来是这样的:
我不知道如何将这两种创建方法合并,以使网站和JSON都能正常工作进行身份验证? 更新 可行的代码
我有sessions_controller#create的可行代码,该代码取自这篇文章-http://blog.codebykat.com/2012/07/23/remote-api-authentication-with-rails-3-using-activeresource-and-devise/
def create
build_resource
resource = User.find_for_database_authentication(:email => params[:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:password])
resource.ensure_authentication_token! #make sure the user has a token generated
render :json => { :authentication_token => resource.authentication_token, :user_id => resource.id }, :status => :created
return
end
end
def invalid_login_attempt
warden.custom_failure!
render :json => { :errors => ["Invalid email or password."] }, :success => false, :status => :unauthorized
end
问题在于原生的Devise sessions_controller#create看起来是这样的:
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end
我不知道如何将这两种创建方法合并,以使网站和JSON都能正常工作进行身份验证? 更新 可行的代码
def create
respond_to do |format|
format.json do
build_resource
resource = User.find_for_database_authentication(:email => params[:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:password])
resource.ensure_authentication_token! #make sure the user has a token generated
render json: { authentication_token: resource.authentication_token, user_id: resource.id }, status: :created
return
end
end
format.html do
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end
end
end