Rails http post方法返回401未经授权的错误

时间:2015-06-25 15:16:59

标签: ruby-on-rails devise

因此,我正在开发一个简单的Web应用程序,我已经设计了用于用户身份验证的设置。 User类的子项是Property。目前,注册和登录都完美地为用户工作。但是,当我尝试创建新属性或编辑属性时,我收到401错误:

Started POST "/api/v1/properties" for ::1 at 2015-06-25 11:00:09 -0400
....
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)

好像来自devise的current_user没有被传递到我的属性控制器中,所以我怀疑它是一个关联问题或一个令牌问题。任何帮助将不胜感激。

PropertiesController:

class Api::V1::PropertiesController < ApplicationController

    skip_before_filter :verify_authenticity_token, :only => :create
    respond_to :json


    def index
        properties = Property.all
        render json: properties
    end

    def show
        respond_with Property.find(params[:id])   
    end

    def create
        property = current_user.property.build(product_params)  
        if property.save
            render json: property, status: 201, location: [:api, property] 
        else
            render json: { errors: property.errors }, status: 422
        end
    end

   ...( code below )
end

物业迁移:

class CreateProperties < ActiveRecord::Migration
    def change
        enable_extension :postgis

    create_table :properties do |t|
        t.string :name
        t.integer :user_id 
        t.timestamps
    end

        add_index :properties, :user_id
end

的ApplicationController:

class ApplicationController < ActionController::Base
    before_filter :authenticate_user_from_token!
    before_action :authenticate_user!

    private

    def authenticate_user_from_token!
        authenticate_with_http_token do |token, options|
        user_email = options[:email].presence
        user = user_email && User.find_by_email(user_email)

        if user && Devise.secure_compare(user.authentication_token, token)
            sign_in user, store: false
        end
    end
  end

end

路线:

...(code above)
devise_for :users, 
path: '/api/v1/users',
controllers: { sessions: 'api/v1/sessions', :registration => "registrations" } do
  get "api/v1/users/sign_up" => "users/registrations#new", :as => :user_signup
  get "api/v1/users/sign_in" => "api/v1/sessions", :as => :user_signin
end


namespace :api, defaults: { format: :json } do
    namespace :v1 do

      resources :properties do
...(code below)

0 个答案:

没有答案