parsley/app/controllers/application_controller.rb
2016-01-21 11:47:30 -06:00

46 lines
1.1 KiB
Ruby

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
def ensure_valid_user
unless current_user?
flash[:warning] = "You must login"
redirect_to login_path
end
end
def ensure_admin_user
unless current_user? && current_user.admin?
flash[:warning] = "You must login as an admin"
redirect_to login_path
end
end
def ensure_owner(item)
unless current_user && item && (item.user_id == current_user.id || current_user.admin?)
flash[:warning] = "Operation Not Permitted"
return redirect_to root_path
end
yield if block_given?
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
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
end