2014-11-21 14:37:56 +01:00
|
|
|
# Generic token verifier with foodcoop scope
|
|
|
|
# @todo use +Rails.application.message_verifier+ when possible
|
2014-01-04 20:12:01 +01:00
|
|
|
class TokenVerifier < ActiveSupport::MessageVerifier
|
|
|
|
def initialize(prefix)
|
|
|
|
super(self.class.secret)
|
|
|
|
@_prefix = prefix.is_a?(Array) ? prefix.join(':') : prefix.to_s
|
|
|
|
end
|
|
|
|
|
2021-03-01 15:27:26 +01:00
|
|
|
def generate(message = nil)
|
2014-01-04 20:12:01 +01:00
|
|
|
fullmessage = [FoodsoftConfig.scope, @_prefix]
|
|
|
|
fullmessage.append(message) unless message.nil?
|
|
|
|
super(fullmessage)
|
|
|
|
end
|
|
|
|
|
|
|
|
def verify(message)
|
|
|
|
r = super(message)
|
2015-01-14 21:15:08 +01:00
|
|
|
raise InvalidMessage unless r.is_a?(Array) && r.length >= 2 && r.length <= 3
|
2014-01-04 20:12:01 +01:00
|
|
|
raise InvalidScope unless r[0] == FoodsoftConfig.scope
|
|
|
|
raise InvalidPrefix unless r[1] == @_prefix
|
2021-03-01 15:27:26 +01:00
|
|
|
|
2014-01-04 20:12:01 +01:00
|
|
|
# return original message
|
|
|
|
if r.length > 2
|
|
|
|
r[2]
|
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class InvalidMessage < ActiveSupport::MessageVerifier::InvalidSignature; end
|
2021-03-01 15:27:26 +01:00
|
|
|
|
2014-01-04 20:12:01 +01:00
|
|
|
class InvalidScope < ActiveSupport::MessageVerifier::InvalidSignature; end
|
2021-03-01 15:27:26 +01:00
|
|
|
|
2014-01-04 20:12:01 +01:00
|
|
|
class InvalidPrefix < ActiveSupport::MessageVerifier::InvalidSignature; end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def self.secret
|
2014-01-16 13:01:11 +01:00
|
|
|
# secret_key_base for Rails 4, but Rails 3 initializer may still be used
|
2015-01-14 21:15:08 +01:00
|
|
|
Foodsoft::Application.config.secret_key_base || Foodsoft::Application.config.secret_token
|
2014-01-04 20:12:01 +01:00
|
|
|
end
|
|
|
|
end
|