libSmalldb  v0.7-37-g795340f
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
SharedTokenMachine Class Reference

Description

Session management using a shared token.

Works well with CookieAuth authenticator. Implements secure login and logout; leaves a space for everything else.

This state machine requires two tables in SQL database: session and user. The session table stores tokens, the user table is used to check login and password pair.

See also
http://smalldb.org/security/

Usage example

$smalldb = new JsonDirBackend(...);
$smalldb->setContext([ 'auth' => new CookieAuth([...], $smalldb), ... ]);
$auth = $smalldb->getAuth();
$auth->getSessionMachine()->login($_POST['login'], $_POST['password']);
$auth->getSessionMachine()->logout();

Configuration Schema

The state machine is configured using JSON object passed to the constructor (the $config parameter). The object must match the following JSON schema (JSON format):

Inheritance diagram for SharedTokenMachine

Public Member Functions

 calculateViewValue ($id, $view, & $properties_cache=null, & $view_cache=null, & $persistent_view_cache=null)
 Resolve specific views. More...
 
- Public Member Functions inherited from FlupdoMachine
 __construct (IFlupdo $flupdo, IAuth $auth=null, IFlupdo $sphinx=null)
 Constructor. More...
 
 invokeTransition (Reference $ref, $transition_name, $args, & $returns, callable $new_id_callback=null)
 Invoke state machine transition. More...
 
 createListing ($filters, $filtering_flags=0)
 Create generic listing on this machine type. More...
 
 createQueryBuilder ()
 Create query builder. More...
 
 getState ($id)
 Get current state of state machine. More...
 
 getProperties ($id, & $state_cache=null)
 Get all properties of state machine, including it's state. More...
 
 encodeProperties ($properties)
 Encode properties to database representation. More...
 
 decodeProperties ($properties)
 Decode properties from database representation. More...
 
 describeId ()
 Reflection: Describe ID (primary key). More...
 
- Public Member Functions inherited from AbstractMachine
 __construct ()
 Constructor is left empty so the machine implementation can use it to obtain resources automatically via dependency injection. More...
 
 initializeMachine (Smalldb $smalldb, string $type, array $config)
 Configure machine. More...
 
 setDebugLogger (IDebugLogger $debug_logger)
 Set debug logger. More...
 
 getDebugLogger ()
 Get debug logger. More...
 
 getErrors ()
 Get errors found while loading the machine definition. More...
 
 getState ($id)
 Get current state of state machine. More...
 
 getProperties ($id, & $state_cache=null)
 Get properties of state machine, including it's state. More...
 
 getView ($id, $view, & $properties_cache=null, & $view_cache=null, & $persistent_view_cache=null)
 Get properties in given view. More...
 
 isTransitionAllowed (Reference $ref, $transition_name, $state=null, & $access_policy=null)
 Returns true if transition can be invoked right now. More...
 
 getAvailableTransitions (Reference $ref, $state=null)
 Get list of all available actions for state machine instance identified by $id. More...
 
 invokeTransition (Reference $ref, $transition_name, $args, & $returns, callable $new_id_callback=null)
 Invoke state machine transition. More...
 
 getMachineType ()
 Get type of this machine. More...
 
 ref ($id)
 Helper to create Reference to this machine. More...
 
 nullRef ()
 Helper to create null Reference to this machine. More...
 
 hotRef ($properties)
 Create pre-heated reference using properties loaded from elsewhere. More...
 
 performSelfCheck ()
 Perform self-check. More...
 
 findUnreachableStates ()
 Run DFS from not-exists state and return list of unreachable states. More...
 
 describeId ()
 Reflection: Describe ID (primary key). More...
 
 getUrlFormat ()
 Get URL format. More...
 
 getParentUrlFormat ()
 Get prent URL format. More...
 
 getPostActionUrlFormat ()
 Get URL for redirect-after-post. More...
 
 getMachineImplementationMTime ()
 Get mtime of machine implementation. More...
 
 getAllMachineStates ($having_section=null)
 Reflection: Get all states. More...
 
 describeMachineState ($state, $field=null)
 Reflection: Describe given machine state. More...
 
 describeAllMachineStates ($having_section=null)
 Reflection: Describe all states. More...
 
 getAllMachineActions ($having_section=null)
 Reflection: Get all actions (transitions) More...
 
 describeMachineAction ($action, $field=null)
 Reflection: Describe given machine action (transition) More...
 
 describeAllMachineActions ($having_section=null)
 Reflection: Describe all actions (transitions) More...
 
 getAllMachineProperties ($having_section=null)
 Reflection: Get all properties. More...
 
 describeMachineProperty ($property, $field=null)
 Reflection: Describe given property. More...
 
 describeAllMachineProperties ($having_section=null)
 Reflection: Describe all properties. More...
 
 getAllMachineViews ($having_section=null)
 Reflection: Get all views. More...
 
 describeMachineView ($view, $field=null)
 Reflection: Describe given view. More...
 
 describeAllMachineViews ($having_section=null)
 Reflection: Describe all views. More...
 
 getAllMachineReferences ($having_section=null)
 Reflection: Get all references. More...
 
 describeMachineReference ($reference, $field=null)
 Reflection: Describe given reference. More...
 
 describeAllMachineReferences ($having_section=null)
 Reflection: Describe all references. More...
 
 exportJson ($debug_opts=false)
 Export state machine as JSON siutable for Grafovatko. More...
 
 exportDot ($debug_opts=false)
 Export state machine to Graphviz source code. More...
 

Protected Member Functions

 configureMachine (array $config)
 Define state machine used by all instances of this type. More...
 
 setupDefaultMachine (array $config)
 Setup session machine. More...
 
 login ($ref, $user, $password)
 Login user. More...
 
 logout ($ref)
 Logout user - simply destroy session. More...
 
- Protected Member Functions inherited from FlupdoCrudMachine
 configureMachine (array $config)
 Define state machine used by all instances of this type. More...
 
 setupDefaultMachine (array $config)
 Setup basic CRUD machine. More...
 
 create (Reference $ref, $properties)
 Create. More...
 
 edit (Reference $ref, $properties)
 Edit. More...
 
 delete (Reference $ref)
 Delete. More...
 
 recalculateTree ()
 Recalculate nested-sets tree indices. More...
 
- Protected Member Functions inherited from FlupdoMachine
 configureMachine (array $config)
 Define state machine used by all instances of this type. More...
 
 scanTableColumns ()
 Scan table in database and populate properties. More...
 
 checkAccessPolicy ($access_policy_name, Reference $ref)
 Returns true if user has required access_policy. More...
 
 queryAddAccessPolicyCondition ($access_policy_name, $query)
 Adds conditions to enforce read access_policy to query object. More...
 
 queryAddFrom ($query)
 Add FROM clause. More...
 
 queryGetThisTable ($query)
 Get table name with alias. More...
 
 queryAddStateSelect ($query)
 Add state column into select clause of the $query. More...
 
 queryAddPropertiesSelect (\Smalldb::Flupdo::FlupdoBuilder $query)
 Add properties to select. More...
 
 queryAddPrimaryKeyWhere ($query, $id, $clause='where')
 Add primary key condition to where clause. More...
 
- Protected Member Functions inherited from AbstractMachine
 configureMachine (array $config)
 Define state machine used by all instances of this type. More...
 
 setupDefaultMachine (array $config)
 Setup default machine when initializeMachine is finished. More...
 
 loadMachineConfig (array $config, array $keys)
 Merge $config into state machine member variables (helper method). More...
 
 checkAccessPolicy ($access_policy, Reference $ref)
 Returns true if user has required access_policy to invoke a transition, which requires given access_policy. More...
 
 calculateViewValue ($id, $view, & $properties_cache=null, & $view_cache=null, & $persistent_view_cache=null)
 Calculate value of a view. More...
 
 urlFormat ($id, $url_fmt, $properties_cache)
 Create URL using properties and given format. More...
 
 resolveMachineReference ($reference_name, $properties_cache)
 Helper function to resolve reference to another machine. More...
 
 onStateChanged (Reference $ref, $old_state, $transition_name, $new_state)
 Called when state is changed, when transition invocation is completed. More...
 
 exportDotRenderExtras ($debug_opts)
 Render extra diagram features. More...
 
 exportJsonAddExtras ($debug_opts, $machine_graph)
 Add extra diagram features into the diagram. More...
 

Protected Attributes

 $table_columns
 Map of table columns. More...
 
 $user_login_filters
 User login listing. More...
 
 $user_login_property = 'email'
 State machine property containing the login. More...
 
 $user_password_property = 'password'
 State machine property containing the password hash. More...
 
- Protected Attributes inherited from FlupdoCrudMachine
 $owner_relation = null
 Relation defining shich machine owns this machine. More...
 
 $owner_create_transition = null
 Transition of owner to check when creating this machine. More...
 
 $nested_sets_table_columns
 Nested-sets configuration. More...
 
 $nested_sets_enabled = false
 Enable nested-sets tree? More...
 
 $nested_sets_order_by = 'id'
 Order by this column. More...
 
 $generate_random_id = null
 Generate random id? More...
 
 $time_created_table_column = null
 Set this column to CURRENT_TIMESTAMP on create transition. More...
 
 $time_modified_table_column = null
 Set this column to CURRENT_TIMESTAMP on edit transition. If MySQL is in use, it is better to use CURRENT_TIMESTAMP column feature. More...
 
- Protected Attributes inherited from FlupdoMachine
 $flupdo
 Database connection. More...
 
 $sphinx
 Sphinx indexer connection. More...
 
 $auth
 Authenticator (gets user id and role) More...
 
 $table
 Name of SQL table, where machine properties are stored. More...
 
 $table_alias = null
 Alias of the $table. More...
 
 $pk_columns = null
 List of columns which are used as primary key. More...
 
 $json_columns = array()
 List of columns which are serialized as JSON in database. More...
 
 $composed_properties = array()
 List of properties, which are composed of multiple columns. More...
 
 $user_id_table_column = null
 Column containing entity owner. More...
 
 $user_id_auth_method = null
 Auth object method name to retrieve current user ID. More...
 
 $load_state_with_properties = true
 True if state should not be loaded with properties. More...
 
 $filters = null
 Filters defined in configuration. More...
 
 $default_filters = null
 Default filters for listing. More...
 
 $additional_filters_data = null
 Additional filters data definition for listing. More...
 
 $state_select = null
 Select expression for selecting machine state. More...
 
- Protected Attributes inherited from AbstractMachine
 $smalldb = null
 Smalldb entry point More...
 
 $machine_type
 Identification of the machine. More...
 
 $state_diagram_extras = []
 List of additional diagram parts in Dot language provided by backend (and its readers). More...
 
 $state_diagram_extras_json = []
 
 $errors = []
 List of errors in state machine definition. More...
 
 $url_fmt
 URL format string where machine is located, usualy only the path part, e.g. More...
 
 $parent_url_fmt
 URL format string where parent of this machine is located, usualy only the path part, e.g. More...
 
 $post_action_url_fmt
 URL format string for redirect-after-post. More...
 
 $states
 Descriptions of all known states – key is state id, value is * description. More...
 
 $state_groups
 State groups. More...
 
 $actions
 Description of all known actions – key is action name. More...
 
 $default_access_policy = null
 Default access policy. More...
 
 $read_access_policy = null
 Read access policy. More...
 
 $listing_access_policy = null
 Listing access policy. More...
 
 $access_policies
 Access policies. More...
 
 $properties
 Description of machine properties – key is property name. More...
 
 $views
 Description of machine views – key is view name. More...
 
 $references
 Description of machine references. More...
 

Additional Inherited Members

- Static Public Member Functions inherited from AbstractMachine
static exportDotIdentifier (string $str, string $prefix='s_')
 Convert state machine state name or group name to a safe dot identifier. More...
 
- Public Attributes inherited from AbstractMachine
const RETURNS_VALUE = null
 Return value of invoked transition is just some value. More...
 
const RETURNS_NEW_ID = 'new_id'
 Return value of invoked transition is new ID of the state machine. More...
 

Member Function Documentation

◆ configureMachine()

configureMachine ( array  $config)
protected

Define state machine used by all instances of this type.

◆ setupDefaultMachine()

setupDefaultMachine ( array  $config)
protected

Setup session machine.

◆ calculateViewValue()

calculateViewValue (   $id,
  $view,
$properties_cache = null,
$view_cache = null,
$persistent_view_cache = null 
)

Resolve specific views.

Todo:
Replace this with something better.
Note
Don't modify caches. The return value will be cached in $view_cache automatically.

◆ login()

login (   $ref,
  $user,
  $password 
)
protected

Login user.

Returns
New session ID on success, null otherwise.
Note
When using Reference to log in, check returned Reference object using Reference::isNullRef().
See also
Timing attack prevention: http://blog.ircmaxell.com/2014/11/its-all-about-time.html

◆ logout()

logout (   $ref)
protected

Logout user - simply destroy session.

Member Data Documentation

◆ $table_columns

$table_columns
protected
Initial value:
= array(
'session_id' => 'id',
'session_token' => 'token',
'user_id' => 'user_id',
)

Map of table columns.

◆ $user_login_filters

$user_login_filters
protected
Initial value:
= array(
'type' => 'user',
)

User login listing.

◆ $user_login_property

$user_login_property = 'email'
protected

State machine property containing the login.

◆ $user_password_property

$user_password_property = 'password'
protected

State machine property containing the password hash.