forked from newleaders/thincloud-authentication
/
authenticatable_controller.rb
98 lines (83 loc) · 2.38 KB
/
authenticatable_controller.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
module Thincloud
module Authentication
module AuthenticatableController
extend ActiveSupport::Concern
included do
helper_method :current_user
helper_method :logged_in?
end
protected
# Protected: The user that is currently logged in.
#
# This method is also available as a view helper.
#
# Returns: An instance of `User` or `nil`.
def current_user
return nil if cookies.signed[:uid].blank?
@current_user ||= User.find(cookies.signed[:uid])
end
# Protected: Determine if the current request has a logged in user.
#
# This method is also available as a view helper.
#
# Returns: Boolean.
def logged_in?
current_user.present?
end
# Protected: Require an authenticated user to perform an action.
#
# Use in a `before_filter`.
#
# Returns: Redirect if not logged in, otherwise `nil`.
def authenticate!
unless logged_in?
redirect_to login_url, alert: "You must be logged in to continue."
end
end
# Protected: Set the `current_user` to the provided `User` instance.
#
# user - An instance of `User` that has been authenticated.
#
# Returns: The `id` of the provided user.
def login_as(user)
reset_session # avoid session fixation
cookies.signed[:uid] = {
value: user.id,
secure: request.ssl?,
httponly: true
}
end
# Protected: Clear the session of an authenticated user.
#
# Returns: A new empty session instance.
def logout
reset_session
cookies.delete(:uid)
end
# Protected: Provides the URL to redirect to after logging in.
#
# Returns: A string.
def after_login_path
main_app.root_url
end
# Protected: Provides the URL to redirect to after logging out.
#
# Returns: A string.
def after_logout_path
main_app.root_url
end
# Protected: Provides the URL to redirect to after registering.
#
# Returns: A string.
def after_registration_path
main_app.root_url
end
# Protected: Provides the URL to redirect to after verification.
#
# Returns: A string.
def after_verification_path
main_app.root_url
end
end
end
end