parsley/app/controllers/application_controller.rb

78 lines
1.6 KiB
Ruby
Raw Normal View History

2016-01-12 18:43:00 -06:00
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
2018-04-01 21:43:23 -05:00
def verified_request?
2022-12-01 18:02:26 -06:00
if request.media_type == "application/json"
2018-04-01 21:43:23 -05:00
true
else
super()
end
end
def ensure_valid_user
2016-01-19 17:43:52 -06:00
unless current_user?
flash[:warning] = "You must login"
redirect_to login_path
end
end
def ensure_admin_user
2016-01-20 20:29:08 -06:00
unless current_user? && current_user.admin?
flash[:warning] = "You must login as an admin"
redirect_to login_path
end
end
2016-01-21 11:47:30 -06:00
def ensure_owner(item)
owner = case
when current_user.nil?
false
when item.nil?
true
when current_user.admin?
true
when current_user.id == item.user_id
true
else
false
end
if owner
yield if block_given?
else
2024-10-02 14:34:50 -05:00
respond_to do |format|
format.html do
flash[:warning] = "Operation Not Permitted"
redirect_to root_path
end
format.json do
render json: { error: "Operation Not Permitted" }, status: current_user.nil? ? :unauthorized : :forbidden
end
end
2016-01-21 11:47:30 -06:00
end
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
2016-01-19 17:43:52 -06:00
def current_user?
!current_user.nil?
end
helper_method :current_user?
def set_current_user(user)
if user
session[:user_id] = user.id
else
session[:user_id] = nil
end
end
2016-01-12 18:43:00 -06:00
end