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 @@ ...@@ -31,6 +31,9 @@
# #
class ApplicationSetting < ActiveRecord::Base class ApplicationSetting < ActiveRecord::Base
include TokenAuthenticatable
add_authentication_token_field :runners_registration_token
CACHE_KEY = 'application_setting.last' CACHE_KEY = 'application_setting.last'
serialize :restricted_visibility_levels serialize :restricted_visibility_levels
......
module TokenAuthenticatable module TokenAuthenticatable
extend ActiveSupport::Concern extend ActiveSupport::Concern
module ClassMethods class_methods do
def find_by_authentication_token(authentication_token = nil) def authentication_token_fields
if authentication_token @token_fields || []
where(authentication_token: authentication_token).first
end
end end
end
def ensure_authentication_token private
if authentication_token.blank?
self.authentication_token = generate_authentication_token def add_authentication_token_field(token_field)
end @token_fields = [] unless @token_fields
end @token_fields << token_field
def reset_authentication_token! define_singleton_method("find_by_#{token_field}") do |token|
self.authentication_token = generate_authentication_token where(token_field => token).first if token
save end
define_method("ensure_#{token_field}") do
write_attribute(token_field, generate_token_for(token_field)) if
read_attribute(token_field).blank?
end
define_method("reset_#{token_field}!") do
write_attribute(token_field, generate_token_for(token_field))
save
end
end
end end
private private
def generate_authentication_token def generate_token_for(token_field)
loop do loop do
token = Devise.friendly_token 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 end
end end
...@@ -69,8 +69,10 @@ class User < ActiveRecord::Base ...@@ -69,8 +69,10 @@ class User < ActiveRecord::Base
include Gitlab::CurrentSettings include Gitlab::CurrentSettings
include Referable include Referable
include Sortable include Sortable
include TokenAuthenticatable
include CaseSensitivity include CaseSensitivity
include TokenAuthenticatable
add_authentication_token_field :authentication_token
default_value_for :admin, false default_value_for :admin, false
default_value_for :can_create_group, gitlab_config.default_can_create_group 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