/
thread_session.rb
88 lines (79 loc) · 3.15 KB
/
thread_session.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
# In several cases we want to break chain of responsibility in MVC a bit and provide
# a safe way to access current user (and maybe few more data items). Storing it as
# a global variable (or class member) is not thread-safe. Including ThreadSession::
# UserModel in models and ThreadSession::Controller in the application controller
# allows this without any concurrent issues.
#
# Idea taken from sentinent_user rails plugin.
#
# http://github.com/bokmann/sentient_user
# http://github.com/astrails/let_my_controller_go
# http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
#
module Katello
def self.pulp_server=(server)
Thread.current[:pulp_server] = server
end
def self.pulp_server
Thread.current[:pulp_server]
end
end
module Katello
module Util
module ThreadSession
# include this in the User model
module UserModel
# TODO: break up method
# rubocop:disable MethodLength
def self.included(base)
base.class_eval do
def self.current
Thread.current[:user]
end
def self.current=(o)
unless (o.nil? || o.is_a?(self) || o.class.name == 'RSpec::Mocks::Mock')
fail(ArgumentError, "Unable to set current User, expected class '#{self}', got #{o.inspect}")
end
if o.is_a?(::User)
debug = ["Setting current user thread-local variable to", o.firstname, o.lastname]
Rails.logger.debug debug.join(" ")
end
Thread.current[:user] = o
if SETTINGS[:katello][:use_cp] && o.respond_to?(:cp_oauth_header)
self.cp_config(o.cp_oauth_header)
end
if SETTINGS[:katello][:use_pulp]
self.pulp_config(User.remote_user)
end
end
def self.pulp_config(user_remote_id, &_block)
uri = URI.parse(SETTINGS[:katello][:pulp][:url])
Katello.pulp_server = Runcible::Instance.new(
:url => "#{uri.scheme}://#{uri.host.downcase}",
:api_path => uri.path,
:user => user_remote_id,
:timeout => SETTINGS[:katello][:rest_client_timeout],
:open_timeout => SETTINGS[:katello][:rest_client_timeout],
:oauth => {:oauth_secret => SETTINGS[:katello][:pulp][:oauth_secret],
:oauth_key => SETTINGS[:katello][:pulp][:oauth_key] },
:logging => {:logger => ::Foreman::Logging.logger('katello/pulp_rest'),
:exception => true,
:info => true,
:debug => true }
)
yield if block_given?
ensure
Katello.pulp_server = nil if block_given?
end
def self.cp_config(cp_oauth_header)
Thread.current[:cp_oauth_header] = cp_oauth_header
yield if block_given?
ensure
Thread.current[:cp_oauth_header] = nil if block_given?
end
end
end
end
end
end
end