debian-mirror-gitlab/app/models/concerns/token_authenticatable.rb

61 lines
1.7 KiB
Ruby
Raw Normal View History

2014-09-02 18:07:02 +05:30
module TokenAuthenticatable
extend ActiveSupport::Concern
2016-09-13 17:45:13 +05:30
private
def write_new_token(token_field)
2017-08-17 22:00:37 +05:30
new_token = generate_available_token(token_field)
2016-09-13 17:45:13 +05:30
write_attribute(token_field, new_token)
end
2017-08-17 22:00:37 +05:30
def generate_available_token(token_field)
2016-09-13 17:45:13 +05:30
loop do
2017-08-17 22:00:37 +05:30
token = generate_token(token_field)
2016-09-13 17:45:13 +05:30
break token unless self.class.unscoped.find_by(token_field => token)
end
end
2017-08-17 22:00:37 +05:30
def generate_token(token_field)
Devise.friendly_token
end
2015-12-23 02:04:40 +05:30
class_methods do
def authentication_token_fields
@token_fields || []
2014-09-02 18:07:02 +05:30
end
2016-09-13 17:45:13 +05:30
private # rubocop:disable Lint/UselessAccessModifier
2015-12-23 02:04:40 +05:30
def add_authentication_token_field(token_field)
@token_fields = [] unless @token_fields
@token_fields << token_field
2014-09-02 18:07:02 +05:30
2015-12-23 02:04:40 +05:30
define_singleton_method("find_by_#{token_field}") do |token|
find_by(token_field => token) if token
end
define_method("ensure_#{token_field}") do
current_token = read_attribute(token_field)
current_token.blank? ? write_new_token(token_field) : current_token
end
2017-08-17 22:00:37 +05:30
define_method("set_#{token_field}") do |token|
write_attribute(token_field, token) if token
end
2018-03-17 18:26:18 +05:30
# Returns a token, but only saves when the database is in read & write mode
define_method("ensure_#{token_field}!") do
2018-03-17 18:26:18 +05:30
send("reset_#{token_field}!") if read_attribute(token_field).blank? # rubocop:disable GitlabSecurity/PublicSend
read_attribute(token_field)
2015-12-23 02:04:40 +05:30
end
2018-03-17 18:26:18 +05:30
# Resets the token, but only saves when the database is in read & write mode
2015-12-23 02:04:40 +05:30
define_method("reset_#{token_field}!") do
write_new_token(token_field)
2018-03-17 18:26:18 +05:30
save! if Gitlab::Database.read_write?
2015-12-23 02:04:40 +05:30
end
end
2014-09-02 18:07:02 +05:30
end
end