asciinema.org/app/controllers/application_controller.rb

70 lines
1.4 KiB
Ruby
Raw Normal View History

2011-11-23 20:46:18 +00:00
class NotFound < StandardError; end
class ApplicationController < ActionController::Base
protect_from_forgery
2011-11-23 21:27:38 +00:00
rescue_from(ActiveRecord::RecordNotFound) { render 'exceptions/not_found' }
2011-11-23 20:46:18 +00:00
2012-03-01 23:25:55 +00:00
class Unauthorized < Exception; end
2012-03-06 20:27:17 +00:00
class Forbidden < Exception; end
2012-03-04 14:54:25 +00:00
rescue_from Unauthorized, :with => :unauthorized
2012-03-06 20:27:17 +00:00
rescue_from Forbidden, :with => :forbidden
2012-03-01 23:25:55 +00:00
helper_method :current_user
def current_user
2012-03-02 21:33:13 +00:00
@current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
end
def current_user=(user)
if user
@current_user = user
session[:user_id] = user.id
else
@current_user = nil
session[:user_id] = nil
end
end
2012-03-01 23:25:55 +00:00
private
def ensure_authenticated!
raise Unauthorized unless current_user
end
2012-03-06 20:28:32 +00:00
def store_location
session[:return_to] = request.path
end
def get_stored_location
session.delete(:return_to)
end
2012-03-06 21:03:12 +00:00
def redirect_back_or_to(default, options = nil)
path = get_stored_location || default
2012-03-06 21:03:12 +00:00
if options
redirect_to path, options
else
redirect_to path
end
end
2012-03-06 20:27:17 +00:00
def forbidden
if request.xhr?
2012-03-06 20:27:17 +00:00
render :json => "Forbidden", :status => 403
else
2012-03-06 20:27:17 +00:00
redirect_to root_path, :alert => "This action is forbidden"
end
end
2012-03-04 14:54:25 +00:00
def unauthorized
if request.xhr?
render :json => "Unauthorized", :status => 401
else
store_location
redirect_to login_path, :notice => "Please login"
end
end
end