2014-07-09 08:42:25 -04:00
|
|
|
module TokenAuthenticatable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2016-06-30 08:41:19 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def write_new_token(token_field)
|
2016-08-19 19:33:46 -04:00
|
|
|
new_token = generate_available_token(token_field)
|
2016-06-30 08:41:19 -04:00
|
|
|
write_attribute(token_field, new_token)
|
|
|
|
end
|
|
|
|
|
2016-08-19 19:33:46 -04:00
|
|
|
def generate_available_token(token_field)
|
2016-06-30 08:41:19 -04:00
|
|
|
loop do
|
2016-08-19 19:33:46 -04:00
|
|
|
token = generate_token(token_field)
|
2016-06-30 08:41:19 -04:00
|
|
|
break token unless self.class.unscoped.find_by(token_field => token)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-08-19 19:33:46 -04:00
|
|
|
def generate_token(token_field)
|
|
|
|
Devise.friendly_token
|
|
|
|
end
|
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
class_methods do
|
|
|
|
def authentication_token_fields
|
|
|
|
@token_fields || []
|
2014-07-09 08:42:25 -04:00
|
|
|
end
|
|
|
|
|
2016-07-19 09:07:52 -04:00
|
|
|
private # rubocop:disable Lint/UselessAccessModifier
|
2015-12-10 04:48:37 -05:00
|
|
|
|
|
|
|
def add_authentication_token_field(token_field)
|
|
|
|
@token_fields = [] unless @token_fields
|
|
|
|
@token_fields << token_field
|
2014-07-09 08:42:25 -04:00
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
define_singleton_method("find_by_#{token_field}") do |token|
|
2015-12-14 21:53:52 -05:00
|
|
|
find_by(token_field => token) if token
|
2015-12-10 04:48:37 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
define_method("ensure_#{token_field}") do
|
2015-12-23 04:47:18 -05:00
|
|
|
current_token = read_attribute(token_field)
|
|
|
|
current_token.blank? ? write_new_token(token_field) : current_token
|
|
|
|
end
|
|
|
|
|
2016-10-02 18:30:44 -04:00
|
|
|
define_method("set_#{token_field}") do |token|
|
|
|
|
write_attribute(token_field, token) if token
|
|
|
|
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
|
2017-08-03 22:20:34 -04:00
|
|
|
send("reset_#{token_field}!") if read_attribute(token_field).blank? # rubocop:disable GitlabSecurity/PublicSend
|
|
|
|
|
2015-12-23 03:29:04 -05:00
|
|
|
read_attribute(token_field)
|
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
|
2015-12-23 04:47:18 -05:00
|
|
|
write_new_token(token_field)
|
2017-09-19 03:44:58 -04:00
|
|
|
save! if Gitlab::Database.read_write?
|
2015-12-10 04:48:37 -05:00
|
|
|
end
|
|
|
|
end
|
2014-07-09 08:42:25 -04:00
|
|
|
end
|
|
|
|
end
|