Introduction
A modern and framework agnostic authorization and authentication package featuring groups, permissions, custom hashing algorithms and additional security features.
The package follows the FIG standard PSR-0 to ensure a high level of interoperability between shared PHP code.
The package requires PHP 5.3+ and comes bundled with a Laravel 4 Facade and a Service Provider to simplify the optional framework integration.
Have a read through the Installation Guide and on how to Integrate it with Laravel 4.
Quick Example
Create a user
Sentry::register(array(
'email' => 'john.doe@example.com',
'password' => 'foobar',
));
Authenticate a user
Sentry::authenticate(array(
'email' => 'john.doe@example.com',
'password' => 'foobar',
));
Create a group
Sentry::createGroup(array(
'name' => 'Subscribers',
'permissions' => array(
'admin' => 1,
'users' => 1,
),
));
Installation
The best and easiest way to install Sentry is with Composer.
Preparation
Open your composer.json
file and add the following to the require
array:
"cartalyst/sentry": "2.1.*"
Note: Make sure that after the required changes your
composer.json
file is valid by runningcomposer validate
.
Install the dependencies
Run Composer to install or update the new requirement.
php composer install
or
php composer update
Now you are able to require the vendor/autoload.php
file to autoload the package.
Integration
Note: The database schema is located under
vendor/cartalyst/sentry/schema/mysql.sql
Laravel 4
After you have installed the package, just follow the instructions.
Sentry has optional support for Laravel 4 and it comes bundled with a Service Provider and a Facade for easy integration.
After installing the package, open your Laravel config file app/config/app.php
and add the following lines.
In the $providers
array add the following service provider for this package.
'Cartalyst\Sentry\SentryServiceProvider',
In the $aliases
array add the following facade for this package.
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
Migrations
php artisan migrate --package=cartalyst/sentry
Configuration
After installing, you can publish the package configuration file into your application by running the following command:
php artisan config:publish cartalyst/sentry
This will publish the config file to app/config/packages/cartalyst/sentry/config.php
where you can modify the package configuration.
CodeIgniter 3.0-dev
After you have installed the package, just follow the instructions.
Visit application/config/config.php
and right down the bottom, add the following:
class_alias('Cartalyst\Sentry\Facades\CI\Sentry', 'Sentry');
This will allow you to use Sentry as normal in CodeIgniter and sets up dependencies required for Sentry to run smoothly within the CI environment.
Note:: You must be running your database using the
PDO
driver (though this would be recommended anyway). Configuration for a MySQL database running PDO could be as follows (inapplication/config/database.php
):
// Ensure the active group is the default config.
// Sentry always runs off your application's default
// database connection.
$active_group = 'default';
// Setup the default config
$db['default'] = array(
// PDO requires the host, dbname and charset are all specified in the "dsn",
// so we'll go ahead and do these now.
'dsn' => 'mysql:host=localhost;dbname=cartalyst_sentry;charset=utf8;',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => '',
'dbdriver' => 'pdo',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
FuelPHP 1.x
After you have installed the package, just follow the instructions.
You must put the following in app/bootstrap.php
below Autoloader::register()
:
// Enable composer based autoloading
require APPPATH.'vendor/autoload.php';
Great! You now have composer working with FuelPHP.
Just one more step is involved now, right at the bottom of that same file, app/bootstrap.php
, put the following:
class_alias('Cartalyst\Sentry\Facades\FuelPHP\Sentry', 'Sentry');
This will mean you can use the FuelPHP Sentry facade as the class Sentry
. VĂ²ila! Sentry automatically works with your current database configuration, there is no further setup required.
Note:: Sentry will always run off the default database connection, so ensure this is working. We may look at adding support for alternate connections in the future however it is not implemented at this stage. Pull requests are welcome.
Native
// Include the composer autoload file
include_once "vendor/autoload.php";
// Import the necessary classes
use Illuminate\Database\Capsule\Manager as Capsule;
// Create the Sentry alias
class_alias('Cartalyst\Sentry\Facades\Native\Sentry', 'Sentry');
// Create a new Database connection
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
]);
$capsule->bootEloquent();
The integration is done and you can now use all the available methods, here's an example:
// Find a user using the user email address
$user = Sentry::findUserByLogin('john.doe@example.com');
Usage
Authentication
In this section, we will cover authentication and login.
Sentry::authenticate()
Authenticates a user based on the provided credentials.
If the authentication was successful, password reset fields and any invalid authentication attempts will be cleared.
Param | Required | Default | Type | Description |
---|---|---|---|---|
$credentials | true | null | array | Array that should contain the user credentials like email and password . |
$remember | false | false | bool | Flag to wether Sentry should remember the user. It sets a Cookie. |
Example
try
{
// Login credentials
$credentials = array(
'email' => 'john.doe@example.com',
'password' => 'password',
);
// Authenticate the user
$user = Sentry::authenticate($credentials, false);
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
{
echo 'Password field is required.';
}
catch (Cartalyst\Sentry\Users\WrongPasswordException $e)
{
echo 'Wrong password, try again.';
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User is not activated.';
}
// The following is only required if the throttling is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
echo 'User is suspended.';
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
echo 'User is banned.';
}
Exceptions
In this section, we provide a list of all exceptions that are thrown by Sentry.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\LoginRequiredException | When you don't provide the required login field, this exception will be thrown. |
Cartalyst\Sentry\Users\PasswordRequiredException | When you don't provide the password field, this exception will be thrown. |
Cartalyst\Sentry\Users\UserNotActivatedException | When the provided user is not activated, this exception will be thrown. |
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Cartalyst\Sentry\Users\WrongPasswordException | When the provided password is incorrect, this exception will be thrown. |
Cartalyst\Sentry\Throttling\UserSuspendedException | When the provided user is suspended, this exception will be thrown. |
Cartalyst\Sentry\Throttling\UserBannedException | When the provided user is banned, this exception will be thrown. |
Sentry::authenticateAndRemember()
Authenticates and Remembers a user based on credentials. This is an helper function for the authenticate()
which sets the $remember
flag to true so the user is remembered (using a cookie). This is the "remember me" you are used to see on web sites.
Example
Sentry::authenticateAndRemember($credentials);
Sentry::login()
Logs in the provided user and sets properties in the session.
If the login is successful, password reset fields and any invalid authentication attempts will be cleared.
Param | Required | Default | Type | Description |
---|---|---|---|---|
$user | true | null | object | A user object Cartalyst\Sentry\Users\UserInterface . |
$remember | false | false | bool | Flag to wether Sentry should remember the user. It sets a Cookie. |
Example
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Log the user in
Sentry::login($user, false);
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User not found.';
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User not activated.';
}
// Following is only needed if throttle is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
echo "User is suspended for [$time] minutes.";
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
echo 'User is banned.';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\LoginRequiredException | When you don't provide the required login field, this exception will be thrown. |
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Cartalyst\Sentry\Users\UserNotActivatedException | When the provided user is not activated, this exception will be thrown. |
Cartalyst\Sentry\Throttling\UserSuspendedException | When the provided user is suspended, this exception will be thrown. |
Cartalyst\Sentry\Throttling\UserBannedException | When the provided user is banned, this exception will be thrown. |
Sentry::loginAndRemember()
Logs in and Remembers a user based on credentials. This is an helper function for the login()
which sets the $remember
flag to true so the user is remembered (using a cookie). This is the "remember me" you are used to see on web sites.
Example
Sentry::loginAndRemember($user);
Sentry::logout()
The logout method logs the user out and destroys all Sentry sessions / cookies for the user.
This method does not fail or throw any Exceptions if there is no user logged in.
Example
Sentry::logout();
Sentry::check()
The check method returns a bool
of whether the user is logged in or not, or if the user is not activated.
If it's logged in, the current User is set in Sentry so you can easily access it via getUser()
.
A user must be activated to pass check()
.
Example
if ( ! Sentry::check())
{
// User is not logged in, or is not activated
}
else
{
// User is logged in
}
Permissions
In this section we will cover how Sentry 2 permissions work and how the user
permission inheritance behaves.
Please be aware that Sentry 2 permissions works practically the same way as in
Sentry 1.
That said, here are the values that your groups and users permissions can have:
Groups Permissions
0 : Deny
1 : Allow
Users Permissions
-1 : Deny
1 : Allow
0 : Inherit
Permission Inheritance
Just as permissions are defined for groups and individual users, the permission
inheritance model depends on a user's group.
An Administrator can assign different permissions to a user than is assigned to a group:
- If a user is not assigned a permission, or if the user is assigned a permission of 0 then the user will inherit permissions from the group
- If a user is assigned a permission of -1 or 1, then the user's permission will override the group permission
Note: Permission Inheritance only works for users permissions, an example
is provided on this page to help you
better understand how this exactly works.
Administrator Group
Let's say you want to have two groups, an Administrator group and a Moderator
group, for each group you can define their own permissions:
{
"name" : "Administrator",
"permissions" : {
"user.create" : 1,
"user.delete" : 1,
"user.view" : 1,
"user.update" : 1
}
}
Moderator Group
{
"name" : "Moderator",
"permissions" : {
"user.create" : 0,
"user.delete" : 0,
"user.view" : 1,
"user.update" : 1
}
}
And you have these three users, one as an Administrator, one as a Moderator
and the last one has the Administrator and Moderator groups assigned.
User - John Rambo
{
"id" : 1,
"first_name" : "John",
"last_name" : "Rambo",
"groups" : ["administrator"],
"permissions" : null
}
Actions he can execute
This user has access to everything and can execute every action on your application.
User - Rocky Balboa
{
"id" : 2,
"first_name" : "Rocky",
"last_name" : "Balboa",
"groups" : ["moderator"],
"permissions" : {
"user.update" : 0
}
}
Actions he can execute
View and Update users
Actions he cannot execute
Create or Delete users
Note: We are using
Permission Inheritance
here, hence theuser.update : 0
which means whatever you define on your group permission
this user permission will inherit that permission, which means that in this
case the user is allowed to update users.
User - Bruce Wayne
{
"id" : 3,
"first_name" : "Bruce",
"last_name" : "Wayne",
"groups" : ["administrator", "moderator"],
"permissions" : {
"user.delete" : -1,
"user.create" : 1
}
}
Actions he can execute
Create, Update and View users
Actions he cannot execute
Delete users
Since this is a special user, mainly because this user has two assigned groups,
there are some things that you should know when assigning multiple groups to
an user.
When a user has two or more groups assigned, if those groups have the same
permissions but different permission access's are assigned,
once one of those group permissions are denied, the user will be denied access
to that permission no matter what the other groups has as a permission value.
Which means for you to allow
a permission to this specific user, you need to
change the user permissions.
In this specific case, we allowed the user to create a new user by changing the
user.create : 1
permission.
Notice that we are denying the user.delete
permission of this user, in this
example, you don't need to do this, but let's say that in your group you are
allowing your users to delete other users, but for this specific user you don't
want him to be able to do that? To achieve this you deny
this user permission
directly on the user, so no matter what your group permission looks like, this
user will never be able to delete other users.
Groups
Create a group
Creating new Groups is very easy and in this section you will learn how to create one.
Param | Required | Default | Type | Description |
---|---|---|---|---|
$attributes | true | null | array | The group attributes. |
Below we'll list all the valid keys
that you can pass through the $attributes
.
Key | Required | Type | Description |
---|---|---|---|
name | true | string | The name of the group. |
permissions | false | array | The group permissions, pass a key /value pair. |
Example
try
{
// Create the group
$group = Sentry::createGroup(array(
'name' => 'Moderator',
'permissions' => array(
'admin' => 1,
'users' => 1,
),
));
}
catch (Cartalyst\Sentry\Groups\NameRequiredException $e)
{
echo 'Name field is required';
}
catch (Cartalyst\Sentry\Groups\GroupExistsException $e)
{
echo 'Group already exists';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Groups\NameRequiredException | If you don't provide the group name, this exception will be thrown. |
Cartalyst\Sentry\Groups\GroupExistsException | This exception will be thrown when the group you are trying to create already exists on your database. |
Update a group
Example
try
{
// Find the group using the group id
$group = Sentry::findGroupById(1);
// Update the group details
$group->name = 'Users';
$group->permissions = array(
'admin' => 1,
'users' => 1,
);
// Update the group
if ($group->save())
{
// Group information was updated
}
else
{
// Group information was not updated
}
}
catch (Cartalyst\Sentry\Groups\NameRequiredException $e)
{
echo 'Name field is required';
}
catch (Cartalyst\Sentry\Groups\GroupExistsException $e)
{
echo 'Group already exists.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Groups\NameRequiredException | If you don't provide the group name, this exception will be thrown. |
Cartalyst\Sentry\Groups\GroupExistsException | This exception will be thrown when the group you are trying to create already exists on your database. |
Cartalyst\Sentry\Groups\GroupNotFoundException | If the provided group was not found, this exception will be thrown. |
Delete a Group
Example
try
{
// Find the group using the group id
$group = Sentry::findGroupById(1);
// Delete the group
$group->delete();
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Groups\GroupNotFoundException | If the provided group was not found, this exception will be thrown. |
Finding Groups
Sentry provides simple methods to find you your groups.
Find all the Groups
This will return all the groups.
$groups = Sentry::findAllGroups();
Find a group by its ID
Find a group by it's ID.
try
{
$group = Sentry::findGroupById(1);
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Find a Group by it's Name
Find a group by it's name.
try
{
$group = Sentry::findGroupByName('admin');
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Groups\GroupNotFoundException | If the provided group was not found, this exception will be thrown. |
Helpers
getPermissions()
Returns the permissions of a group.
try
{
// Find the group using the group id
$group = Sentry::findGroupById(1);
// Get the group permissions
$groupPermissions = $group->getPermissions();
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group does not exist.';
}
Users
In this section we'll cover how you can create or register users, assign groups and permissions to users.
Sentry::createUser()
To create a new user you need to pass an array()
of user fields into the create()
method, please note, that the login
field and the password are required, all the other fields are optional.
Param | Required | Default | Type | Description |
---|---|---|---|---|
$credentials | true | null | array | The user credentials and attributes. |
Examples
Create a User and assign this new user an existing group.
try
{
// Create the user
$user = Sentry::createUser(array(
'email' => 'john.doe@example.com',
'password' => 'test',
'activated' => true,
));
// Find the group using the group id
$adminGroup = Sentry::findGroupById(1);
// Assign the group to the user
$user->addGroup($adminGroup);
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
{
echo 'Password field is required.';
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
echo 'User with this login already exists.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Create a new user and set permissions on this user.
This example does pretty much the same as the previous one with the exception that we are not assigning him any group, but we are granting this user some permissions.
try
{
// Create the user
$user = Sentry::createUser(array(
'email' => 'john.doe@example.com',
'password' => 'test',
'activated' => true,
'permissions' => array(
'user.create' => -1,
'user.delete' => -1,
'user.view' => 1,
'user.update' => 1,
),
));
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
{
echo 'Password field is required.'
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
echo 'User with this login already exists.';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\LoginRequiredException | When you don't provide the required login field, this exception will be thrown. |
Cartalyst\Sentry\Users\PasswordRequiredException | When you don't provide the password field, this exception will be thrown. |
Cartalyst\Sentry\Users\UserExistsException | This exception will be thrown when the user you are trying to create already exists on your database. |
Cartalyst\Sentry\Groups\GroupNotFoundException | This exception will be thrown when the group that's being assigned to the user doesn't exist. |
Sentry::register()
Registering a user will require the user to be manually activated but you can bypass this passing a boolean of true
as a second parameter.
If the user already exists but is not activated, it will create a new activation code.
Param | Required | Default | Type | Description |
---|---|---|---|---|
$credentials | true | null | array | The user credentials and attributes. |
$activate | false | false | boolean | Flag to wether activate the user or not. |
Example
try
{
// Let's register a user.
$user = Sentry::register(array(
'email' => 'john.doe@example.com',
'password' => 'test',
));
// Let's get the activation code
$activationCode = $user->getActivationCode();
// Send activation code to the user so he can activate the account
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
{
echo 'Password field is required.';
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
echo 'User with this login already exists.';
}
Exceptions
Below is a list of exceptions that this method can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\LoginRequiredException | When you don't provide the required login field, this exception will be thrown. |
Cartalyst\Sentry\Users\PasswordRequiredException | When you don't provide the required password field, this exception will be thrown. |
Cartalyst\Sentry\Users\UserExistsException | This exception will be thrown when the user you are trying to create already exists on your database. |
Update a User
Updating users information is very easy with Sentry, you just need to find the user you want to update and update their information. You can add or remove groups from users as well.
Examples
In this example we are just updating the user information.
Note: If you provide another email address, and that email address is already registered in your system, the following Exception
Cartalyst\Sentry\Users\UserExistsException
will be thrown.
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Update the user details
$user->email = 'john.doe@example.com';
$user->first_name = 'John';
// Update the user
if ($user->save())
{
// User information was updated
}
else
{
// User information was not updated
}
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
echo 'User with this login already exists.';
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Assign a new Group to a User
In this example we are assigning the provided Group to the provided User.
Note: If the provided Group is not found an Exception
Cartalyst\Sentry\Groups\GroupNotFoundException
will be thrown.
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Find the group using the group id
$adminGroup = Sentry::findGroupById(1);
// Assign the group to the user
if ($user->addGroup($adminGroup))
{
// Group assigned successfully
}
else
{
// Group was not assigned
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Remove a Group from the User
In this example we are removing the provided Group from the provided User.
Note: If the provided Group is not found an Exception
Cartalyst\Sentry\Groups\GroupNotFoundException
will be thrown.
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Find the group using the group id
$adminGroup = Sentry::findGroupById(1);
// Assign the group to the user
if ($user->removeGroup($adminGroup))
{
// Group removed successfully
}
else
{
// Group was not removed
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Update the User details and assign a new Group
This is a combination of the previous examples, where we are updating the user information and assigning a new Group the provided User.
Note: If the provided Group is not found an Exception
Cartalyst\Sentry\Groups\GroupNotFoundException
will be thrown.
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Find the group using the group id
$adminGroup = Sentry::findGroupById(1);
// Assign the group to the user
if ($user->addGroup($adminGroup))
{
// Group assigned successfully
}
else
{
// Group was not assigned
}
// Update the user details
$user->email = 'john.doe@example.com';
$user->first_name = 'John';
// Update the user
if ($user->save())
{
// User information was updated
}
else
{
// User information was not updated
}
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
echo 'User with this login already exists.';
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\LoginRequiredException | When you don't provide the required login field, this exception will be thrown. |
Cartalyst\Sentry\Users\UserExistsException | This exception will be thrown when the user you are trying to create already exists in your database. |
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Cartalyst\Sentry\Groups\GroupNotFoundException | This exception will be thrown when the group that's being assigned to the user doesn't exist. |
Delete a user
Deleting users is very simple and easy.
Example
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Delete the user
$user->delete();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Activating a User
User activation is very easy with Sentry, you need to first find the user you want to activate, then use the attemptActivation()
method and provide the activation code, if the activation passes it will return true
otherwise, it will return false
.
Note: If the user you are trying to activate, is already activated, the following Exception
Cartalyst\Sentry\Users\UserAlreadyActivatedException
will be thrown.
Example
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Attempt to activate the user
if ($user->attemptActivation('8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb'))
{
// User activation passed
}
else
{
// User activation failed
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Users\UserAlreadyActivatedException $e)
{
echo 'User is already activated.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\UserAlreadyActivatedException | If the provided user is already activated, this exception will be thrown. |
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Reset a User Password
In this section you will learn how easy it is to reset a user password with Sentry 2.
Step 1
The first step is to get a password reset code, to do this we use the
getResetPasswordCode()
method.
Example
try
{
// Find the user using the user email address
$user = Sentry::findUserByLogin('john.doe@example.com');
// Get the password reset code
$resetCode = $user->getResetPasswordCode();
// Now you can send this code to your user via email for example.
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Step 2
After your user received the password reset code you need to provide a way for them to validate that code, and reset their password.
All the logic part on how you pass the reset password code is all up to you.
Example
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
// Check if the reset password code is valid
if ($user->checkResetPasswordCode('8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb'))
{
// Attempt to reset the user password
if ($user->attemptResetPassword('8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb', 'new_password'))
{
// Password reset passed
}
else
{
// Password reset failed
}
}
else
{
// The provided password reset code is Invalid
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Finding Users
Finding users can sometimes be difficult and harsh, well, Sentry provides you simple methods to find your users.
Get the Current Logged in User
Returns the user that's set with Sentry, does not check if a user is logged in or not. To do that, use check()
instead.
try
{
// Get the current active/logged in user
$user = Sentry::getUser();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
// User wasn't found, should only happen if the user was deleted
// when they were already logged in or had a "remember me" cookie set
// and they were deleted.
}
Find all the Users
This will return all the users.
$users = Sentry::findAllUsers();
Find all the Users with access to a permissions(s)
Finds all users with access to a permission(s).
// Feel free to pass a string for just one permission instead
$users = Sentry::findAllUsersWithAccess(array('admin', 'other'));
Find all the Users in a Group
Finds all users assigned to a group.
$group = Sentry::findGroupByName('admin');
$users = Sentry::findAllUsersInGroup($group);
Find a User by their Credentials
Find a user by an array of credentials, which must include the login column. Hashed fields will be hashed and checked against their value in the database.
try
{
$user = Sentry::findUserByCredentials(array(
'email' => 'john.doe@example.com',
'password' => 'test',
'first_name' => 'John',
));
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Find a User by their Id
Find a user by their ID.
try
{
$user = Sentry::findUserById(1);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Find a User by their Login Id
Find a user by their login ID.
try
{
$user = Sentry::findUserByLogin('john.doe@example.com');
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Find a User by their Activation Code
Find a user by their registration activation code.
try
{
$user = Sentry::findUserByActivationCode('8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb');
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Find a User by their Reset Password Code
Find a user by their reset password code.
try
{
$user = Sentry::findUserByResetPasswordCode('8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb');
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Helpers
checkPassword()
Checks if the provided password matches the user's current password.
try
{
// Find the user using the user id
$user = Sentry::findUserById(1);
if($user->checkPassword('mypassword'))
{
echo 'Password matches.';
}
else
{
echo 'Password does not match.';
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
getGroups()
Returns the user groups.
try
{
// Find the user using the user id
$user = Sentry::findUserByID(1);
// Get the user groups
$groups = $user->getGroups();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
getPermissions()
Returns the user permissions.
try
{
// Find the user using the user id
$user = Sentry::findUserByID(1);
// Get the user permissions
$permissions = $user->getPermissions();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
getMergedPermissions()
Returns an array of merged permissions from groups and the user permissions.
try
{
// Find the user using the user id
$user = Sentry::getUserProvider()->findById(1);
// Get the user permissions
$permissions = $user->getMergedPermissions();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
hasAccess($permission)
Checks to see if a user been granted a certain permission. This includes any
permissions given to them by groups they may be apart of as well. Users may
also have permissions with a value of '-1'. This value is used to deny users of
permissions that may have been assigned to them from a group.
Any user with superuser
permissions automatically has access to everything,
regardless of the user permissions and group permissions.
try
{
// Find the user using the user id
$user = Sentry::findUserByID(1);
// Check if the user has the 'admin' permission. Also,
// multiple permissions may be used by passing an array
if ($user->hasAccess('admin'))
{
// User has access to the given permission
}
else
{
// User does not have access to the given permission
}
}
catch (Cartalyst\Sentry\UserNotFoundException $e)
{
echo 'User was not found.';
}
hasAnyAccess($permissions)
This method calls the hasAccess()
method, and it is used to check if an user
has access to any of the provided permissions.
If one of the provided permissions is found it will return true
even though the
user may not have access to the other provided permissions.
try
{
// Find the user using the user id
$user = Sentry::getUserProvider()->findById(1);
// Check if the user has the 'admin' and 'foo' permission.
if ($user->hasAnyAccess(array('admin', 'foo')))
{
// User has access to one of the given permissions
}
else
{
// User does not have access to any of the given permissions
}
}
catch (Cartalyst\Sentry\UserNotFoundException $e)
{
echo 'User was not found.';
}
isActivated()
Checks if a user is activated.
try
{
// Find the user
$user = Sentry::findUserByLogin('jonh.doe@example.com');
// Check if the user is activated or not
if ($user->isActivated())
{
// User is Activated
}
else
{
// User is Not Activated
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
isSuperUser()
Returns if the user is a super user, it means, that has access to everything regardless of permissions.
try
{
// Find the user
$user = Sentry::findUserByLogin('jonh.doe@example.com');
// Check if this user is a super user
if ($user->isSuperUser())
{
// User is a super user
}
else
{
// User is not a super user
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
inGroup($group)
Checks if a user is in a certain group.
try
{
// Find the user using the user id
$user = Sentry::findUserByID(1);
// Find the Administrator group
$admin = Sentry::findGroupByName('Administrator');
// Check if the user is in the administrator group
if ($user->inGroup($admin))
{
// User is in Administrator group
}
else
{
// User is not in Administrator group
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e)
{
echo 'Group was not found.';
}
Throttle
Disable the Throttling Feature
Disables the throttling feature.
Can be done on the throttle provider (global) level or on a throttle instance itself.
Example
// Get the Throttle Provider
$throttleProvider = Sentry::getThrottleProvider();
// Disable the Throttling Feature
$throttleProvider->disable();
Enable the Throttling Feature
Enables the throttling feature.
Can be done on the throttle provider (global) level or on a throttle instance itself.
Example
// Get the Throttle Provider
$throttleProvider = Sentry::getThrottleProvider();
// Enable the Throttling Feature
$throttleProvider->enable();
Check the Throttling Feature Status
Checks to see if the throttling feature is enabled or disabled.
Example
// Get the Throttle Provider
$provider = Sentry::getThrottleProvider();
// Check if the Throttling feature is enabled or disabled
if($provider->isEnabled())
{
// The Throttling Feature is Enabled
}
else
{
// The Throttling Feature is Disabled
}
User Throttling
Ban user(s)
Bans the user associated with the throttle.
try
{
// Find the user using the user id
$throttle = Sentry::findThrottlerByUserId(1);
// Ban the user
$throttle->ban();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Unban user(s)
Unbans the user associated with the throttle.
try
{
// Find the user using the user id
$throttle = Sentry::findThrottlerByUserId(1);
// Unban the user
$throttle->unBan();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Check if a User is Banned
Checks to see if the user is banned.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
if($banned = $throttle->isBanned())
{
// User is Banned
}
else
{
// User is not Banned
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Suspend user(s)
Suspends a user temporarily. Length of the suspension is set by the driver or setSuspensionTime($minutes).
try
{
// Find the user using the user id
$throttle = Sentry::findThrottlerByUserId(1);
// Suspend the user
$throttle->suspend();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Unsuspend user(s)
Unsuspends a login. This also clears all previous attempts by the specified login if they were suspended.
try
{
// Find the user using the user id
$throttle = Sentry::findThrottlerByUserId(1);
// Unsuspend the user
$throttle->unsuspend();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Check if a User is Suspended
Checks to see if the user is suspended.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
if($suspended = $throttle->isSuspended())
{
// User is Suspended
}
else
{
// User is not Suspended
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Set the User Suspension Time
Sets the length of the suspension.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$throttle->setSuspensionTime(10);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Get the User Suspension Time
Retrieves the length of the suspension time set by the throttling driver.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$suspensionTime = $throttle->getSuspensionTime();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Add a Login Attempt
Adds an attempt to the throttle object.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$throttle->addLoginAttempt();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Get Login Attempts
Retrieves the number of attempts a user currently has tried. Checks suspension time to see if login attempts can be reset. This may happen if the suspension time was (for example) 10 minutes however the last login was 15 minutes ago, attempts will be reset to 0.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$attempts = $throttle->getLoginAttempts();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Clear Login Attempts
Clears all login attempts, it also unsuspends them. This does not unban a login.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$throttle->clearLoginAttempts();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Check the User Throttle Status
Checks the login throttle status and throws a number of Exceptions upon failure.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
if ($throttle->check())
{
echo 'Good to go.';
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
echo "User is suspended for [$time] minutes.";
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
ehco 'User is banned.';
}
Set Attempt Limit
Sets the number of attempts allowed before suspension.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$throttle->setAttemptLimit(3);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Get Attempt Limit
Retrieves the number of attempts allowed by the throttle object.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
$attemptLimit = $throttle->getAttemptLimit();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Throttle\UserNotFoundException | If the provided user was not found, this exception will be thrown. |
Cartalyst\Sentry\Throttling\UserSuspendedException | When the provided user is suspended, this exception will be thrown. |
Cartalyst\Sentry\Users\UserBannedException | When the provided user is banned, this exception will be thrown. |
Find User(s)
Find a User by their Id
Retrieves a throttle object based on the user ID provided. Will always retrieve a throttle object.
try
{
$throttle = Sentry::findThrottlerByUserId(1);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Find a User by their Login
Retrieves a throttle object based on the user login provided. Will always retrieve a throttle object.
try
{
$throttle = Sentry::findThrottlerByUserLogin('john.doe@example.com');
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
Exceptions
Below is a list of exceptions that the methods can throw.
Exception | Description |
---|---|
Cartalyst\Sentry\Users\UserNotFoundException | If the provided user was not found, this exception will be thrown. |