Skip to content
Closed
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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
```shell
composer install
cp .env.example .env
php artisan key:generate
touch database/database.sqlite
php artisan migrate --seed
```
Expand All @@ -27,6 +28,40 @@ php artisan serve

Access [the GraphiQL UI](https://github.com/graphql/graphiql/blob/main/packages/graphiql/README.md) at `/graphiql`.

Sanctum keeps sessions only for [stateful domains](https://laravel.com/docs/sanctum#configuring-your-first-party-domains), such as `127.0.0.1:8000`.

In order to log in through Sanctum, find out the email of the seeded user:

```graphql
{
users {
data {
email
}
}
}
```

Then, log in with the following mutation:

```graphql
mutation {
login(email: "<email>", password: "password") {
id
}
}
```

To validate you are in fact logged in, run the following query:

```graphql
{
me {
id
}
}
```

## Minimalism

In order to keep maintenance as simple as possible,
Expand Down
35 changes: 35 additions & 0 deletions app/GraphQL/Mutations/Login.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\GraphQL\Mutations;

use App\Models\User;
use GraphQL\Error\Error;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

final class Login
{
/**
* @param null $_
* @param array{email: string, password: string} $args
*/
public function __invoke($_, array $args): User
{
$guardConfig = config('sanctum.guard');
assert(is_array($guardConfig));

$guardName = Arr::first($guardConfig);
assert(is_string($guardName));

$guard = Auth::guard($guardName);

if (! $guard->attempt($args)) {
throw new Error('Invalid credentials.');
}

$user = $guard->user();
assert($user instanceof User, 'must receive User after successful login');

return $user;
}
}
27 changes: 27 additions & 0 deletions app/GraphQL/Mutations/Logout.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\GraphQL\Mutations;

use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

final class Logout
{
public function __invoke(): ?User
{
$guardConfig = config('sanctum.guard');
assert(is_array($guardConfig));

$guardName = Arr::first($guardConfig);
assert(is_string($guardName));

$guard = Auth::guard($guardName);

$user = $guard->user();

$guard->logout();

return $user;
}
}
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"require": {
"php": "^8.3",
"laravel/framework": "^13",
"laravel/sanctum": "^4",
"laravel/tinker": "^3.0",
"mll-lab/laravel-graphiql": "^4",
"nuwave/lighthouse": "^6"
Expand Down
65 changes: 64 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions config/graphiql.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php declare(strict_types=1);

return [
/*
|--------------------------------------------------------------------------
| Routes configuration
|--------------------------------------------------------------------------
|
| Set the key as URI at which the GraphiQL UI can be viewed,
| and add any additional configuration for the route.
|
| You can add multiple routes pointing to different GraphQL endpoints.
|
*/

'routes' => [
'/graphiql' => [
'name' => 'graphiql',
'middleware' => ['web'],
// 'prefix' => '',
// 'domain' => 'graphql.' . env('APP_DOMAIN', 'localhost'),

/*
|--------------------------------------------------------------------------
| Default GraphQL endpoint
|--------------------------------------------------------------------------
|
| The default endpoint that the GraphiQL UI is set to.
| It assumes you are running GraphQL on the same domain
| as GraphiQL, but can be set to any URL.
|
*/

'endpoint' => '/graphql',

/*
|--------------------------------------------------------------------------
| Subscription endpoint
|--------------------------------------------------------------------------
|
| The default subscription endpoint the GraphiQL UI uses to connect to.
| Tries to connect to the `endpoint` value if `null` as ws://{{endpoint}}
|
| Example: `ws://your-endpoint` or `wss://your-endpoint`
|
*/

'subscription-endpoint' => env('GRAPHIQL_SUBSCRIPTION_ENDPOINT', null),
],
],

/*
|--------------------------------------------------------------------------
| Control GraphiQL availability
|--------------------------------------------------------------------------
|
| Control if the GraphiQL UI is accessible at all.
| This allows you to disable it in certain environments,
| for example you might not want it active in production.
|
*/

'enabled' => env('GRAPHIQL_ENABLED', true),
];
54 changes: 54 additions & 0 deletions config/lighthouse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php declare(strict_types=1);

return [
/*
|--------------------------------------------------------------------------
| Route Configuration
|--------------------------------------------------------------------------
|
| Controls the HTTP route that your GraphQL server responds to.
| You may set `route` => false, to disable the default route
| registration and take full control.
|
*/

'route' => [
/*
* The URI the endpoint responds to, e.g. mydomain.com/graphql.
*/
'uri' => '/graphql',

/*
* Lighthouse creates a named route for convenient URL generation and redirects.
*/
'name' => 'graphql',

/*
* Beware that middleware defined here runs before the GraphQL execution phase.
* Make sure to return spec-compliant responses in case an error is thrown.
*/
'middleware' => [
Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

// Ensures the request is not vulnerable to cross-site request forgery.
// Nuwave\Lighthouse\Http\Middleware\EnsureXHR::class,

// Always set the `Accept: application/json` header.
Nuwave\Lighthouse\Http\Middleware\AcceptJson::class,

// Logs in a user if they are authenticated. In contrast to Laravel's 'auth'
// middleware, this delegates auth and permission checks to the field level.
Nuwave\Lighthouse\Http\Middleware\AttemptAuthentication::class,

// Logs every incoming GraphQL query.
// Nuwave\Lighthouse\Http\Middleware\LogGraphQLQueries::class,
],

/*
* The `prefix`, `domain` and `where` configuration options are optional.
*/
// 'prefix' => '',
// 'domain' => '',
// 'where' => [],
],
];
25 changes: 25 additions & 0 deletions database/migrations/2024_11_13_083152_create_sessions_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types=1);

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

return new class extends Migration
{
public function up(): void
{
Schema::create('sessions', function (Blueprint $table): void {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}

public function down(): void
{
Schema::dropIfExists('sessions');
}
};
8 changes: 8 additions & 0 deletions graphql/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,12 @@ scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")
"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

type Mutation {
"Log in to a new session and get the user."
login(email: String!, password: String!): User!
Comment thread
spawnia marked this conversation as resolved.

"Log out from the current session, showing the user one last time."
logout: User @guard
}

#import models/*.graphql
Loading
Loading