Class: Softwear::Auth::StandardModel
- Inherits:
-
Object
- Object
- Softwear::Auth::StandardModel
show all
- Includes:
- ActiveModel::Conversion, ActiveModel::Model
- Defined in:
- lib/softwear/auth/standard_model.rb
Defined Under Namespace
Classes: AccessDeniedError, AuthServerDown, AuthServerError, InvalidCommandError
Constant Summary
collapse
- REMOTE_ATTRIBUTES =
INSTANCE METHODS ======================
[
:id, :email, :first_name, :last_name,
:roles, :profile_picture_url,
:default_view, :rights
]
Class Attribute Summary collapse
Instance Attribute Summary collapse
Class Method Summary
collapse
-
.abstract_class? ⇒ Boolean
-
.all ⇒ Object
Returns an array of all registered users ====================.
-
.arel_table ⇒ Object
-
.auth(token, app_name = nil) ⇒ Object
Given a valid signin token: Returns the authenticated user for the given token Given an invalid signin token: Returns false ====================.
-
.auth_server_down? ⇒ Boolean
Returns true if the authentication server was unreachable for the previous query.
-
.auth_server_down_mailer ⇒ Object
Override this in your subclasses! The mailer should have auth_server_down(time) and auth_server_up(time) ===================.
-
.auth_server_host ⇒ Object
Host of the auth server, from ‘auth_server_endpoint’ env variable.
-
.auth_server_port ⇒ Object
Port of the auth server, from ‘auth_server_endpoint’ env variable.
-
.base_class ⇒ Object
-
.default_socket ⇒ Object
-
.expire_query_cache ⇒ Object
Expires the query cache, setting a new expiration time as well as merging with the previous query cache, in case of an auth server outage.
-
.filter_all(method, options) ⇒ Object
-
.find(target_id) ⇒ Object
Finds a user with the given ID ====================.
-
.find_by(options) ⇒ Object
Finds a user with the given attributes (just queries for ‘all’ and uses ruby filters) ====================.
-
.force_query(message) ⇒ Object
Runs a query through the server without error or cache checking.
-
.has_many(assoc, options = {}) ⇒ Object
Not a fully featured has_many - must specify foreign_key if the association doesn’t match the model name, through is inefficient.
-
.logger ⇒ Object
Overridable logger method used when recording query benchmarks ====================.
-
.new(*args) ⇒ Object
-
.of_role(*roles) ⇒ Object
Returns array of all users with the given roles ====================.
-
.pluck(*attrs) ⇒ Object
Pretty much a map function - for activerecord compatibility.
-
.primary_key ⇒ Object
.
-
.query(message) ⇒ Object
Queries the authentication server only if there isn’t a cached response.
-
.raw_query(message) ⇒ Object
Bare minimum query function - sends a message and returns the response, and handles a broken socket.
-
.record(before, after, type, body) ⇒ Object
-
.relation_delegate_class ⇒ Object
-
.unscoped ⇒ Object
-
.validate_response(response_string) ⇒ Object
Expects a response string returned from #query and raises an error for the following cases:.
-
.where(options) ⇒ Object
Finds users with the given attributes (just queries for ‘all’ and uses ruby filters) ====================.
Instance Method Summary
collapse
Constructor Details
#initialize(attributes = {}) ⇒ StandardModel
448
449
450
|
# File 'lib/softwear/auth/standard_model.rb', line 448
def initialize(attributes = {})
update_attributes(attributes)
end
|
Class Attribute Details
.auth_server_went_down_at ⇒ Object
Returns the value of attribute auth_server_went_down_at.
26
27
28
|
# File 'lib/softwear/auth/standard_model.rb', line 26
def auth_server_went_down_at
@auth_server_went_down_at
end
|
.query_cache ⇒ Object
The query cache takes message keys (such as “get 12”) with response values straight from the server. So yes, this will cache error responses. You can clear this with <User Class>.query_cache.clear or <User Class>.query_cache = nil
43
44
45
|
# File 'lib/softwear/auth/standard_model.rb', line 43
def query_cache
@query_cache ||= ThreadSafe::Cache.new
end
|
.query_cache_expiry ⇒ Object
47
48
49
|
# File 'lib/softwear/auth/standard_model.rb', line 47
def query_cache_expiry
@query_cache_expiry || Figaro.env.query_cache_expiry.try(:to_f) || 1.hour
end
|
.sent_auth_server_down_email ⇒ Object
Returns the value of attribute sent_auth_server_down_email.
27
28
29
|
# File 'lib/softwear/auth/standard_model.rb', line 27
def sent_auth_server_down_email
@sent_auth_server_down_email
end
|
.time_before_down_email ⇒ Object
Returns the value of attribute time_before_down_email.
28
29
30
|
# File 'lib/softwear/auth/standard_model.rb', line 28
def time_before_down_email
@time_before_down_email
end
|
.total_query_cache ⇒ Object
Returns the value of attribute total_query_cache.
23
24
25
|
# File 'lib/softwear/auth/standard_model.rb', line 23
def total_query_cache
@total_query_cache
end
|
Instance Attribute Details
#persisted ⇒ Object
Also known as:
persisted?
Returns the value of attribute persisted.
429
430
431
|
# File 'lib/softwear/auth/standard_model.rb', line 429
def persisted
@persisted
end
|
Class Method Details
.abstract_class? ⇒ Boolean
18
19
20
|
# File 'lib/softwear/auth/standard_model.rb', line 18
def abstract_class?
true
end
|
.all ⇒ Object
Returns an array of all registered users
375
376
377
378
379
380
|
# File 'lib/softwear/auth/standard_model.rb', line 375
def all
json = validate_response query "all"
objects = JSON.parse(json).map(&method(:new))
objects.each { |u| u.instance_variable_set(:@persisted, true) }
end
|
.arel_table ⇒ Object
132
133
134
|
# File 'lib/softwear/auth/standard_model.rb', line 132
def arel_table
@arel_table ||= Arel::Table.new(model_name.plural, self)
end
|
.auth(token, app_name = nil) ⇒ Object
Given a valid signin token:
Returns the authenticated user for the given token
Given an invalid signin token:
Returns false
401
402
403
404
405
406
407
408
409
410
|
# File 'lib/softwear/auth/standard_model.rb', line 401
def auth(token, app_name = nil)
response = validate_response query "auth #{app_name || Figaro.env.hub_app_name} #{token}"
return false unless response =~ /^yes .+$/
_yes, json = response.split(' ', 2)
object = new(JSON.parse(json))
object.instance_variable_set(:@persisted, true)
object
end
|
.auth_server_down? ⇒ Boolean
Returns true if the authentication server was unreachable for the previous query.
34
35
36
|
# File 'lib/softwear/auth/standard_model.rb', line 34
def auth_server_down?
!!auth_server_went_down_at
end
|
.auth_server_down_mailer ⇒ Object
Override this in your subclasses! The mailer should have auth_server_down(time) and auth_server_up(time)
55
56
57
|
# File 'lib/softwear/auth/standard_model.rb', line 55
def auth_server_down_mailer
end
|
.auth_server_host ⇒ Object
Host of the auth server, from ‘auth_server_endpoint’ env variable. Defaults to localhost.
149
150
151
152
153
154
155
156
157
158
|
# File 'lib/softwear/auth/standard_model.rb', line 149
def auth_server_host
endpoint = Figaro.env.auth_server_endpoint
if endpoint.blank?
'localhost'
elsif endpoint.include?(':')
endpoint.split(':').first
else
endpoint
end
end
|
.auth_server_port ⇒ Object
Port of the auth server, from ‘auth_server_endpoint’ env variable. Defaults to 2900.
164
165
166
167
168
169
170
171
|
# File 'lib/softwear/auth/standard_model.rb', line 164
def auth_server_port
endpoint = Figaro.env.auth_server_endpoint
if endpoint.try(:include?, ':')
endpoint.split(':').last
else
2900
end
end
|
.base_class ⇒ Object
64
65
66
|
# File 'lib/softwear/auth/standard_model.rb', line 64
def base_class
self
end
|
.default_socket ⇒ Object
173
174
175
|
# File 'lib/softwear/auth/standard_model.rb', line 173
def default_socket
@default_socket ||= TCPSocket.open(auth_server_host, auth_server_port)
end
|
.expire_query_cache ⇒ Object
Expires the query cache, setting a new expiration time as well as merging with the previous query cache, in case of an auth server outage.
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
|
# File 'lib/softwear/auth/standard_model.rb', line 209
def expire_query_cache
before = Time.now
if total_query_cache
query_cache.each_pair do |key, value|
total_query_cache[key] = value
end
else
self.total_query_cache = query_cache.clone
end
query_cache.clear
query_cache['_expire_at'] = (query_cache_expiry || 1.hour).from_now
after = Time.now
record(before, after, "Authentication Expire Cache", "")
end
|
.filter_all(method, options) ⇒ Object
352
353
354
355
356
|
# File 'lib/softwear/auth/standard_model.rb', line 352
def filter_all(method, options)
all.send(method) do |user|
options.all? { |field, wanted_value| user.send(field) == wanted_value }
end
end
|
.find(target_id) ⇒ Object
Finds a user with the given ID
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
|
# File 'lib/softwear/auth/standard_model.rb', line 336
def find(target_id)
json = validate_response query "get #{target_id}"
if json == 'nosuchuser'
nil
else
object = new(JSON.parse(json))
object.instance_variable_set(:@persisted, true)
object
end
rescue JSON::ParserError => e
Rails.logger.error "Bad user model JSON: ``` #{json} ```"
nil
end
|
.find_by(options) ⇒ Object
Finds a user with the given attributes (just queries for ‘all’ and uses ruby filters)
361
362
363
|
# File 'lib/softwear/auth/standard_model.rb', line 361
def find_by(options)
filter_all(:find, options)
end
|
.force_query(message) ⇒ Object
Runs a query through the server without error or cache checking.
304
305
306
307
308
309
310
311
|
# File 'lib/softwear/auth/standard_model.rb', line 304
def force_query(message)
before = Time.now
response = raw_query(message)
after = Time.now
record(before, after, "Authentication Query (forced)", message)
response
end
|
.has_many(assoc, options = {}) ⇒ Object
Not a fully featured has_many - must specify foreign_key if the association doesn’t match the model name, through is inefficient.
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
# File 'lib/softwear/auth/standard_model.rb', line 93
def has_many(assoc, options = {})
assoc = assoc.to_s
if through = options[:through]
source = options[:source] || assoc
class_eval "def \#{assoc}\n\#{through}.flat_map(&:\#{source})\nend\n", __FILE__, __LINE__ + 1
else
class_name = options[:class_name] || assoc.singularize.camelize
foreign_key = options[:foreign_key] || 'user_id'
class_eval "def \#{assoc}\n\#{class_name}.where(\#{foreign_key}: id)\nend\n", __FILE__, __LINE__ + 1
end
end
|
.logger ⇒ Object
Overridable logger method used when recording query benchmarks
415
416
417
|
# File 'lib/softwear/auth/standard_model.rb', line 415
def logger
Rails.logger
end
|
.new(*args) ⇒ Object
76
77
78
79
80
81
82
83
84
85
86
|
# File 'lib/softwear/auth/standard_model.rb', line 76
def new(*args)
if args.size == 3
assoc_class = args[2].owner.class.name
assoc_name = args[2].reflection.name
raise "Unsupported user association: #{assoc_class}##{assoc_name}. If this is a belongs_to "\
"association, you may have #{assoc_class} include Softwear::Auth::BelongsToUser and call "\
"`belongs_to_user_called :#{assoc_name}' instead of the traditional rails method."
else
super
end
end
|
.of_role(*roles) ⇒ Object
Returns array of all users with the given roles
385
386
387
388
389
390
391
392
393
|
# File 'lib/softwear/auth/standard_model.rb', line 385
def of_role(*roles)
roles = roles.flatten.compact
return [] if roles.empty?
json = validate_response query "ofrole #{Figaro.env.hub_app_name} #{roles.split(' ')}"
objects = JSON.parse(json).map(&method(:new))
objects.each { |u| u.instance_variable_set(:@persisted, true) }
end
|
.pluck(*attrs) ⇒ Object
Pretty much a map function - for activerecord compatibility.
120
121
122
123
124
125
126
127
128
129
130
|
# File 'lib/softwear/auth/standard_model.rb', line 120
def pluck(*attrs)
if attrs.size == 1
all.map do |user|
user.send(attrs.first)
end
else
all.map do |user|
attrs.map { |a| user.send(a) }
end
end
end
|
.primary_key ⇒ Object
60
61
62
|
# File 'lib/softwear/auth/standard_model.rb', line 60
def primary_key
:id
end
|
.query(message) ⇒ Object
Queries the authentication server only if there isn’t a cached response. Also keeps track of whether or not the server is reachable, and sends emails when the server goes down and back up.
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
|
# File 'lib/softwear/auth/standard_model.rb', line 231
def query(message)
before = Time.now
expire_at = query_cache['_expire_at']
expire_query_cache if expire_at.blank? || Time.now > expire_at
if cached_response = query_cache[message]
response = cached_response
action = "Authentication Cache"
else
begin
response = raw_query(message)
action = "Authentication Query"
query_cache[message] = response
if auth_server_went_down_at
self.auth_server_went_down_at = nil
if sent_auth_server_down_email
self.sent_auth_server_down_email = false
if (mailer = auth_server_down_mailer) && mailer.respond_to?(:auth_server_up)
mailer.auth_server_up(Time.now).deliver_now
end
end
end
rescue AuthServerError => e
raise unless total_query_cache
old_response = total_query_cache[message]
if old_response
response = old_response
action = "Authentication Cache (due to error)"
Rails.logger.error "AUTHENTICATION: The authentication server encountered an error. "\
"You should probably check the auth server's logs. "\
"A cached response was used."
else
raise
end
rescue AuthServerDown => e
if auth_server_went_down_at.nil?
self.auth_server_went_down_at = Time.now
expire_query_cache
elsif auth_server_went_down_at > (time_before_down_email || 5.minutes).ago
unless sent_auth_server_down_email
self.sent_auth_server_down_email = true
if (mailer = auth_server_down_mailer) && mailer.respond_to?(:auth_server_down)
mailer.auth_server_down(auth_server_went_down_at).deliver_now
end
end
end
old_response = total_query_cache[message]
if old_response
response = old_response
action = "Authentication Cache (server down)"
else
raise AuthServerDown, "An uncached query was attempted, and the authentication server is down."
end
end
end
after = Time.now
record(before, after, action, message)
response
end
|
.raw_query(message) ⇒ Object
Bare minimum query function - sends a message and returns the response, and handles a broken socket. #query and #force_query call this function.
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
|
# File 'lib/softwear/auth/standard_model.rb', line 181
def raw_query(message)
begin
default_socket.puts message
rescue Errno::EPIPE => e
@default_socket = TCPSocket.open(auth_server_host, auth_server_port)
@default_socket.puts message
end
response = default_socket.gets.try(:chomp)
if response.nil?
@default_socket.close rescue nil
@default_socket = nil
return raw_query(message)
end
response
rescue Errno::ECONNREFUSED => e
raise AuthServerDown, "Unable to connect to the authentication server."
rescue Errno::ETIMEDOUT => e
raise AuthServerDown, "Connection to authentication server timed out."
end
|
.record(before, after, type, body) ⇒ Object
This is only used to record how long it takes to perform queries for development.
139
140
141
142
143
|
# File 'lib/softwear/auth/standard_model.rb', line 139
def record(before, after, type, body)
ms = (after - before) * 1000
Rails.logger.info " \033[1m\033[33m#{type} (#{'%.1f' % ms}ms)\033[0m #{body}"
end
|
.relation_delegate_class ⇒ Object
68
69
70
|
# File 'lib/softwear/auth/standard_model.rb', line 68
def relation_delegate_class(*)
self
end
|
.unscoped ⇒ Object
72
73
74
|
# File 'lib/softwear/auth/standard_model.rb', line 72
def unscoped
self
end
|
.validate_response(response_string) ⇒ Object
Expects a response string returned from #query and raises an error for the following cases:
-
Access denied (AccessDeniedError)
-
Invalid command (bad query message) (InvalidCommandError)
-
Error on auth server’s side (AuthServerError)
321
322
323
324
325
326
327
328
329
330
331
|
# File 'lib/softwear/auth/standard_model.rb', line 321
def validate_response(response_string)
case response_string
when 'denied' then raise AccessDeniedError, "Denied"
when 'invalid' then raise InvalidCommandError, "Invalid command"
when 'sorry'
expire_query_cache
raise AuthServerError, "Authentication server encountered an error"
else
response_string
end
end
|
.where(options) ⇒ Object
Finds users with the given attributes (just queries for ‘all’ and uses ruby filters)
368
369
370
|
# File 'lib/softwear/auth/standard_model.rb', line 368
def where(options)
filter_all(:select, options)
end
|
Instance Method Details
#force_query(*a) ⇒ Object
440
441
442
|
# File 'lib/softwear/auth/standard_model.rb', line 440
def force_query(*a)
self.class.force_query(*a)
end
|
#full_name ⇒ Object
479
480
481
|
# File 'lib/softwear/auth/standard_model.rb', line 479
def full_name
"#{@first_name} #{@last_name}"
end
|
#logger ⇒ Object
443
444
445
|
# File 'lib/softwear/auth/standard_model.rb', line 443
def logger
self.class.logger
end
|
#query(*a) ⇒ Object
Various class methods accessible on instances
434
435
436
|
# File 'lib/softwear/auth/standard_model.rb', line 434
def query(*a)
self.class.query(*a)
end
|
#raw_query(*a) ⇒ Object
437
438
439
|
# File 'lib/softwear/auth/standard_model.rb', line 437
def raw_query(*a)
self.class.raw_query(*a)
end
|
#reload ⇒ Object
471
472
473
474
475
476
477
|
# File 'lib/softwear/auth/standard_model.rb', line 471
def reload
json = validate_response query "get #{id}"
update_attributes(JSON.parse(json))
@persisted = true
self
end
|
#role?(*wanted_roles) ⇒ Boolean
487
488
489
490
491
492
493
494
495
|
# File 'lib/softwear/auth/standard_model.rb', line 487
def role?(*wanted_roles)
return true if wanted_roles.empty?
if @roles.nil?
query("role #{Figaro.env.hub_app_name} #{id} #{wanted_roles.join(' ')}") == 'yes'
else
wanted_roles.any? { |r| @roles.include?(r.to_s) }
end
end
|
#to_json ⇒ Object
461
462
463
464
465
466
467
468
469
|
# File 'lib/softwear/auth/standard_model.rb', line 461
def to_json
{
id: @id,
email: @email,
first_name: @first_name,
last_name: @last_name
}
.to_json
end
|
#update_attributes(attributes = {}) ⇒ Object
452
453
454
455
456
457
458
459
|
# File 'lib/softwear/auth/standard_model.rb', line 452
def update_attributes(attributes={})
return if attributes.blank?
attributes = attributes.with_indifferent_access
REMOTE_ATTRIBUTES.each do |attr|
instance_variable_set("@#{attr}", attributes[attr])
end
end
|
#valid_password?(pass) ⇒ Boolean
483
484
485
|
# File 'lib/softwear/auth/standard_model.rb', line 483
def valid_password?(pass)
query("pass #{id} #{pass}") == 'yes'
end
|