2011-11-23 20:46:18 +00:00
|
|
|
class NotFound < StandardError; end
|
|
|
|
|
2011-11-21 21:36:42 +00:00
|
|
|
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:26:05 +00:00
|
|
|
|
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
|
|
|
|
2012-02-25 22:43:17 +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]
|
2012-02-25 22:43:17 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def current_user=(user)
|
|
|
|
if user
|
2012-02-26 15:33:37 +00:00
|
|
|
@current_user = user
|
2012-02-25 22:43:17 +00:00
|
|
|
session[:user_id] = user.id
|
|
|
|
else
|
2012-02-26 15:33:37 +00:00
|
|
|
@current_user = nil
|
2012-02-25 22:43:17 +00:00
|
|
|
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 20:46:05 +00:00
|
|
|
def redirect_back_or_to(default, options = {})
|
|
|
|
path = get_stored_location || default
|
|
|
|
redirect_to path, options
|
|
|
|
end
|
|
|
|
|
2012-03-06 20:27:17 +00:00
|
|
|
def forbidden
|
2012-03-04 14:26:05 +00:00
|
|
|
if request.xhr?
|
2012-03-06 20:27:17 +00:00
|
|
|
render :json => "Forbidden", :status => 403
|
2012-03-04 14:26:05 +00:00
|
|
|
else
|
2012-03-06 20:27:17 +00:00
|
|
|
redirect_to root_path, :alert => "This action is forbidden"
|
2012-03-04 14:26:05 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-03-04 14:54:25 +00:00
|
|
|
def unauthorized
|
2012-03-04 14:26:05 +00:00
|
|
|
if request.xhr?
|
|
|
|
render :json => "Unauthorized", :status => 401
|
|
|
|
else
|
2012-03-06 20:29:07 +00:00
|
|
|
store_location
|
2012-03-04 14:26:05 +00:00
|
|
|
redirect_to login_path, :notice => "Please login"
|
|
|
|
end
|
|
|
|
end
|
2011-11-21 21:36:42 +00:00
|
|
|
end
|