2014-07-09 08:42:25 -04:00
|
|
|
module TokenAuthenticatable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
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
|
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
private
|
|
|
|
|
|
|
|
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|
|
|
|
|
where(token_field => token).first if token
|
|
|
|
end
|
|
|
|
|
|
|
|
define_method("ensure_#{token_field}") do
|
|
|
|
write_attribute(token_field, generate_token_for(token_field)) if
|
|
|
|
read_attribute(token_field).blank?
|
|
|
|
end
|
|
|
|
|
|
|
|
define_method("reset_#{token_field}!") do
|
|
|
|
write_attribute(token_field, generate_token_for(token_field))
|
|
|
|
save
|
|
|
|
end
|
|
|
|
end
|
2014-07-09 08:42:25 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2015-12-10 04:48:37 -05:00
|
|
|
def generate_token_for(token_field)
|
2014-07-09 08:42:25 -04:00
|
|
|
loop do
|
|
|
|
token = Devise.friendly_token
|
2015-12-10 04:48:37 -05:00
|
|
|
break token unless self.class.unscoped.where(token_field => token).first
|
2014-07-09 08:42:25 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|