blob: 687bc6ea4a3a7c54afa4b308e56c7312305c1d8a (
plain)
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
|
module ControllerExtension::Authentication
extend ActiveSupport::Concern
private
included do
helper_method :current_user, :logged_in?, :admin?
end
def current_user
@current_user ||= token_authenticate || warden.user || anonymous
end
def logged_in?
current_user.is_a? User
end
def require_login
login_required unless logged_in?
end
# some actions only make sense if you are not logged in yet.
# (login, signup). If a user tries to perform these they will
# be redirected to their dashboard.
def redirect_if_logged_in
redirect_to home_url if logged_in?
end
def access_denied
respond_to_error :not_authorized, :forbidden, home_url
end
def login_required
# Warden will intercept the 401 response and call
# SessionController#unauthenticated instead.
respond_to_error :not_authorized_login, :unauthorized, login_url
end
def respond_to_error(message, status=nil, redirect=nil)
message = t(message) if message.is_a?(Symbol)
respond_to do |format|
format.html do
redirect_to redirect, alert: message
end
format.json do
status ||= :unprocessable_entity
render json: {error: message}, status: status
end
end
end
def admin?
current_user.is_admin?
end
def require_admin
access_denied unless admin?
end
def authentication_errors
return unless attempted_login?
errors = get_warden_errors
errors.inject({}) do |translated,err|
translated[err.first] = I18n.t(err.last)
translated
end
end
def get_warden_errors
if strategy = warden.winning_strategy
message = strategy.message
# in case we get back the default message to fail!
message.respond_to?(:inject) ? message : { base: message }
else
{ login: :all_strategies_failed }
end
end
def attempted_login?
request.env['warden.options'] &&
request.env['warden.options'][:attempted_path]
end
protected
def anonymous
AnonymousUser.new
end
end
|