-
Notifications
You must be signed in to change notification settings - Fork 3
/
Listing_10.27.rb
41 lines (37 loc) · 1.05 KB
/
Listing_10.27.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
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
# Guard against session replay attacks.
# See https://bit.ly/33UvK0w for more.
session[:session_token] = user.session_token
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.encrypted[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
user = User.find_by(id: user_id)
if user && session[:session_token] == user.session_token
@current_user = user
end
elsif (user_id = cookies.encrypted[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Returns true if the given user is the current user.
def current_user?(user)
user && user == current_user
end
.
.
.
end