Skip to content

Commit

Permalink
WIP JWT Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
bjuraszewski committed Sep 13, 2021
1 parent 6b9094e commit dfc6a22
Show file tree
Hide file tree
Showing 17 changed files with 724 additions and 816 deletions.
3 changes: 1 addition & 2 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Kernel extends HttpKernel
protected $middlewareGroups = [
'api' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\UnauthenticatedUser::class,
\App\Http\Middleware\Authenticate::class,
],
];

Expand Down Expand Up @@ -60,7 +60,6 @@ class Kernel extends HttpKernel
protected $middlewarePriority = [
\Fruitcake\Cors\HandleCors::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\UnauthenticatedUser::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Auth\Middleware\Authorize::class,
\App\Http\Middleware\SecureHeaders::class,
Expand Down
56 changes: 43 additions & 13 deletions app/Http/Middleware/Authenticate.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,63 @@

namespace App\Http\Middleware;

use App\Enums\RoleType;
use App\Models\Role;
use App\Models\User;
use App\Models\App;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\Manager;
use Tymon\JWTAuth\Payload;

class Authenticate extends Middleware
{
/**
* @throws AuthenticationException
*/
public function handle($request, Closure $next, ...$guards): mixed
{
if (
$request->hasHeader('x-app-id') &&
$request->hasHeader('x-app-key') &&
$this->authenticateApp($request->header('x-app-id'), $request->header('x-app-key'))
) {
return $next($request);
if (!Auth::check()) {
if ($request->hasHeader('Authorization')) {
Config::set('auth.providers.users.model', App::class);
Auth::forgetGuards();

if (!Auth::check()) {
throw new AuthenticationException();
}
} else {
$user = User::make([
'name' => 'Unauthenticated',
]);

$roles = Role::where('type', RoleType::UNAUTHENTICATED)->get();
$user->setRelation('roles', $roles);
$user->id = 'null';

Auth::claims(['typ' => 'access'])->login($user);
}
}

return parent::handle($request, $next, ...$guards);
}
if (Auth::payload()->get('typ') !== 'access') {
throw new AuthenticationException();
}

protected function authenticateApp(string $id, string $key): bool
{
$app = App::findOrFail($id);
//// Token service
//
// $token = Auth::getToken();
//
// $jwt = new JWT(app(Manager::class), new Parser(new Request()));
// $jwt->setToken($token);
//
// dd($jwt->payload());

return $app && Hash::check($key, $app->key);
return $next($request);
}

/**
Expand Down
47 changes: 0 additions & 47 deletions app/Http/Middleware/UnauthenticatedUser.php

This file was deleted.

24 changes: 22 additions & 2 deletions app/Models/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,38 @@

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
* @mixin IdeHelperApp
*/
class App extends Model
class App extends Model implements
AuthorizableContract,
AuthenticatableContract,
JWTSubject
{
use HasFactory;
use HasFactory,
Authorizable,
Authenticatable;

protected $fillable = [
'name',
'key',
'url',
];

public function getJWTIdentifier(): string
{
return $this->getKey();
}

public function getJWTCustomClaims(): array
{
return [];
}
}
18 changes: 14 additions & 4 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use OwenIt\Auditing\Auditable;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
* @OA\Schema ()
Expand All @@ -30,10 +30,10 @@ class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract,
AuditableContract
AuditableContract,
JWTSubject
{
use HasApiTokens,
Notifiable,
use Notifiable,
Authenticatable,
Authorizable,
CanResetPassword,
Expand Down Expand Up @@ -108,4 +108,14 @@ public function getAvatarAttribute(): string
{
return '//www.gravatar.com/avatar/' . md5(strtolower(trim($this->email))) . '?d=mp&s=50x50';
}

public function getJWTIdentifier(): string
{
return $this->getKey();
}

public function getJWTCustomClaims(): array
{
return [];
}
}
4 changes: 0 additions & 4 deletions app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ public function boot(): void
{
$this->registerPolicies();

Passport::routes();
Passport::ignoreMigrations();
Passport::personalAccessTokensExpireIn(now()->addDays(25));

Password::defaults(function () {
return Password::min(10)
->letters()
Expand Down
29 changes: 17 additions & 12 deletions app/Services/AuthService.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Services;

use App\Exceptions\AuthException;
use App\Models\App;
use App\Models\User;
use App\Notifications\ResetPassword;
use App\Services\Contracts\AuthServiceContract;
Expand All @@ -11,27 +12,31 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Laravel\Passport\Passport;
use Laravel\Passport\PersonalAccessTokenResult;

class AuthService implements AuthServiceContract
{
public function login(string $email, string $password, ?string $ip, ?string $userAgent): PersonalAccessTokenResult
public function login(string $email, string $password, ?string $ip, ?string $userAgent)
{
if (!Auth::guard('web')->attempt([
$token = Auth::claims(['typ' => 'identity'])->attempt([
'email' => $email,
'password' => $password,
])) {
]);

if ($token === null) {
throw new AuthException('Invalid credentials');
}

$user = Auth::guard('web')->user();
$token = $user->createToken('Admin');

$token->token->update([
'ip' => $ip,
'user_agent' => $userAgent,
]);
// $user = Auth::guard('web')->user();
// $token = $user->createToken('Admin');
//
// $token->token->update([
// 'ip' => $ip,
// 'user_agent' => $userAgent,
// ]);

// $user = App::factory()->create();
//
// $token = auth()->login($user);

return $token;
}
Expand Down
2 changes: 1 addition & 1 deletion app/Services/Contracts/AuthServiceContract.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

interface AuthServiceContract
{
public function login(string $email, string $password, ?string $ip, ?string $userAgent): PersonalAccessTokenResult;
public function login(string $email, string $password, ?string $ip, ?string $userAgent);

public function logout(User $user): void;

Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.3",
"heseya/laravel-searchable": "^1.0",
"heseya/demo": "dev-master",
"heseya/laravel-searchable": "^1.0",
"heseya/resource": "*",
"jenssegers/agent": "^2.6",
"laravel/framework": "^8.44",
"laravel/passport": "^10.1",
"league/html-to-markdown": "^5.0",
"league/omnipay": "^3.1",
"omnipay/common": "^3",
Expand All @@ -28,7 +27,8 @@
"propaganistas/laravel-phone": "^4.3",
"sentry/sentry-laravel": "^2.6",
"spatie/laravel-permission": "^4.2",
"srmklive/paypal": "^3.0"
"srmklive/paypal": "^3.0",
"tymon/jwt-auth": "^1.0.2"
},
"require-dev": {
"brianium/paratest": "^6.3",
Expand Down
Loading

0 comments on commit dfc6a22

Please sign in to comment.