debian-mirror-gitlab/app/models/concerns/token_authenticatable.rb

62 lines
1.7 KiB
Ruby
Raw Normal View History

2018-11-20 20:47:30 +05:30
# frozen_string_literal: true
2014-09-02 18:07:02 +05:30
module TokenAuthenticatable
extend ActiveSupport::Concern
2016-09-13 17:45:13 +05:30
private
2015-12-23 02:04:40 +05:30
class_methods do
2016-09-13 17:45:13 +05:30
private # rubocop:disable Lint/UselessAccessModifier
2015-12-23 02:04:40 +05:30
2018-11-18 11:00:15 +05:30
def add_authentication_token_field(token_field, options = {})
2019-02-15 15:39:39 +05:30
if token_authenticatable_fields.include?(token_field)
2018-11-18 11:00:15 +05:30
raise ArgumentError.new("#{token_field} already configured via add_authentication_token_field")
end
2019-02-15 15:39:39 +05:30
token_authenticatable_fields.push(token_field)
2014-09-02 18:07:02 +05:30
2018-11-18 11:00:15 +05:30
attr_accessor :cleartext_tokens
2019-02-15 15:39:39 +05:30
strategy = TokenAuthenticatableStrategies::Base
.fabricate(self, token_field, options)
2018-11-18 11:00:15 +05:30
2019-02-15 15:39:39 +05:30
if options.fetch(:unique, true)
2018-12-13 13:39:08 +05:30
define_singleton_method("find_by_#{token_field}") do |token|
strategy.find_token_authenticatable(token)
end
2015-12-23 02:04:40 +05:30
end
2018-11-18 11:00:15 +05:30
define_method(token_field) do
strategy.get_token(self)
end
2017-08-17 22:00:37 +05:30
define_method("set_#{token_field}") do |token|
2018-11-18 11:00:15 +05:30
strategy.set_token(self, token)
end
define_method("ensure_#{token_field}") do
strategy.ensure_token(self)
2017-08-17 22:00:37 +05:30
end
2018-03-17 18:26:18 +05:30
# Returns a token, but only saves when the database is in read & write mode
define_method("ensure_#{token_field}!") do
2018-11-18 11:00:15 +05:30
strategy.ensure_token!(self)
2015-12-23 02:04:40 +05:30
end
2018-03-17 18:26:18 +05:30
# Resets the token, but only saves when the database is in read & write mode
2015-12-23 02:04:40 +05:30
define_method("reset_#{token_field}!") do
2018-11-18 11:00:15 +05:30
strategy.reset_token!(self)
2015-12-23 02:04:40 +05:30
end
2019-02-15 15:39:39 +05:30
define_method("#{token_field}_matches?") do |other_token|
token = read_attribute(token_field)
token.present? && ActiveSupport::SecurityUtils.variable_size_secure_compare(other_token, token)
end
end
def token_authenticatable_fields
@token_authenticatable_fields ||= []
2015-12-23 02:04:40 +05:30
end
2014-09-02 18:07:02 +05:30
end
end