module Sinatra::AuthLane::Helpers
The AuthLane ‘Helpers` are helper methods that are made available to an application’s route definitions. It is the main interface between a Sinatra
Application and AuthLane
and enables easy interaction with the authorization logic by calling a specific helper method.
Public Instance Methods
Gets the credentials of the currently logged in user.
@example
get '/account' do authorized? @username = current_user.username @email = current_user[:email] # This works too (refer to SerializedUser for more info) mustache :account end
@return [SerializedUser, Object] the user data serialized into the Session, either as ‘SerializedUser`
or a custom class set by the developer.
# File lib/authlane/helper.rb, line 197 def current_user session[settings.authlane[:session_key]] end
@note This method uses {#authorized?} to decide, whether to redirect users to your app’s ‘failed_route`.
Check if a user is authorized to view a route.
It utilizes the Role and *Remember Strategy* to see if a user can access the route this helper method is called from. The first query inside this method is to look for logged in user credentials in the Session. If this fails, AuthLane attempts to login the user via Cookie token by calling the *Remember Strategy* that is defined for the application. If it succeeds, this method will continue normally (as in the user was already logged in ‘regularly’) and use the *Role Strategy* to check user privileges for the route, in case there were any specified when it was being called.
@example
get '/account' do protect! mustache :account end get '/admin' do protect! roles: [:Admin], failed_route: '/account' mustache :admin end
@param [Hash] roles A Hash specifying the **Role Strategy** to be used with its key and optional arguments as the value.
**Example:** `protect! :rolename => arguments`
@return [void]
@see Sinatra::AuthLane.create_role_strategy
create_role_strategy @see Sinatra::AuthLane.create_remember_strategy
create_remember_strategy
# File lib/authlane/helper.rb, line 45 def protect!(*roles) redirect settings.authlane[:failed_route] unless authorized?(*roles) end
Private Instance Methods
# File lib/authlane/helper.rb, line 205 def serialize_user(obj) if settings.authlane[:serialize_user].is_a? Array Sinatra::AuthLane::SerializedUser.new(obj, settings.authlane[:serialize_user]) elsif settings.authlane[:serialize_user].is_a? Class settings.authlane[:serialize_user].new(obj) end end