如果有人能解释一下,我将不胜感激,因为我对这个问题有点无能为力。基本上,我正在尝试使用构建在rails-api gem之上的仅 JSON rails rest api 应用程序来完成设计身份验证。
我已经实现了Sessions
和Registrations
处理,如下所述。
class ApplicationController < ActionController::API
include ActionController::MimeResponds
end
session_controller.rb
class SessionsController < Devise::SessionsController
prepend_before_filter :require_no_authentication, :only => [:create ]
before_filter :ensure_params_exist
def create
build_resource
resource = User.find_for_database_authentication(:email => params[:user][:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user][:password])
sign_in("user", resource)
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :email=>resource.email}
return
end
invalid_login_attempt
end
def destroy
sign_out(resource_name)
end
protected
def ensure_params_exist
return unless params[:user][:email].blank?
render :json=>{:success=>false, :message=>"missing login email parameter"}, :status=>422
end
def invalid_login_attempt
warden.custom_failure!
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
注册控制器.rb
class RegistrationsController < Devise::RegistrationsController
skip_before_filter :verify_authenticity_token, :only => :create
def create
user = User.new(params[:user])
if user.save
render :json=> {:user => [:email => user.email, :auth_token => user.authentication_token]}, :status => 201
return
else
warden.custom_failure!
render :json=> user.errors, :status=>422
end
end
end
到目前为止一切正常。在我的其他控制器中,我添加了这条线来保护它们。before_filter :authenticate_user!
但是使用 auth_token 调用时出现此错误。?auth_token=xxxxxxxxxxx
undefined method authenticate_user!
class RestaurantsController < ApplicationController
before_filter :authenticate_user!
def index
@restaurants = Restaurant.all
end
def show
@restaurant = Restaurant.find(params[:id])
end
end
仍然不确定这里可能是什么问题 - 我假设这种情况正在发生,因为在使用时缺少正确设计的东西ActionController::API
更新
似乎问题出在我routes.rb
自己身上 - 这就是路线的完成方式。
require 'api_constraints'
MyApi::Application.routes.draw do
namespace :api, defaults: {format: 'json'} do
scope module: :v1, constraints: ApiConstraints.new(version: 1,default: true) do
devise_for :users
resources :friends
resources :locations
resources :profiles
resources :users
end
scope module: :v2, constraints: ApiConstraints.new(version: 2) do
# Future releases of the API can go here
end
end
end
现在,如果在范围外重复,devise_for :users
一切都开始工作了。
require 'api_constraints'
MyApi::Application.routes.draw do
namespace :api, defaults: {format: 'json'} do
scope module: :v1, constraints: ApiConstraints.new(version: 1,default: true) do
devise_for :users
resources :friends
resources :locations
resources :profiles
resources :users
end
scope module: :v2, constraints: ApiConstraints.new(version: 2) do
# Future releases of the API can go here
end
end
devise_for :users
end
有没有人解释为什么?