class Authenticatable::Proxy
The authenticatable session, persisted in env
Public Class Methods
# File lib/authenticatable/proxy.rb, line 6 def initialize(env) @env = env @current = {} @config = Authenticatable.config end
Public Instance Methods
Check if the given scope is already signed in or else run authenticated strategies it. This does not halt the flow of control and is a passive attempt to authenticate only. :api: public
# File lib/authenticatable/proxy.rb, line 15 def authenticate(scope) current?(scope) || run_serializers_for(scope) || nil end
Same as authenticate
except on failure it will trow a :unauthenticated symbol. :api: public
# File lib/authenticatable/proxy.rb, line 22 def authenticate!(scope) unless (resource = authenticate(scope)) raise Authenticatable::UnauthenticatedError end resource end
Provides access to the user object in a given scope for a request. Will be nil if not logged in or an instance of the resource if logged in.
Examples:
env['authenticatable'].current?(:user) => #<User> env['authenticatable'].current?(:admin) => #<Admin>
# File lib/authenticatable/proxy.rb, line 66 def current?(scope) scope = scope.to_sym # Make sure to always use symbols. @current[scope] end
Add a resource/scope into the @current hash. This method is called after an authentication strategy has succeeded, but can also be used in tests/debugging to manually sign in a user.
PLEASE NOTICE that this method DOES NOT perform any authentication strategies. To authenticate a user, you must use the authenticate
method instead.
# File lib/authenticatable/proxy.rb, line 35 def sign_in(resource, serializer = nil) scope = scope_from_resource(resource) @current[scope] = resource unless serializer.nil? klass = initialize_serializer(scope, serializer) klass.store(resource.id) end resource end
Remove a resource/scope from the @current hash
# File lib/authenticatable/proxy.rb, line 48 def sign_out(resource, serializer = nil) scope = scope_from_resource(resource) @current[scope] = nil unless serializer.nil? klass = initialize_serializer(scope, serializer) klass.purge! end true end
Private Instance Methods
Return a constantized class by scope name.
# File lib/authenticatable/proxy.rb, line 87 def initialize_serializer(scope, name) class_name = name.to_s.classify klass = "Authenticatable::Serializers::#{class_name}".constantize klass.new(@env, scope) end
:api: private
# File lib/authenticatable/proxy.rb, line 74 def run_serializers_for(scope) serializers = %i[session] serializers.each do |name| serializer = initialize_serializer(scope, name) if (record = serializer.fetch) sign_in(record) return record end end nil end
Convert an instance to a scope symbol by returning the param_key from ActiveModel#model_name Examples:
scope_from_resource(#<User>) => :user scope_from_resource(#<Admin>) => :admin
# File lib/authenticatable/proxy.rb, line 98 def scope_from_resource(resource) scope = resource.model_name.param_key scope.to_sym # Make sure to always use symbols. end