Commit 6b3ab93148468c900ba586a5629f5f65eb1bb29f

Authored by Braulio Bhavamitra
Committed by Braulio Bhavamitra
1 parent 608ddc9d

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 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 26 def self.[](login)
19 27 self.find_by_login(login)
20 28 end
... ...
lib/authenticated_system.rb
1 1 module AuthenticatedSystem
  2 +
2 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 18 # Returns true or false if the user is logged in.
4 19 # Preloads @current_user with the user model if they're logged in.
5 20 def logged_in?
... ... @@ -8,7 +23,9 @@ module AuthenticatedSystem
8 23  
9 24 # Accesses the current user from the session.
10 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 29 end
13 30  
14 31 # Store the given user in the session.
... ... @@ -19,7 +36,7 @@ module AuthenticatedSystem
19 36 session[:user] = new_user.id
20 37 new_user.register_login
21 38 end
22   - @current_user = new_user
  39 + @current_user = User.current = new_user
23 40 end
24 41  
25 42 # Check if the user is authorized.
... ...