Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
quangdung93 committed Sep 8, 2021
0 parents commit e5488b2
Show file tree
Hide file tree
Showing 8 changed files with 286 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 1.0.0 - 2021-09-07

### Added
- Everything, initial release
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

## Install
```php
composer require quangdung93/jwt-redis
```

## Publish config
```php
php artisan vendor:publish --provider="Ajax\JwtRedis\JwtRedisServiceProvider"
```

## Config

`config/jwt_redis.php`

```php

//Limit the number of tokens stored in redis
'limit_token' => 5,

//The keys in the payload are used to hash session_id
'key_payload_hash' => [
'imei',
'user_id'
],

// Except route affected by middleware
'route_except' => [
'api/login'
]

```


## Use

```php
// use Ajax\JwtRedis\Facades\JwtRedis;

$imei = '123';
$user_id = '1';

$params = [$imei, $user_id];

//$params is array include key payload used to hash to session_id

// Save token to redis
JwtRedis::set($token, $params)

//Get token
JwtRedis::get($params)

//Check token exists in Redis
JwtRedis::check($token, $params)
```
29 changes: 29 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "quangdung93/jwt-redis",
"description": "This package to add JSON Web Token to Redis",
"authors": [
{
"name": "Ajax",
"email": "[email protected]"
}
],
"require": {},
"autoload": {
"psr-4": {
"Ajax\\JwtRedis\\": "src/"
}
},
"extra": {
"laravel": {
"providers": [
"Ajax\\JwtRedis\\JwtRedisServiceProvider"
],
"aliases": {
"JwtRedis": "Ajax\\JwtRedis\\Facades\\JwtRedis"
}
}
},
"homepage": "https://github.com/spatie/laravel-permission",
"minimum-stability": "dev",
"license": "MIT"
}
44 changes: 44 additions & 0 deletions config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

return [
/*
|--------------------------------------------------------------------------
| Limit Token
|--------------------------------------------------------------------------
| Limit the number of tokens stored in redis
|
*/
'limit_token' => 5,

/*
|--------------------------------------------------------------------------
| Key Hash
|--------------------------------------------------------------------------
| The keys in the payload are used to hash session_id
|
*/
'key_payload_hash' => [
'imei',
'user_id'
],

/*
|--------------------------------------------------------------------------
| Except Route
|--------------------------------------------------------------------------
| Except route affected by middleware Http\Middleware\JwtRedisMiddleware
|
*/
'route_except' => [
'api/login'
],

/*
|--------------------------------------------------------------------------
| Push Middleware To Group
|--------------------------------------------------------------------------
| Push middleware Http\Middleware\JwtRedisMiddleware to Group
|
*/
'group' => 'api',
];
13 changes: 13 additions & 0 deletions src/Facades/JwtRedis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Ajax\JwtRedis\Facades;

use Illuminate\Support\Facades\Facade;

class JwtRedis extends Facade
{
protected static function getFacadeAccessor()
{
return 'JwtRedis';
}
}
52 changes: 52 additions & 0 deletions src/JwtRedis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Ajax\JwtRedis;

use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Config;

class JwtRedis{

public function set(string $token, array $params):array
{
// encode session_id
$session_id = $this->hashKey($params);

//Push token in redis
Redis::lpush($session_id, $token);

//Limit list length in redis
Redis::ltrim($session_id, 0, config('jwt_redis.limit_token', 5));

return $this->getTokenBySessionIdFromRedis($session_id);
}

public function get(array $params):array
{
$session_id = $this->hashKey($params);
return $this->getTokenBySessionIdFromRedis($session_id);
}

public function check(string $token, array $params):bool
{
$session_id = $this->hashKey($params);
$redis = $this->getTokenBySessionIdFromRedis($session_id);

if(count($redis) > 0 && in_array($token, $redis)){
return true;
}

return false;
}

public function getTokenBySessionIdFromRedis($session_id):array
{
return Redis::lrange($session_id, 0, -1);
}

public function hashKey(array $params):string
{
return md5(implode('.', $params));
}

}
36 changes: 36 additions & 0 deletions src/JwtRedisServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Ajax\JwtRedis;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Ajax\JwtRedis\JwtRedis;
use Ajax\JwtRedis\Middleware\JwtRedisMiddleware;

class JwtRedisServiceProvider extends ServiceProvider {

public function boot()
{
$this->publishConfigFile();
$router = $this->app->make(Router::class);
$router->pushMiddlewareToGroup(config('jwt_redis.group', 'api'), JwtRedisMiddleware::class);
}

public function register()
{
//Bind Facades
$this->app->bind('JwtRedis', function($app) {
return new JwtRedis();
});
}

/**
* @return void
*/
private function publishConfigFile()
{
$this->publishes([
__DIR__.'/../config/config.php' => config_path('jwt_redis.php'),
]);
}
}
53 changes: 53 additions & 0 deletions src/Middleware/JwtRedisMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Ajax\JwtRedis\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Ajax\JwtRedis\Facades\JwtRedis;

class JwtRedisMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);

try {
foreach (config('jwt_redis.route_except') as $excluded_route) {
if ($request->path() === $excluded_route) {
return $response;
}
}

//Get token from header
$token = $request->bearerToken();
if($token){
$payload = Auth::payload();
$params = $payload->get(config('jwt_redis.key_payload_hash'));

//Check if token exists in redis
if(JwtRedis::check($token, $params)){
return $response;
}
}

return response()->json([
'error' => 'API request Invalid.',
], Response::HTTP_UNAUTHORIZED);

}catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage(),
], Response::HTTP_UNAUTHORIZED);
}

}
}

0 comments on commit e5488b2

Please sign in to comment.