/
authentication_helpers.rb
112 lines (99 loc) · 3.16 KB
/
authentication_helpers.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
module Padrino
module Admin
module Helpers
##
# Common helpers used for authorization within an application.
#
module AuthenticationHelpers
##
# Returns true if +current_account+ is logged and active.
#
def logged_in?
!current_account.nil?
end
##
# Returns the current_account, it's an instance of Account model.
#
def current_account
@current_account ||= login_from_session
end
##
# Override the current_account, you must provide an instance of Account model.
#
# @example
# set_current_account(Account.authenticate(params[:email], params[:password])
#
def set_current_account(account=nil)
session[settings.session_id] = account ? account.id : nil
@current_account = account
end
##
# Returns true if the +current_account+ is allowed to see the requested path.
#
# For configure this role please refer to: +Padrino::Admin::AccessControl::Base+
#
def allowed?
access_control.allowed?(current_account, request.path_info)
end
##
# Returns project modules for the current account.
#
def project_modules
access_control.project_modules(current_account)
end
##
# Returns a helper useful in a +before_filter+ for check if
# an account are: +logged_in?+ and +allowed?+
#
# By default this method is used in Admin Apps.
#
def login_required
unless allowed?
store_location! if store_location
access_denied
end
end
##
# Store in session[:return_to] the env['REQUEST_URI'].
#
def store_location!
session[:return_to] = env['REQUEST_URI']
end
##
# Redirect the account to the page that requested an authentication or
# if the account is not allowed/logged return it to a default page.
#
def redirect_back_or_default(default)
return_to = session.delete(:return_to)
redirect(return_to || default)
end
private
def access_denied
# If we have a login_page we redirect the user
if login_page
redirect(login_page)
else
halt 401, "You don't have permission for this resource"
end
end
def login_page
login_page ||= settings.login_page rescue nil
return unless login_page
login_page = File.join(ENV['RACK_BASE_URI'].to_s, login_page) if ENV['RACK_BASE_URI']
login_page
end
def store_location
settings.store_location rescue nil
end
def login_from_session
admin_model_obj.find_by_id(session[settings.session_id]) if admin_model_obj
end
def admin_model_obj
@_admin_model_obj ||= settings.admin_model.constantize
rescue NameError
raise Padrino::Admin::AccessControlError, "You must define an #{settings.admin_model} Model!"
end
end
end
end
end