lib/touth/authenticator.rb in touth-1.2.0 vs lib/touth/authenticator.rb in touth-1.3.0
- old
+ new
@@ -1,59 +1,75 @@
+require 'base64'
+
+
module Touth
module Authenticator
+ class << self
- module_function
+ def issue_access_token(resource, lifetime = Touth.access_token_lifetime)
+ expires_at = Time.now.to_i + lifetime
- def issue_access_token(resource, lifetime = Touth.access_token_lifetime)
- expires_at = Time.now.to_i + lifetime
+ data = Marshal.dump({
+ class: resource.class,
+ id: resource.id,
+ secret: token_secret(resource),
+ expires_at: expires_at,
+ })
- data = Marshal.dump([
- resource.class,
- resource.id,
- expires_at,
- ])
+ data_sign = Touth.digest data
- data_sign = Touth.digest data
- data_key = gen_data_key resource, data_sign
+ Base64.urlsafe_encode64 [
+ data,
+ data_sign,
+ ].join
+ end
- [
- data_sign,
- data_key,
- data,
- ].join.unpack('H*')[0]
- end
+ def valid_access_token?(token)
+ !!get_resource(token)
+ end
- def valid_access_token?(token)
- !!get_resource(token)
- end
+ def get_resource(token)
+ return unless token
- def get_resource(token)
- @access_token_data_cache ||= {}
- resource = @access_token_data_cache[token]
+ resource = Store.access_tokens[token]
- return resource if resource
+ return resource if resource
- @access_token_data_cache[token] = nil
+ Store.access_tokens[token] = nil
- begin
- data_sign, data_key, data = [token].pack('H*').unpack 'A32A32A*'
+ begin
+ data = Base64.urlsafe_decode64(token)
+ data_sign = data.slice! -32..-1
- if data_sign == Touth.digest(data)
- resource_class, id, expires_at = Marshal.load data
+ if data_sign == Touth.digest(data)
+ data = Marshal.load data
- resource = resource_class.find id
+ resource = data[:class].find data[:id]
- if gen_data_key(resource, data_sign) == data_key && Time.now.to_i < expires_at
- @access_token_data_cache[token] = resource
+ if token_secret(resource) == data[:secret] && Time.now.to_i < data[:expires_at]
+ Store.access_tokens[token] = resource
+ end
end
+ rescue
+ nil
end
- rescue
- nil
end
- end
- def gen_data_key(resource, data_sign)
- Touth.digest [data_sign, resource.send(Touth.password_field)].join
- end
+ def token_secret(resource)
+ password = resource.send Touth.password_field
+ Touth.digest(password)[0..16]
+ end
+ def set_current(resource)
+ return unless resource
+
+ resource_name = Touth.get_resource_name resource.class.name
+ Store.currents[resource_name] = resource
+ end
+
+ def current(resource_name)
+ Store.currents[resource_name]
+ end
+
+ end
end
end