All Projects → lahaxearnaud → Laravel Token

lahaxearnaud / Laravel Token

Licence: mit
Laravel token management

Projects that are alternatives of or similar to Laravel Token

Spa Starter Kit
A highly opinionated starter kit for building Single Page Applications with Laravel and Vue.js
Stars: ✭ 933 (+9230%)
Mutual labels:  laravel
Localization Helpers
An artisan command package for easy translation management
Stars: ✭ 8 (-20%)
Mutual labels:  laravel
Laravelshoppingcart
Shopping Cart Implementation for Laravel Framework
Stars: ✭ 853 (+8430%)
Mutual labels:  laravel
Lighthouse Utils
An add-on to Lighthouse to auto-generate CRUD actions from types https://github.com/nuwave/lighthouse
Stars: ✭ 26 (+160%)
Mutual labels:  laravel
Laravel Relationships Data
Migrations, seeders and factories to get up and running with various relationship types data quickly
Stars: ✭ 27 (+170%)
Mutual labels:  laravel
Foocart
A Laravel 5 eCommerce application with integrated Stripe payments.
Stars: ✭ 8 (-20%)
Mutual labels:  laravel
Blade Migrations Laravel
An intelligent alternative version of Laravel 5/6 Database Migrations - uses raw-sql syntax, transactions, auto-rollback, UP-DOWN-UP testing
Stars: ✭ 25 (+150%)
Mutual labels:  laravel
React Input Tags
React component for tagging inputs.
Stars: ✭ 10 (+0%)
Mutual labels:  tokenizer
Laravel Seo Gen
SEO friendly meta tags generator for Laravel
Stars: ✭ 7 (-30%)
Mutual labels:  laravel
Dockerized lara
Build your Laravel App with Redis - Mongodb - MariaDB - Nginx - php7 - zsh
Stars: ✭ 9 (-10%)
Mutual labels:  laravel
Laravel Pwa
Laravel with Progressive Web Apps (PWA)
Stars: ✭ 26 (+160%)
Mutual labels:  laravel
Laravel Restaurant Pos
Restaurant POS
Stars: ✭ 27 (+170%)
Mutual labels:  laravel
Base
Until 2018, Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE. Backpack v4 no longer uses this package, they're now built-in - use Backpack/CRUD instead.
Stars: ✭ 848 (+8380%)
Mutual labels:  laravel
Laravel6 Frontend Boilerplate
A Vue.js Frontend starter project kit template/boilerplate with Laravel 6 Backend API support.
Stars: ✭ 26 (+160%)
Mutual labels:  laravel
Deployer
Deployer is a free and open source deployment tool.
Stars: ✭ 854 (+8440%)
Mutual labels:  laravel
Socialite Mailru
MailRu OAuth2 Provider for Laravel Socialite
Stars: ✭ 25 (+150%)
Mutual labels:  laravel
Laravel Hashids
Integrate Hashids with Laravel. Automatic model binding and id resolving included!
Stars: ✭ 8 (-20%)
Mutual labels:  laravel
Lumen Api Demo
Lumen rest api demo with Dingo/Api, JWT, CORS, PHPUNIT
Stars: ✭ 856 (+8460%)
Mutual labels:  laravel
Laravel Pay
可能是我用过的最优雅的 Alipay 和 WeChat 的 laravel 支付扩展包了
Stars: ✭ 856 (+8460%)
Mutual labels:  laravel
Laravel Mail Preview
A mail driver to quickly preview mail
Stars: ✭ 851 (+8410%)
Mutual labels:  laravel

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
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].