Commit 9948e5bc authored by Grzegorz Bizon's avatar Grzegorz Bizon

Refactor `TokenAuthenticatable` to improve reusability

This adds a ability to use multiple different authentication token
fields in other models. From now on it is necessary to add
authentication token field manually in each class that implements this
mixin.
parent 4a32b07d
......@@ -31,6 +31,9 @@
#
class ApplicationSetting < ActiveRecord::Base
include TokenAuthenticatable
add_authentication_token_field :runners_registration_token
CACHE_KEY = 'application_setting.last'
serialize :restricted_visibility_levels
......
module TokenAuthenticatable
extend ActiveSupport::Concern
module ClassMethods
def find_by_authentication_token(authentication_token = nil)
if authentication_token
where(authentication_token: authentication_token).first
end
end
class_methods do
def authentication_token_fields
@token_fields || []
end
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
private
def add_authentication_token_field(token_field)
@token_fields = [] unless @token_fields
@token_fields << token_field
define_singleton_method("find_by_#{token_field}") do |token|
where(token_field => token).first if token
end
define_method("ensure_#{token_field}") do
write_attribute(token_field, generate_token_for(token_field)) if
read_attribute(token_field).blank?
end
def reset_authentication_token!
self.authentication_token = generate_authentication_token
define_method("reset_#{token_field}!") do
write_attribute(token_field, generate_token_for(token_field))
save
end
end
end
private
def generate_authentication_token
def generate_token_for(token_field)
loop do
token = Devise.friendly_token
break token unless self.class.unscoped.where(authentication_token: token).first
break token unless self.class.unscoped.where(token_field => token).first
end
end
end
......@@ -69,8 +69,10 @@ class User < ActiveRecord::Base
include Gitlab::CurrentSettings
include Referable
include Sortable
include TokenAuthenticatable
include CaseSensitivity
include TokenAuthenticatable
add_authentication_token_field :authentication_token
default_value_for :admin, false
default_value_for :can_create_group, gitlab_config.default_can_create_group
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment