Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add API Key support (🚧) #350

Open
wants to merge 2 commits into
base: v1.0.0-alpha
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions backend/app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace HiEvents\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Laravel\Sanctum\Exceptions\MissingAbilityException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Throwable;

Expand Down Expand Up @@ -52,6 +53,10 @@ public function render($request, Throwable $exception)
return response()->json([
'message' => $exception->getMessage() ?: 'Resource not found',
], 404);
} else if ($exception instanceof MissingAbilityException) {
return response()->json([
'message' => $exception->getMessage(),
], 403);
}

return parent::render($request, $exception);
Expand Down
31 changes: 31 additions & 0 deletions backend/app/Http/Actions/Auth/CreateApiKeyAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace HiEvents\Http\Actions\Auth;

use App\Models\Sanctum\PersonalAccessToken;
use HiEvents\DomainObjects\Enums\Role;
use HiEvents\Http\Actions\BaseAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use \DateTime;

class CreateApiKeyAction extends BaseAction
{
public function __invoke(Request $request): JsonResponse
{
$this->minimumAllowedRole(Role::ADMIN);

$abilities = ['*'];
$expiryDateTime = null;
if ($request->abilities && count($request->abilities) > 0) {
$abilities = $request->abilities;
}
if ($request->expires_at) {
$expiryDateTime = DateTime::createFromFormat("U", strtotime($request->expires_at));
}
return $this->jsonResponse($request->user()->createToken(
$request->token_name,
$abilities,
$expiryDateTime));
}
}
20 changes: 20 additions & 0 deletions backend/app/Http/Actions/Auth/GetApiKeysAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace HiEvents\Http\Actions\Auth;

use HiEvents\DomainObjects\Enums\Role;
use HiEvents\Http\Actions\BaseAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Sanctum\PersonalAccessToken;

class GetApiKeysAction extends BaseAction
{
public function __invoke(Request $request): JsonResponse
{
$this->minimumAllowedRole(Role::ADMIN);

$tokens = $request->user()->tokens;
return $this->jsonResponse($tokens);
}
}
24 changes: 24 additions & 0 deletions backend/app/Http/Actions/Auth/RevokeApiKeyAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace HiEvents\Http\Actions\Auth;

use App\Models\Sanctum\PersonalAccessToken;
use HiEvents\DomainObjects\Enums\Role;
use HiEvents\Http\Actions\BaseAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RevokeApiKeyAction extends BaseAction
{
public function __invoke(Request $request, int $apiKey): Response
{
$this->minimumAllowedRole(Role::ADMIN);

if ($request->user()->tokens()->where('id', $apiKey)->delete()) {
return $this->deletedResponse();
} else {
return $this->notFoundResponse();
}
}
}
2 changes: 2 additions & 0 deletions backend/app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,7 @@ class Kernel extends HttpKernel
'signed' => ValidateSignature::class,
'throttle' => ThrottleRequests::class,
'verified' => EnsureEmailIsVerified::class,
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
];
}
21 changes: 18 additions & 3 deletions backend/app/Http/Middleware/SetAccountContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,31 @@
use Closure;
use HiEvents\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Sanctum\TransientToken;

class SetAccountContext
{

public function handle($request, Closure $next)
{
if (Auth::check()) {
$accountId = Auth::payload()->get('account_id');
if (Auth::user()->currentAccessToken()) {
if (Auth::user()->currentAccessToken() instanceof TransientToken) {
// assume logged in
$accountId = auth()->guard('api')->payload()->get('account_id');

if ($accountId) {
User::setCurrentAccountId($accountId);
}
} else {
User::setCurrentAccountId(Auth::user()->currentAccessToken()->account_id);
}
} else {
$accountId = Auth::payload()->get('account_id');

if ($accountId) {
User::setCurrentAccountId($accountId);
if ($accountId) {
User::setCurrentAccountId($accountId);
}
}
}

Expand Down
21 changes: 21 additions & 0 deletions backend/app/Models/PersonalAccessToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace HiEvents\Models;

use Laravel\Sanctum\PersonalAccessToken as SanctumAccessToken;

class PersonalAccessToken extends SanctumAccessToken
{
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);

$this->mergeFillable(['account_id']);
}
}
22 changes: 22 additions & 0 deletions backend/app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\NewAccessToken;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use RuntimeException;
use DateTimeInterface;

class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, JWTSubject
{
Expand All @@ -25,6 +30,8 @@ class User extends BaseModel implements AuthenticatableContract, AuthorizableCon
use Authorizable;
use CanResetPassword;
use MustVerifyEmail;
use HasApiTokens;
use HasFactory;

/** @var array */
protected $guarded = [];
Expand Down Expand Up @@ -92,4 +99,19 @@ public function currentAccountUser(): HasOne
return $this->hasOne(AccountUser::class)
->where('account_id', static::getCurrentAccountId());
}

public function createToken(string $name, array $abilities = ['*'], ?DateTimeInterface $expiresAt = null)
{
$plainTextToken = $this->generateTokenString();

$token = $this->tokens()->create([
'name' => $name,
'token' => hash('sha256', $plainTextToken),
'abilities' => $abilities,
'expires_at' => $expiresAt,
'account_id' => $this->getCurrentAccountId(),
]);

return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
}
6 changes: 6 additions & 0 deletions backend/app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
use HiEvents\DomainObjects\OrganizerDomainObject;
use HiEvents\Models\Event;
use HiEvents\Models\Organizer;
use HiEvents\Models\PersonalAccessToken;
use HiEvents\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\ServiceProvider;
use Laravel\Sanctum\Sanctum;
use Stripe\StripeClient;

class AppServiceProvider extends ServiceProvider
Expand All @@ -40,11 +43,14 @@ static function ($query) {
);
}

Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);

Model::preventLazyLoading(!app()->isProduction());

Relation::enforceMorphMap([
EventDomainObject::class => Event::class,
OrganizerDomainObject::class => Organizer::class,
'user' => User::class,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious what the reason for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As soon as I added the traits required for Sanctum to the User class, I received an error about being unable to morph a User object (I unfortunately don't recall the specific error). Upon doing some google research, I discovered some other people suggesting this as a fix to the error, and it worked.

I'm sure if you remove this you'll get the same error, just in case there is a better solution I am unaware of. Or maybe you won't and I was just being gaslit. 😂

]);
}

Expand Down
11 changes: 11 additions & 0 deletions backend/app/Services/Domain/Auth/AuthUserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Models\User;
use HiEvents\Repository\Interfaces\AccountUserRepositoryInterface;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\AuthManager;
use Laravel\Sanctum\TransientToken;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
use PHPOpenSourceSaver\JWTAuth\Payload;

Expand All @@ -28,6 +30,15 @@ public function getAuthenticatedAccountId(): ?int
return null;
}

if (Auth::user()->currentAccessToken()) {
if (Auth::user()->currentAccessToken() instanceof TransientToken) {
// assume logged in
return auth()->guard('api')->payload()->get('account_id');
} else {
return Auth::user()->currentAccessToken()->account_id;
}
}

try {
/** @var Payload $payload */
$payload = $this->authManager->payload();
Expand Down
4 changes: 4 additions & 0 deletions backend/config/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@
'driver' => 'jwt',
'provider' => 'users',
],
'sanctum' => [
'driver' => 'sanctum', // For Sanctum
'provider' => 'users',
],
],

/*
Expand Down
2 changes: 1 addition & 1 deletion backend/config/sanctum.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
|
*/

'guard' => ['web'],
'guard' => ['api'],

/*
|--------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

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

return new class extends Migration
{
public function up(): void
{
Schema::table('personal_access_tokens', static function (Blueprint $table) {
$table->foreignId('account_id')
->constrained()
->onDelete('cascade');
});
}

public function down(): void
{
Schema::table('personal_access_tokens', static function (Blueprint $table) {
$table->dropColumn('account_id');
});
}
};
Loading
Loading