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