Laravel token management
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.

README.md

Laravel token

Build Status SensioLabsInsight CodeClimat Test Coverage License Scrutinizer Code Quality

Table of Contents

Installation

{
    "require": {
        "lahaxearnaud/laravel-token": "~0.5"
    }
}

Database

    $ php artisan migrate --package="lahaxearnaud/laravel-token"

Provider

	'providers' => array(
        // ...
		'Lahaxearnaud\LaravelToken\LaravelTokenServiceProvider',
	),

Facade

	'aliases' => array(
        // ...
		'Token' => 'Lahaxearnaud\LaravelToken\LaravelTokenFacade',
	),

Usage

Create token

    $token = Token::create($userID, $allowLogin);

If $allowLogin is set to true the token can be use to authentification via route filter.

Crypt token

    $token = Token::create($userID, $allowLogin);
    $cryptToken = Token::cryptToken($token->token);

If $allowLogin is set to true the token can be use to authentification via route filter.

Validate token

If you crypt your token

    $tokenStr = Token::getTokenValueFromRequest();

    $cryptToken = Token::isValidCryptToken($token->token, $userId);

If you don't crypt your token:

    $tokenStr = Token::getTokenValueFromRequest();

    $cryptToken = Token::isValidToken($token->token, $userId);

If you use those functions the token is not burn. It can be use many times.

For one shot usage token:

    $tokenStr = Token::getTokenValueFromRequest();

    /**
      * if the token is crypt do :
      * $tokenStr = Token::uncryptToken($tokenStr);
    **/

    $tokenValid = true;
    try {
        // find the token
        $token = $token->findByToken($tokenStr, $userId);

        // test the token validity
        if (Token::isValidToken($token)) {

            // do what you need to do

            // delete the token
            Token::burn($token);
        } else {
            $tokenValid = false;
        }
    } catch (TokenNotFoundException $e) {
        $tokenValid = false;
    }

    if($tokenValid) {
        // manage errors
    }

Route filter

Simple token protection:

    Route::get('/token-protected', array('before' => 'token', function () {
        echo "I am token protected";
    }));

Authentification by token:

The token used for an authentification must be a login token, pleaserefer to the token creation section

    Route::get('/login-by-token', array('before' => 'token.auth', function () {
        echo Auth::user()->username;
    }));

In order to use the authentification by token your class User need to implements Lahaxearnaud\LaravelToken\Models\UserTokenInterface


use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Lahaxearnaud\LaravelToken\Models\UserTokenInterface;

class User extends Eloquent implements UserInterface, RemindableInterface, UserTokenInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

    public function loggableByToken()
    {
        return true;
    }
}

The method loggableByToken is called when a user try to authentificate with a token.

If an error occur on token validation a TokenExeption is throw, please go to Exceptions section.

By default you can send your token in parameter or header. The default name of the field is token but you can change it by publishing and change the configuration:

    $ php artisan config:publish lahaxearnaud/laravel-token

Then change the tokenFieldName config/packages/lahaxearnaud/laravel-token/config.php.

You can get the token instance via:

    Token::getCurrentToken();

Exceptions

If you use route filter you need to handle some Exceptions. Add the following error handler in you filter.php to catch them. This is basic example, change the behavior to fit your needs (redirect, log...).

    App::error(function(\Lahaxearnaud\LaravelToken\exeptions\TokenException $exception)
    {
        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotFoundException) {
            return \Response::make('Unauthorized (Not found)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotValidException) {
            return \Response::make('Unauthorized (Not valid token)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\UserNotLoggableByTokenException) {
            return \Response::make('Unauthorized (Not loggable by token)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\NotLoginTokenException) {
            return \Response::make('Unauthorized (Not login token)', 401);
        }
    });

Events

You can listen events:

  • Token not found
    • name: token.notFound
    • parameters:
      • the token string
  • Token not valid
    • name: token.notValid
    • parameters:
      • the token object
  • Token doesn't allow to be used for login
    • name: token.notLoginToken
    • parameters:
      • the token object
  • The user can't logged with a token
    • name: token.notLoggableUser
    • parameters:
      • the token object
      • the user object
  • Token burn
    • name: token.burned
    • parameters:
      • the token object
  • Token created
    • name: token.created
    • parameters:
      • the token object
  • Token saved
    • name: token.saved
    • parameters:
      • the token object

Commands

A new artisan command is added to your project in order to help you to clean your token table

### Delete expired tokens
    Without any option the command delete all expired tokens.
    ```bash
        $ php artisan token:clean
    ```
### Truncate the table
    If you specified ``--all`` all token will be deleted
    ```bash
        $ php artisan token:clean -all
    ```

API

Security

Crypt a string token in order to get a public token

    Token::cryptToken ($uncrypt)

Uncrypt a public token in order to get the private token

    Token::uncryptToken ($crypt)

Creation

Create a Token instance (directly saved in database)

    Token::create ($userId, $allowLogin = false, $lifetime = 3600, $length = 100)

If $allowLogin is set to true the token can be use to authentification via route filter.

Deletion

Delete the token

    Token::burn (Token $token)

Validation

Fetch the token, check id the token has the good user ID and if it is not expired

    Token::isValidToken ($token, $userId)

Same as isValidToken but uncrypt the token before trying to find him

    Token::isValidCryptToken ($token, $userId)

Only validate if the token is expired

    Token::isValid (Token $token)

Find

Find the token by ID

    Token::find ($id)

Find the token by token string

    Token::findByToken ($token, $userId)

Find all token for an user

    Token::findByUser ($idUser)

Todo

  • config to allow only one token by user and type