使用devise通过JSON验证API登录请求

时间:2014-11-03 23:37:06

标签: ruby-on-rails ruby-on-rails-4 devise rails-api

我正在尝试使用devise来验证简单的电子邮件/密码登录,以便用户可以通过auth令牌访问其余的API。我正在遇到设计麻烦只需返回You need to sign in or sign up before continuing.这是我的代码:

class LoginController < ApplicationController
  respond_to :json

  def login
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    render :status => 200,
          :json => { :success => true,
                  :info => "Logged in",
                  :user => current_user
       }
  end

  def failure
    render :status => 401,
       :json => { :success => false,
                  :info => "Login Failed",
                  :data => {} }
  end

  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
 end

的routes.rb

  devise_scope :user do
    post 'register' => 'registration#create', :as => :registers
    post 'login' => 'login#login', :as => :login
  end

我发送了以下帖子数据:

{ 
  "user" : {
    "email" : "testPost4@fake.com",
    "password" : "Password1"
  }
}

浏览了我添加的各种帖子:

config.navigational_formats = [:json]

到devise.rb文件,但它没有解决问题。

添加skip_before_filter :authenticate_user!也不起作用。

1 个答案:

答案 0 :(得分:0)

我无法使其工作,所以我已经恢复了更简单的手动检查和登录方法。

def login
  params = login_params
  user = User.find_by_email(params['email'].downcase)
  if user.valid_password?(params['password']) then
    sign_in(user)
    success
  else
    failure
  end
end