Skip to content

Commit

Permalink
fix api token get inctive token as valid
Browse files Browse the repository at this point in the history
  • Loading branch information
metallurgical committed Mar 28, 2020
1 parent 85d4497 commit cec351a
Show file tree
Hide file tree
Showing 18 changed files with 668 additions and 28 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/vendor
composer.phar
composer.lock
.DS_Store
.DS_Store
.php_cs.cache
32 changes: 32 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

$finder = Symfony\Component\Finder\Finder::create()
->notPath('vendor')
->in(__DIR__)
->name('*.php')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);

return PhpCsFixer\Config::create()
->setRules([
'@Symfony' => true,
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sortAlgorithm' => 'length'],
'no_unused_imports' => true,
'blank_line_after_namespace' => true,
'elseif' => true,
'switch_case_space' => true,
'ternary_operator_spaces' => true,
'ternary_to_null_coalescing' => true,
'binary_operator_spaces' => ['align_double_arrow' => false],
'linebreak_after_opening_tag' => true,
'not_operator_with_successor_space' => false,
'phpdoc_order' => true,
'phpdoc_align' => ['align' => 'left'],
'concat_space'=> ['spacing' => 'one'],
'new_with_braces' => false,
'phpdoc_no_empty_return' => false,
])
->setFinder($finder);
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,5 +273,15 @@ $key = 'J1VFYTgUafp21ljEkanJYYnlY1j4REURXgAKzlwAUxABfCWPw4PBw9HKYbG4GWNvi125WUO0
$user->isKeyActive($key);
```

## Test

Run test with following command

```
vendor/bin/phpunit --testdox --verbose
```

## License
This package is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)


13 changes: 11 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "kasitaw/api-key",
"description": "User defined api key to communicate with Kasitaw using machine-to-machine concept. Mostly for external integration",
"description": "User defined api key(using custom laravel guard) to enable client communicate with server for external integration in general",
"keywords": ["kasitaw", "api-key", "api-integration", "api"],
"require": {
"php": ">=7",
Expand All @@ -9,7 +9,8 @@
"require-dev": {
"laravel/framework": "^6.0",
"phpunit/phpunit": "^9.0",
"orchestra/testbench": "^5.1"
"orchestra/testbench": "^4.0",
"friendsofphp/php-cs-fixer": "^2.16"
},
"autoload": {
"psr-4": {
Expand All @@ -28,6 +29,14 @@
]
}
},
"scripts": {
"format": [
"vendor/bin/php-cs-fixer fix"
],
"format-dry-run": [
"vendor/bin/php-cs-fixer fix --dry-run --diff"
]
},
"license": "MIT",
"authors": [
{
Expand Down
20 changes: 20 additions & 0 deletions database/factories/ApiKeyFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

use Kasitaw\ApiKey\ApiKey;
use Illuminate\Support\Str;
use Faker\Generator as Faker;
use Kasitaw\ApiKey\Tests\TestModel\User;

/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(ApiKey::class, function (Faker $faker) {
$user = factory(User::class)->create();

return [
'uuid' => Str::uuid()->toString(),
'model_type' => get_class($user),
'model_id' => $user->id,
'key' => Str::random(80),
'status' => true,
'last_access_at' => now(),
];
});
13 changes: 13 additions & 0 deletions database/factories/UserFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

use Faker\Generator as Faker;
use Kasitaw\ApiKey\Tests\TestModel\User;

/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'created_at' => now(),
'updated_at' => now(),
];
});
2 changes: 1 addition & 1 deletion database/migrations/create_api_keys_table.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class CreateApiKeysTable extends Migration
$table->morphs('model');
$table->text(config('api-key.columns.key'));
$table->boolean('status')->default(true);
$table->timestamp('last_access_at');
$table->timestamp('last_access_at')->nullable();
$table->timestamps();
$table->softDeletes();
});
Expand Down
2 changes: 0 additions & 2 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="phpunit.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
syntaxCheck="true"
verbose="true"
>
<testsuites>
Expand Down
10 changes: 9 additions & 1 deletion src/ApiKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,24 @@
use Illuminate\Support\Str;
use Kasitaw\ApiKey\Traits\HasApiKey;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ApiKey extends Model
{
use HasApiKey;
use SoftDeletes;

public $incrementing = false;

protected $guarded = [];

protected $dates = ['last_access_at'];
protected $primaryKey = 'uuid';

protected $keyType = 'string';

protected $dates = [
'last_access_at',
];

protected $casts = [
'status' => 'boolean',
Expand Down
6 changes: 2 additions & 4 deletions src/ApiKeyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public function boot(Filesystem $filesystem)
__DIR__ . '/../database/migrations/create_api_keys_table.php.stub' => $this->getMigrationFileName($filesystem),
], 'migrations');

$this->loadRoutesFrom(__DIR__ . '/../tests/TestRoute/TestRoute.php');

Auth::extend('api_key', function ($app, $name, array $config) {
// Automatically build the DI, put it as reference
$userProvider = app(UserTokenProvider::class);
Expand All @@ -39,10 +41,6 @@ public function register()

/**
* Returns existing migration file if found, else uses the current timestamp.
*
* @param Filesystem $filesystem
*
* @return string
*/
protected function getMigrationFileName(Filesystem $filesystem): string
{
Expand Down
7 changes: 3 additions & 4 deletions src/Guards/ApiGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,16 @@ public function user()
$token
);
}

if ($apiKey) {
$this->setUser($apiKey->authenticable);

$apiKey->last_access_at = Carbon::now();
$apiKey->save();

return $apiKey->authenticable;
}

return $apiKey->authenticable;
return null;
}

/**
Expand All @@ -98,8 +99,6 @@ public function getTokenForRequest()
/**
* Validate a user's credentials.
*
* @param array $credentials
*
* @return bool
*/
public function validate(array $credentials = [])
Expand Down
13 changes: 0 additions & 13 deletions src/Traits/HasApiKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ public function revokeKeyByUuid(...$uuid)
/**
* Generate new key.
*
* @param bool $status
*
* @return \Illuminate\Database\Eloquent\Model|string
*/
public function generateNewKey(bool $status = true)
Expand Down Expand Up @@ -195,8 +193,6 @@ public function isKeyActive($keyOrUuid)
/**
* Base function to set the status.
*
* @param bool $status
*
* @return $this
*/
private function setStatusToAll(bool $status = true)
Expand All @@ -211,8 +207,6 @@ private function setStatusToAll(bool $status = true)
/**
* Flatten the multi array into flat view.
*
* @param array $input
*
* @return array
*/
private function flatten(array $input)
Expand All @@ -223,10 +217,6 @@ private function flatten(array $input)
/**
* Base method to set status(active or inactive) for some keys.
*
* @param string $keyType
* @param array $keyOrUuid
* @param bool $status
*
* @return bool
*/
private function setStatusToSome(string $keyType, array $keyOrUuid, bool $status = true)
Expand All @@ -246,9 +236,6 @@ private function setStatusToSome(string $keyType, array $keyOrUuid, bool $status
/**
* Base method to delete the key.
*
* @param string $keyType
* @param array $keyOrUuid
*
* @return $this
*/
private function deleteKeys(string $keyType, array $keyOrUuid)
Expand Down
1 change: 1 addition & 0 deletions src/UserTokenProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public function retrieveByToken($identifier, $apiKey)
return $this->apiKey
->with('authenticable')
->where($identifier, $apiKey)
->where('status', true)
->first();
}

Expand Down
Loading

0 comments on commit cec351a

Please sign in to comment.