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

50 lines
1.2 KiB
Ruby
Raw Normal View History

2014-09-02 18:07:02 +05:30
module TokenAuthenticatable
extend ActiveSupport::Concern
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
2015-12-23 02:04:40 +05:30
private
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
define_method("ensure_#{token_field}!") do
send("reset_#{token_field}!") if read_attribute(token_field).blank?
read_attribute(token_field)
2015-12-23 02:04:40 +05:30
end
define_method("reset_#{token_field}!") do
write_new_token(token_field)
2015-12-23 02:04:40 +05:30
save!
end
end
2014-09-02 18:07:02 +05:30
end
private
def write_new_token(token_field)
new_token = generate_token(token_field)
write_attribute(token_field, new_token)
end
def generate_token(token_field)
2014-09-02 18:07:02 +05:30
loop do
token = Devise.friendly_token
2015-12-23 02:04:40 +05:30
break token unless self.class.unscoped.find_by(token_field => token)
2014-09-02 18:07:02 +05:30
end
end
end