我的网站存在以下问题。我正在创建一堆可供其他人使用但主要用于前端的 api 调用。我的问题是出于某种原因,似乎 Authlogic 在调用控制器和权威人士之前没有对我的用户进行身份验证。有趣的是,这只会发生在TrackingController
其他人身上,而不会发生。
为了让 Authlogic 在标头而不是 url 参数上进行身份验证,我确实需要做一些技巧。这再次在我的工作正常,ShiftsController
但不会在我的TrackingController
.
我已经能够追查到是缺少user
导致CalShiftArchivePolicy
错误的对象。如果我注释掉第 5 行,代码将在第 11 行停止并出现错误:
“未定义的方法‘has_roles?’ 对于零:NilClass”
任何帮助都会很棒。
Ruby 版本 2.1.5p273,Rails 版本 4.1.8
在我的控制器中,我有:
class TrackingController < ApplicationController
include Pundit
after_action :verify_authorized
def index
@tracking = CalShiftArchive.where("cal_shift_id = :id", :id => params[:shift_id])
authorize @tracking, :index?
end
end
权威政策:
class CalShiftArchivePolicy < ApplicationPolicy
attr_reader :user, :tracking
def initialize(user, shifts)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
@user = user
@tracking = :tracking
end
def index?
user.has_roles?("CalAdmin")
end
结尾
应用控制器:
class ApplicationController < ActionController::Base
include Pundit
before_filter :api_logon
helper_method :current_user_session, :current_user
before_filter :set_current_user
protect_from_forgery with: :exception
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
protected
def permission_denied
flash[:error] = "Sorry, you are not allowed to access that page."
redirect_to root_url
end
def api_logon
if request.headers["apiKey"]
params['user_credentials'] = request.headers["apiKey"]
end
end
private
def user_not_authorized
respond_to do |format|
format.html do
flash[:error] = "You are not authorized to perform that action action."
redirect_to(request.referrer || root_path)
end
format.xml { render :xml => "<error>You are not authorized to access that resource</error>", :status => 403 }
format.json { render :json =>
{:error => "You are not authorized to access that resource "}.to_json,
:status => 403 }
end
end
#----------------- Model Current_user workaround
# passes the current_user object to a thread safe
# object that can be accesssed in models.
def set_current_user
User.current_user = current_user
end
end
路由:
Rails.application.routes.draw do
#root rout - main page location
root to: 'welcome#index'
#Login and Logout routes
resources :user_sessions
get 'login' => 'user_sessions#new', :as => :login
get 'logout' => 'user_sessions#destroy', :as => :logout
resources :users do
patch 'suppress', on: :member
patch 'unsuppress', on: :member
patch 'activate', on: :member
patch 'lock', on: :member
patch 'unlock', on: :member
patch 'password', on: :member
end
resources :shifts, except: [:new, :edit] do
patch 'submit', on: :member
patch 'acquire', on: :member
resources :tracking, except: [:new, :edit, :destroy, :update, :create]
end
end