2018-08-03 13:22:24 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-07-09 08:42:25 -04:00
|
|
|
module TokenAuthenticatable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2016-06-30 08:41:19 -04:00
|
|
|
private
|
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
class_methods do
|
2016-07-19 09:07:52 -04:00
|
|
|
private # rubocop:disable Lint/UselessAccessModifier
|
2015-12-10 04:48:37 -05:00
|
|
|
|
2018-10-29 12:06:45 -04:00
|
|
|
def add_authentication_token_field(token_field, options = {})
|
2015-12-10 04:48:37 -05:00
|
|
|
@token_fields = [] unless @token_fields
|
2018-10-31 13:28:42 -04:00
|
|
|
unique = options.fetch(:unique, true)
|
2018-10-29 12:06:45 -04:00
|
|
|
|
|
|
|
if @token_fields.include?(token_field)
|
|
|
|
raise ArgumentError.new("#{token_field} already configured via add_authentication_token_field")
|
|
|
|
end
|
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
@token_fields << token_field
|
2014-07-09 08:42:25 -04:00
|
|
|
|
2018-10-29 12:06:45 -04:00
|
|
|
attr_accessor :cleartext_tokens
|
|
|
|
|
|
|
|
strategy = if options[:digest]
|
|
|
|
TokenAuthenticatableStrategies::Digest.new(self, token_field, options)
|
|
|
|
else
|
|
|
|
TokenAuthenticatableStrategies::Insecure.new(self, token_field, options)
|
|
|
|
end
|
|
|
|
|
2018-10-31 13:28:42 -04:00
|
|
|
if unique
|
|
|
|
define_singleton_method("find_by_#{token_field}") do |token|
|
|
|
|
strategy.find_token_authenticatable(token)
|
|
|
|
end
|
2015-12-10 04:48:37 -05:00
|
|
|
end
|
|
|
|
|
2018-10-29 12:06:45 -04:00
|
|
|
define_method(token_field) do
|
|
|
|
strategy.get_token(self)
|
2015-12-23 04:47:18 -05:00
|
|
|
end
|
|
|
|
|
2016-10-02 18:30:44 -04:00
|
|
|
define_method("set_#{token_field}") do |token|
|
2018-10-29 12:06:45 -04:00
|
|
|
strategy.set_token(self, token)
|
|
|
|
end
|
|
|
|
|
|
|
|
define_method("ensure_#{token_field}") do
|
|
|
|
strategy.ensure_token(self)
|
2016-10-02 18:30:44 -04:00
|
|
|
end
|
|
|
|
|
2017-09-19 03:44:58 -04:00
|
|
|
# Returns a token, but only saves when the database is in read & write mode
|
2015-12-23 04:47:18 -05:00
|
|
|
define_method("ensure_#{token_field}!") do
|
2018-10-29 12:06:45 -04:00
|
|
|
strategy.ensure_token!(self)
|
2015-12-10 04:48:37 -05:00
|
|
|
end
|
|
|
|
|
2017-09-19 03:44:58 -04:00
|
|
|
# Resets the token, but only saves when the database is in read & write mode
|
2015-12-10 04:48:37 -05:00
|
|
|
define_method("reset_#{token_field}!") do
|
2018-10-29 12:06:45 -04:00
|
|
|
strategy.reset_token!(self)
|
2015-12-10 04:48:37 -05:00
|
|
|
end
|
|
|
|
end
|
2014-07-09 08:42:25 -04:00
|
|
|
end
|
|
|
|
end
|