Commit 6b3ab93148468c900ba586a5629f5f65eb1bb29f
Committed by
Braulio Bhavamitra
1 parent
608ddc9d
Exists in
master
and in
29 other branches
Global thread-safe current user for models use
Showing
2 changed files
with
27 additions
and
2 deletions
Show diff stats
app/models/user.rb
@@ -15,6 +15,14 @@ class User < ActiveRecord::Base | @@ -15,6 +15,14 @@ class User < ActiveRecord::Base | ||
15 | :email => {:label => _('Email'), :weight => 5}, | 15 | :email => {:label => _('Email'), :weight => 5}, |
16 | } | 16 | } |
17 | 17 | ||
18 | + # see http://stackoverflow.com/a/2513456/670229 | ||
19 | + def self.current | ||
20 | + Thread.current[:current_user] | ||
21 | + end | ||
22 | + def self.current=(user) | ||
23 | + Thread.current[:current_user] = user | ||
24 | + end | ||
25 | + | ||
18 | def self.[](login) | 26 | def self.[](login) |
19 | self.find_by_login(login) | 27 | self.find_by_login(login) |
20 | end | 28 | end |
lib/authenticated_system.rb
1 | module AuthenticatedSystem | 1 | module AuthenticatedSystem |
2 | + | ||
2 | protected | 3 | protected |
4 | + | ||
5 | + # See impl. from http://stackoverflow.com/a/2513456/670229 | ||
6 | + def self.included? base | ||
7 | + base.around_filter do | ||
8 | + begin | ||
9 | + User.current = current_user | ||
10 | + yield | ||
11 | + ensure | ||
12 | + # to address the thread variable leak issues in Puma/Thin webserver | ||
13 | + User.current = nil | ||
14 | + end | ||
15 | + end | ||
16 | + end | ||
17 | + | ||
3 | # Returns true or false if the user is logged in. | 18 | # Returns true or false if the user is logged in. |
4 | # Preloads @current_user with the user model if they're logged in. | 19 | # Preloads @current_user with the user model if they're logged in. |
5 | def logged_in? | 20 | def logged_in? |
@@ -8,7 +23,9 @@ module AuthenticatedSystem | @@ -8,7 +23,9 @@ module AuthenticatedSystem | ||
8 | 23 | ||
9 | # Accesses the current user from the session. | 24 | # Accesses the current user from the session. |
10 | def current_user | 25 | def current_user |
11 | - @current_user ||= (session[:user] && User.find_by_id(session[:user])) || nil | 26 | + @current_user ||= begin |
27 | + User.current = (session[:user] && User.find_by_id(session[:user])) || nil | ||
28 | + end | ||
12 | end | 29 | end |
13 | 30 | ||
14 | # Store the given user in the session. | 31 | # Store the given user in the session. |
@@ -19,7 +36,7 @@ module AuthenticatedSystem | @@ -19,7 +36,7 @@ module AuthenticatedSystem | ||
19 | session[:user] = new_user.id | 36 | session[:user] = new_user.id |
20 | new_user.register_login | 37 | new_user.register_login |
21 | end | 38 | end |
22 | - @current_user = new_user | 39 | + @current_user = User.current = new_user |
23 | end | 40 | end |
24 | 41 | ||
25 | # Check if the user is authorized. | 42 | # Check if the user is authorized. |