Class: Softwear::Auth::StandardModel

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Conversion, ActiveModel::Model
Defined in:
lib/softwear/auth/standard_model.rb

Direct Known Subclasses

Model, StubbedModel

Defined Under Namespace

Classes: AccessDeniedError, AuthServerDown, AuthServerError, InvalidCommandError

Constant Summary collapse

REMOTE_ATTRIBUTES =
INSTANCE METHODS ======================
[
  :id, :email, :first_name, :last_name,
  :roles, :groups, :profile_picture_url,
  :default_view, :rights
]

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ StandardModel



469
470
471
# File 'lib/softwear/auth/standard_model.rb', line 469

def initialize(attributes = {})
  update_attributes(attributes)
end

Class Attribute Details

.auth_server_went_down_atObject

Returns the value of attribute auth_server_went_down_at.



28
29
30
# File 'lib/softwear/auth/standard_model.rb', line 28

def auth_server_went_down_at
  @auth_server_went_down_at
end

.query_cacheObject

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



45
46
47
# File 'lib/softwear/auth/standard_model.rb', line 45

def query_cache
  @query_cache ||= ThreadSafe::Cache.new
end

.query_cache_expiryObject



49
50
51
# File 'lib/softwear/auth/standard_model.rb', line 49

def query_cache_expiry
  @query_cache_expiry || Figaro.env.query_cache_expiry.try(:to_f) || 1.hour
end

.sent_auth_server_down_emailObject

Returns the value of attribute sent_auth_server_down_email.



29
30
31
# File 'lib/softwear/auth/standard_model.rb', line 29

def sent_auth_server_down_email
  @sent_auth_server_down_email
end

.time_before_down_emailObject

Returns the value of attribute time_before_down_email.



30
31
32
# File 'lib/softwear/auth/standard_model.rb', line 30

def time_before_down_email
  @time_before_down_email
end

.total_query_cacheObject

Returns the value of attribute total_query_cache.



25
26
27
# File 'lib/softwear/auth/standard_model.rb', line 25

def total_query_cache
  @total_query_cache
end

Instance Attribute Details

#persistedObject (readonly) Also known as: persisted?

Returns the value of attribute persisted.



450
451
452
# File 'lib/softwear/auth/standard_model.rb', line 450

def persisted
  @persisted
end

Class Method Details

.abstract_class?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/softwear/auth/standard_model.rb', line 20

def abstract_class?
  true
end

.allObject

Returns an array of all registered users



386
387
388
389
390
391
# File 'lib/softwear/auth/standard_model.rb', line 386

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_tableObject



134
135
136
# File 'lib/softwear/auth/standard_model.rb', line 134

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


422
423
424
425
426
427
428
429
430
431
# File 'lib/softwear/auth/standard_model.rb', line 422

def auth(token, app_name = nil)
  response = validate_response query "auth #{app_name || Figaro.env.hub_app_name} #{token}"

  return false unless response =~ /^yes/

  json = response.sub(/^yes/, '')
  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.

Returns:

  • (Boolean)


36
37
38
# File 'lib/softwear/auth/standard_model.rb', line 36

def auth_server_down?
  !!auth_server_went_down_at
end

.auth_server_down_mailerObject

Override this in your subclasses! The mailer should have auth_server_down(time) and auth_server_up(time)



57
58
59
# File 'lib/softwear/auth/standard_model.rb', line 57

def auth_server_down_mailer
  # override me
end

.auth_server_hostObject

Host of the auth server, from ‘auth_server_endpoint’ env variable. Defaults to localhost.



151
152
153
154
155
156
157
158
159
160
# File 'lib/softwear/auth/standard_model.rb', line 151

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_portObject

Port of the auth server, from ‘auth_server_endpoint’ env variable. Defaults to 2900.



166
167
168
169
170
171
172
173
# File 'lib/softwear/auth/standard_model.rb', line 166

def auth_server_port
  endpoint = Figaro.env.auth_server_endpoint
  if endpoint.try(:include?, ':')
    endpoint.split(':').last
  else
    2900
  end
end

.base_classObject



66
67
68
# File 'lib/softwear/auth/standard_model.rb', line 66

def base_class
  self
end

.default_socketObject



179
180
181
182
183
184
185
186
187
# File 'lib/softwear/auth/standard_model.rb', line 179

def default_socket
  if existing = Thread.current[:auth_socket]
    return existing
  end

  Thread.current[:auth_socket] = zmq.connect(
    :REQ, "tcp://#{auth_server_host}:#{auth_server_port}"
  )
end

.destroy_default_socket!Object



189
190
191
# File 'lib/softwear/auth/standard_model.rb', line 189

def destroy_default_socket!
  Thread.current[:auth_socket].try(:destroy) rescue nil
end

.expire_query_cacheObject

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.



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/softwear/auth/standard_model.rb', line 220

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



363
364
365
366
367
# File 'lib/softwear/auth/standard_model.rb', line 363

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



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/softwear/auth/standard_model.rb', line 347

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)



372
373
374
# File 'lib/softwear/auth/standard_model.rb', line 372

def find_by(options)
  filter_all(:find, options)
end

.force_query(message) ⇒ Object

Runs a query through the server without error or cache checking.



315
316
317
318
319
320
321
322
# File 'lib/softwear/auth/standard_model.rb', line 315

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.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/softwear/auth/standard_model.rb', line 95

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})\n      end\n    RUBY\n\n  else\n    class_name  = options[:class_name]  || assoc.singularize.camelize\n    foreign_key = options[:foreign_key] || 'user_id'\n\n    class_eval <<-RUBY, __FILE__, __LINE__ + 1\n      def \#{assoc}\n        \#{class_name}.where(\#{foreign_key}: id)\n      end\n    RUBY\n  end\nend\n", __FILE__, __LINE__ + 1

.loggerObject

Overridable logger method used when recording query benchmarks



436
437
438
# File 'lib/softwear/auth/standard_model.rb', line 436

def logger
  Rails.logger
end

.new(*args) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/softwear/auth/standard_model.rb', line 78

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_group(group_code) ⇒ Object

Returns array of all users in the given group



409
410
411
412
413
414
# File 'lib/softwear/auth/standard_model.rb', line 409

def of_group(group_code)
  json = validate_response query "ofgroup #{Figaro.env.hub_app_name} #{group_code}"

  objects = JSON.parse(json).map(&method(:new))
  objects.each { |u| u.instance_variable_set(:@persisted, true) }
end

.of_role(*roles) ⇒ Object

Returns array of all users with the given roles



396
397
398
399
400
401
402
403
404
# File 'lib/softwear/auth/standard_model.rb', line 396

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.



122
123
124
125
126
127
128
129
130
131
132
# File 'lib/softwear/auth/standard_model.rb', line 122

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_keyObject



62
63
64
# File 'lib/softwear/auth/standard_model.rb', line 62

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.



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
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/softwear/auth/standard_model.rb', line 242

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.



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/softwear/auth/standard_model.rb', line 197

def raw_query(message)
  begin
    default_socket.send message
  end

  response = default_socket.recv.try(:chomp)
  if response.nil?
    destroy_default_socket!
    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.



141
142
143
144
145
# File 'lib/softwear/auth/standard_model.rb', line 141

def record(before, after, type, body)
  ms = (after - before) * 1000
  # The garbage in this string gives us the bold and color
  Rails.logger.info "  \033[1m\033[33m#{type} (#{'%.1f' % ms}ms)\033[0m #{body}"
end

.relation_delegate_classObject



70
71
72
# File 'lib/softwear/auth/standard_model.rb', line 70

def relation_delegate_class(*)
  self
end

.unscopedObject



74
75
76
# File 'lib/softwear/auth/standard_model.rb', line 74

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)



332
333
334
335
336
337
338
339
340
341
342
# File 'lib/softwear/auth/standard_model.rb', line 332

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)



379
380
381
# File 'lib/softwear/auth/standard_model.rb', line 379

def where(options)
  filter_all(:select, options)
end

.zmqObject



175
176
177
# File 'lib/softwear/auth/standard_model.rb', line 175

def zmq
  $zmq_context ||= ZMQ::Context.new
end

Instance Method Details

#force_query(*a) ⇒ Object



461
462
463
# File 'lib/softwear/auth/standard_model.rb', line 461

def force_query(*a)
  self.class.force_query(*a)
end

#full_nameObject



500
501
502
# File 'lib/softwear/auth/standard_model.rb', line 500

def full_name
  "#{@first_name} #{@last_name}"
end

#group?(group) ⇒ Boolean

Returns:

  • (Boolean)


518
519
520
521
522
523
524
# File 'lib/softwear/auth/standard_model.rb', line 518

def group?(group)
  if @groups.nil?
    query("group #{Figaro.env.hub_app_name} #{id} #{group}") == 'yes'
  else
    @groups.include?(group)
  end
end

#loggerObject



464
465
466
# File 'lib/softwear/auth/standard_model.rb', line 464

def logger
  self.class.logger
end

#query(*a) ⇒ Object

Various class methods accessible on instances



455
456
457
# File 'lib/softwear/auth/standard_model.rb', line 455

def query(*a)
  self.class.query(*a)
end

#raw_query(*a) ⇒ Object



458
459
460
# File 'lib/softwear/auth/standard_model.rb', line 458

def raw_query(*a)
  self.class.raw_query(*a)
end

#reloadObject



492
493
494
495
496
497
498
# File 'lib/softwear/auth/standard_model.rb', line 492

def reload
  json = validate_response query "get #{id}"

  update_attributes(JSON.parse(json))
  @persisted = true
  self
end

#role?(*wanted_roles) ⇒ Boolean

Returns:

  • (Boolean)


508
509
510
511
512
513
514
515
516
# File 'lib/softwear/auth/standard_model.rb', line 508

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_jsonObject



482
483
484
485
486
487
488
489
490
# File 'lib/softwear/auth/standard_model.rb', line 482

def to_json
  {
    id:         @id,
    email:      @email,
    first_name: @first_name,
    last_name:  @last_name
  }
    .to_json
end

#update_attributes(attributes = {}) ⇒ Object



473
474
475
476
477
478
479
480
# File 'lib/softwear/auth/standard_model.rb', line 473

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

Returns:

  • (Boolean)


504
505
506
# File 'lib/softwear/auth/standard_model.rb', line 504

def valid_password?(pass)
  query("pass #{id} #{pass}") == 'yes'
end