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-04 14:26:05 +00:00
|
|
|
class Forbiden < Exception; end
|
|
|
|
|
2012-03-04 14:54:25 +00:00
|
|
|
rescue_from Unauthorized, :with => :unauthorized
|
2012-03-04 14:26:05 +00:00
|
|
|
rescue_from Forbiden, :with => :forbiden
|
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-04 14:26:05 +00:00
|
|
|
def forbiden
|
|
|
|
if request.xhr?
|
|
|
|
render :json => "Forbiden", :status => 403
|
|
|
|
else
|
|
|
|
redirect_to root_path, :alert => "This action is forbiden"
|
|
|
|
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
|
|
|
|
redirect_to login_path, :notice => "Please login"
|
|
|
|
end
|
|
|
|
end
|
2011-11-21 21:36:42 +00:00
|
|
|
end
|