Skip to content

Commit

Permalink
JWT is working, removed unused stuff. Implemented a simple phpunit test.
Browse files Browse the repository at this point in the history
  • Loading branch information
formidablae committed Nov 2, 2021
1 parent 98cbf37 commit 9442356
Show file tree
Hide file tree
Showing 19 changed files with 143 additions and 62 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Homestead.yaml
!.env.example

.phpunit.result.cache
.phpunit.cache/

.vscode/*
!.vscode/settings.json
Expand All @@ -16,4 +17,4 @@ private/tmp

/tmp

.DS_Store
.DS_Store
9 changes: 0 additions & 9 deletions app/Http/Controllers/AuthenticationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,6 @@
use Laravel\Lumen\Routing\Controller as BaseController;

class AuthenticationController extends BaseController {
/**
* create a new AuthenticationController instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth:api', ['except' => ['login']]);
}

/**
* login a user
*/
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/CommentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public function editComment(Request $request, $comment_id) {

$user = Auth::user();

Gate::authorize('isPremiumUser', $user); // check if user has premium subscription, thus can edit own comments
Gate::authorize('isPremiumUser'); // check if user has premium subscription, thus can edit own comments

$comment = $this->getComment($comment_id);

Expand Down
1 change: 0 additions & 1 deletion app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public function newUser(Request $request) {
$data = $request->all();
$user->fill($data);
$user->password = Hash::make($data["password"]);
$user->api_token = Str::random(64);
$user->save();
return $user;
}
Expand Down
7 changes: 5 additions & 2 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
* @var array
*/
protected $hidden = [
'password', 'updated_at', 'api_token'
'password', 'updated_at'
];

/**
Expand All @@ -50,7 +50,10 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
* obtain full name attribute
*/
public function getFullNameAttribute(): string {
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
if (isset($this->attributes['first_name']) && isset($this->attributes['last_name'])) {
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
return "";
}

/**
Expand Down
6 changes: 0 additions & 6 deletions app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,6 @@ public function boot()
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.

$this->app['auth']->viaRequest('api', function ($request) {
if ($request->header('Authorization')) {
return User::where('api_token', $request->header('Authorization'))->first();
}
});

Gate::policy(Post::class, PostPolicy::class);
Gate::policy(Comment::class, CommentPolicy::class);
Gate::policy(User::class, PremiumPolicy::class);
Expand Down
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
"scripts": {
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
],
"test": "phpunit",
"test-coverage": "phpunit --coverage-html /tmp"
}
}
7 changes: 0 additions & 7 deletions config/app.php

This file was deleted.

2 changes: 1 addition & 1 deletion config/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,4 @@
//
],

];
];
3 changes: 0 additions & 3 deletions config/jwt.php

This file was deleted.

3 changes: 1 addition & 2 deletions database/factories/UserFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ public function definition()
'first_name' => $this->faker->firstName(),
'last_name' => $this->faker->lastName(),
'email' => $this->faker->unique()->safeEmail,
'password' => Hash::make('password'),
'api_token' => Str::random(64)
'password' => Hash::make('password')
];
}
}
33 changes: 33 additions & 0 deletions database/migrations/1970_01_01_000001_init.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class Init extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
if ($this->doMigration()) {
DB::unprepared(file_get_contents(__DIR__ . '/init/up.sql'));
}
}

/**
* Reverse the migrations.
*/
public function down()
{
if ($this->doMigration()) {
DB::unprepared(file_get_contents(__DIR__ . '/init/down.sql'));
}
}

private function doMigration()
{
return App::environment(['local']);
}
}
32 changes: 32 additions & 0 deletions database/migrations/2021_11_02_105203_add_jwt_remove_api_token.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddJwtRemoveApiToken extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('api_token');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 64)->after('password');
});
}
}
2 changes: 2 additions & 0 deletions database/migrations/init/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DROP DATABASE IF EXISTS a_lumen_blog_sviluppo;
DROP DATABASE IF EXISTS a_lumen_blog_testing;
2 changes: 2 additions & 0 deletions database/migrations/init/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE DATABASE IF NOT EXISTS a_lumen_blog_sviluppo;
CREATE DATABASE IF NOT EXISTS a_lumen_blog_testing;
24 changes: 17 additions & 7 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
cacheResultFile=".phpunit.cache/test-results"
executionOrder="depends,defects"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
convertDeprecationsToExceptions="true"
verbose="true">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">./tests</directory>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>

<coverage cacheDirectory=".phpunit.cache/code-coverage"
processUncoveredFiles="true">
<include>
<directory suffix=".php">app</directory>
</include>
</coverage>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="DB_DATABASE" value="a_lumen_blog_testing"/>
</php>
</phpunit>
21 changes: 0 additions & 21 deletions tests/ExampleTest.php

This file was deleted.

26 changes: 26 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
<?php

use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
use DatabaseMigrations;

/**
* Creates the application.
*
Expand All @@ -13,4 +18,25 @@ public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}

protected function disableExceptionHandling()
{
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}

public function report(Throwable $e)
{
// no-op
}

public function render($request, Throwable $e) {
throw $e;
}
});
}

protected function setUp(): void {
parent::setUp();
$this->disableExceptionHandling();
}
}
18 changes: 18 additions & 0 deletions tests/UserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

class UserTest extends TestCase {
/**
* Test user creation
*
* @test
*/
public function newUserTest()
{
$email = '[email protected]';
$pwd = 'pass34dsifjsdiv';

$this->notSeeInDatabase('users', ['email' => $email]);
$this->post('auth/register', ['email' => $email, 'password' => $pwd])->seeStatusCode(200);
$this->seeInDatabase('users', ['email' => $email]);
}
}

0 comments on commit 9442356

Please sign in to comment.