Skip to content
Snippets Groups Projects
Commit 36979875 authored by James Edwards-Jones's avatar James Edwards-Jones
Browse files

TokenAuthenticatable allows non-unique tokens

Avoids needing an index to repeatedly check that
the token doesn't already exist when saving.
parent 5bb7067a
No related branches found
No related tags found
No related merge requests found
Loading
Loading
@@ -5,15 +5,15 @@ module TokenAuthenticatable
 
private
 
def write_new_token(token_field)
new_token = generate_available_token(token_field)
def write_new_token(token_field, unique: true)
new_token = generate_available_token(token_field, unique: unique)
write_attribute(token_field, new_token)
end
 
def generate_available_token(token_field)
def generate_available_token(token_field, unique:)
loop do
token = generate_token(token_field)
break token unless self.class.unscoped.find_by(token_field => token)
break token unless unique && self.class.unscoped.find_by(token_field => token)
end
end
 
Loading
Loading
@@ -28,17 +28,19 @@ module TokenAuthenticatable
 
private # rubocop:disable Lint/UselessAccessModifier
 
def add_authentication_token_field(token_field)
def add_authentication_token_field(token_field, unique: true)
@token_fields = [] unless @token_fields
@token_fields << token_field
 
define_singleton_method("find_by_#{token_field}") do |token|
find_by(token_field => token) if token
if unique
define_singleton_method("find_by_#{token_field}") do |token|
find_by(token_field => token) if token
end
end
 
define_method("ensure_#{token_field}") do
current_token = read_attribute(token_field)
current_token.blank? ? write_new_token(token_field) : current_token
current_token.blank? ? write_new_token(token_field, unique: unique) : current_token
end
 
define_method("set_#{token_field}") do |token|
Loading
Loading
@@ -54,7 +56,7 @@ module TokenAuthenticatable
 
# Resets the token, but only saves when the database is in read & write mode
define_method("reset_#{token_field}!") do
write_new_token(token_field)
write_new_token(token_field, unique: unique)
save! if Gitlab::Database.read_write?
end
end
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment