Optional Authentication

Unlike a situation where you require authentication, you may come across certain scenarios where you can have a user logged in, but if they are not they can still proceed. A common scenario that fits this description would be checking out on an ecommerce website. You may have a user logged in so they can take advantage of stored addresses, stored payment information, etc. At the same time you may allow guest checkout, so authentication was optional.

Community Auth has an example of this in the Examples controller. See the optional_login_test() method.

Allowing a Login Form on a Page

By default Community Auth is checking that a login attempt is coming from the login page set in authentication.php. In order to allow a login form from another page, you must add that page to the allowed_pages_for_login array in authentication.php. For instance, if you want to use the optional login test in the Examples controller, you would add “examples/optional_login_test” to the array.

$config['allowed_pages_for_login'] = [
    'examples/optional_login_test'
];

The Optional Login

In your controller, instead of using one of the methods to enforce authentication, you would verify that the user is logged in, and then add a login form if they are not:

if( $this->verify_min_level(1) )
{
	echo 'Optionally logged in</br>' . secure_anchor('examples/logout', 'Logout');
}
else if( $this->tokens->match && $this->optional_login() )
{
	// Let Community Auth handle the login attempt ...
}
else
{
	// Show your form here ...
	echo '<p>You are not logged in, but can still see this page.</p>';

	// Notice the parameter is set to TRUE, which designates this as an optional login
	$this->setup_login_form(TRUE);

	$this->load->view( 'examples/login_form' );
}

Special Case For Calling More Than One Authentication Method

Normally you will only want to call one authentication method per request, but you can see that the code above has two. This type of usage (calling more than one authentication method in the same request) is a special case, and no others are known at this time. See the following blog post for more information: How Not to Use Authentication Methods