Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample setup Lighthouse with Lumen
<?php
require_once __DIR__.'/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
// $app->withFacades(); No facades, woohoo
$app->withEloquent();
/*
|--------------------------------------------------------------------------
| Load configuration files.
|--------------------------------------------------------------------------
|
|
*/
$app->configure('app');
$app->configure('auth');
$app->configure('lighthouse');
$app->configure('lighthouse_subscriptions');
$app->configure('status_codes');
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
$app->middleware([
\Nord\Lumen\Cors\CorsMiddleware::class,
]);
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'scopes' => Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
'cors' => \Nord\Lumen\Cors\CorsMiddleware::class,
]);
if (!function_exists('config_path')) {
function config_path($path = '')
{
return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
}
}
if (!function_exists('app_path')) {
function app_path($path = '')
{
return app()->basePath() . '/app' . ($path ? '/' . $path : $path);
}
}
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(\App\Providers\AppServiceProvider::class);
$app->register(\App\Providers\AuthServiceProvider::class);
$app->register(\App\Providers\EventServiceProvider::class);
$app->register(\App\Providers\PassportServiceProvider::class);
$app->register(\Dusterio\LumenPassport\PassportServiceProvider::class);
$app->register(\Illuminate\Redis\RedisServiceProvider::class);
$app->register(\Illuminate\Broadcasting\BroadcastServiceProvider::class);
$app->register(\Nuwave\Lighthouse\Providers\LighthouseServiceProvider::class);
$app->register(\Nuwave\Lighthouse\Subscriptions\SubscriptionServiceProvider::class);
if ($app->environment() == 'local') {
$app->register(Laravel\Tinker\TinkerServiceProvider::class);
$app->register(Appzcoder\LumenRoutesList\RoutesCommandServiceProvider::class);
}
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
# Just the basics: User with Images
scalar DateTime @scalar(class: "DateTime")
type User {
id: ID! @globalId
name: String
email: String
created_at: DateTime!
updated_at: DateTime!
last_login_at: DateTime!
last_request_at: DateTime!
images(orderBy: String): [Image!]! @paginate(type: "relay", model: "Image", scopes: ["orderAndFilter"])
}
type Image @model {
id: ID! @globalId
person: User! @belongsTo
number: Float!
filename: String
active: Boolean
created_at: DateTime!
}
type Query {
viewer: User @auth
images (orderBy: String): [Image!]! @paginate(type: "relay", model: "Image", scopes: ["orderAndFilter"])
}
<?php
namespace App\Providers;
use Queue;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
//@TODO Remove me when a fix is implemented
protected function loadRoutesFrom($location){
return $location;
}
}
<?php
namespace App\Providers;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;
use Dusterio\LumenPassport\LumenPassport;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// 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.
LumenPassport::routes($this->app, ['prefix' => 'oauth']);
LumenPassport::allowMultipleTokens();
LumenPassport::tokensExpireIn(Carbon::now()->addDays(50));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(60));
// Gates
// Gate::define('update-post', function ($user, $post) {
// return $user->id === $post->user_id;
// }); // if (Gate::allows('update-post', $post)) {
// Policies
// Gate::policy(Post::class, PostPolicy::class);
Passport::tokensCan(['login', 'graphql']);
}
}
<?php
namespace App\Providers;
use Carbon\Carbon;
use Dusterio\LumenPassport\LumenPassport;
use Illuminate\Auth\RequestGuard;
use Illuminate\Auth\Events\Logout;
use Laravel\Passport\Passport;
use Laravel\Passport\ClientRepository;
use Laravel\Passport\Guards\TokenGuard;
use Laravel\Passport\PassportServiceProvider as LaravelPassportServiceProvider;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\ResourceServer;
class PassportServiceProvider extends LaravelPassportServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// override key path, not needed if you're not using NixOS
// Passport::$keyPath = '/run/keys';
parent::boot();
}
/**
* Register the token guard.
*
* @return void
*/
protected function registerGuard()
{
app('auth')->extend('passport', function ($app, $name, array $config) {
return tap($this->makeGuard($config), function ($guard) {
$this->app->refresh('request', $guard, 'setRequest');
});
});
}
/**
* Make an instance of the token guard.
*
* @param array $config
* @return \Illuminate\Auth\RequestGuard
*/
protected function makeGuard(array $config)
{
return new RequestGuard(function ($request) use ($config) {
return (new TokenGuard(
$this->app->make(ResourceServer::class),
app('auth')->createUserProvider($config['provider']),
$this->app->make(TokenRepository::class),
$this->app->make(ClientRepository::class),
$this->app->make('encrypter')
))->user($request);
}, $this->app['request']);
}
/**
* Register the cookie deletion event handler.
*
* @return void
*/
protected function deleteCookieOnLogout()
{
// never needed since API's shouldn't use cookies AFAIK
// $this->app['event']->listen(Logout::class, function () {
// if ($this->app['request']->hasCookie(Passport::cookie())) {
// $this->app['cookie']->queue($this->app['cookie']->forget(Passport::cookie()));
// }
// });
}
}
{
"name": "wyw/api",
"description": "The API for the Witness Your World platform",
"keywords": ["wyw", "api", "platform"],
"license": "MIT",
"type": "project",
"repositories": [
{
"type": "vcs",
"url": "https://github.com/4levels/lumen-tinker" // just to update dependency version
}
],
"require": {
"php": ">=7.1.3",
"dusterio/lumen-passport": "^0.2.6",
"illuminate/redis": "^5.6",
"laravel/lumen-framework": "5.6.*",
"laravel/passport": "~6.0.0",
"nuwave/lighthouse": "dev-master",
"nuwave/lighthouse-ws": "dev-master",
"predis/predis": "^1.1",
"vlucas/phpdotenv": "~2.2"
},
"require-dev": {
"appzcoder/lumen-routes-list": "^1.0",
"fzaninotto/faker": "~1.4",
"laravel/tinker": "dev-master",
"mockery/mockery": "~1.0",
"phpunit/phpunit": "~7.0"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
"scripts": {
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
}
}
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
*/
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon"
|
*/
'driver' => 'bcrypt',
];
<?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this, as it will be used to sign your tokens.
| A helper command is provided for this: `php artisan jwt:generate`
|
*/
'secret' => env('JWT_SECRET', 'jasdflñjdslfjklrowqweupoi'),
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/
'ttl' => 60,
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks
|
*/
'refresh_ttl' => 20160,
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/2.2.0/src/Namshi/JOSE/Signer
| for possible values
|
*/
'algo' => 'HS256',
/*
|--------------------------------------------------------------------------
| User Model namespace
|--------------------------------------------------------------------------
|
| Specify the full namespace to your User model.
| e.g. 'Acme\Entities\User'
|
*/
'user' => 'App\User',
/*
|--------------------------------------------------------------------------
| User identifier
|--------------------------------------------------------------------------
|
| Specify a unique property of the user that will be added as the 'sub'
| claim of the token payload.
|
*/
'identifier' => 'id',
/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/
'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| User Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to find the user based
| on the subject claim
|
*/
'user' => 'Tymon\JWTAuth\Providers\User\EloquentUserAdapter',
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => 'Tymon\JWTAuth\Providers\JWT\Namshi',
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => 'Tymon\JWTAuth\Providers\Auth\Illuminate',
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist
|
*/
'storage' => 'Tymon\JWTAuth\Providers\Storage\Illuminate',
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| LightHouse endpoint & middleware
|--------------------------------------------------------------------------
|
| Setup this values as required,
| default route endpoints its yourdomain.com/graphql
| setup middleware here for all request,
| setup more endpoints, ej: pointing to the controller value inside your route file
|
*/
'route_name' => 'graphql',
'route' => [
'prefix' => '',
'middleware' => [ 'auth:api', 'scopes:graphql' ], // [ 'loghttp']
],
/*
|--------------------------------------------------------------------------
| Directive registry
|--------------------------------------------------------------------------
|
| This package allows you to create your own server-side directives. Change
| these values to register the directory that will hold all of your
| custom directives.
|
*/
'directives' => [__DIR__.'/../app/GraphQL/Directives'],
/*
|--------------------------------------------------------------------------
| Namespace registry
|--------------------------------------------------------------------------
|
| This package provides a set of commands to make it easy for you to
| create new parts in your GraphQL schema. Change these values to
| match the namespaces you'd like each piece to be created in.
|
*/
'namespaces' => [
'models' => 'App\Models',
'mutations' => 'App\GraphQL\Mutations',
'queries' => 'App\GraphQL\Queries',
'types' => 'App\GraphQL\Types',
'fields' => 'App\GraphQL\Fields',
'scalars' => 'App\GraphQL\Scalars',
'connections' => 'App\GraphQL\Connections',
'dataloaders' => 'App\GraphQL\DataLoaders',
],
/*
|--------------------------------------------------------------------------
| GraphQL Controller
|--------------------------------------------------------------------------
|
| Specify which controller (and method) you want to handle GraphQL requests.
|
*/
'controller' => 'Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController@query',
/*
|--------------------------------------------------------------------------
| Schema Cache
|--------------------------------------------------------------------------
|
| Specify where the GraphQL schema should be cached.
|
*/
'cache' => null,
/*
|--------------------------------------------------------------------------
| Global ID
|--------------------------------------------------------------------------
|
| When creating a GraphQL type that is Relay compliant, provide a named field
| for the Node identifier.
|
*/
'global_id_field' => 'id',
/*
|--------------------------------------------------------------------------
| Schema declaration
|--------------------------------------------------------------------------
|
| This is a path that points to where your GraphQL schema is located
| relative to the app path. You should define your entire GraphQL
| schema in this file (additional files may be imported).
|
*/
'schema' => [
'register' => base_path('app/GraphQL/schema.graphql'),
],
'route_enable_get' => true,
];
<?php
return [
/**
* The port the web socket server
* will listen on.
*/
'port' => env('WEBSOCKET_PORT', 8100),
/**
* Set your keep alive interval here
* if your connection requires it.
*/
'keep_alive' => env('WEBSOCKET_KEEPALIVE', 0),
/**
* Set connection storage here.
*/
'storage' => env('WEBSOCKET_STORAGE', 'memory'),
/**
* Set context generator here.
*/
'context' => env('WEBSOCKET_CONTEXT', 'subscriber'),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment