hellocash/hellomicroservice

基于laravel/lighthouse/graphql的web服务的共享工具,包括RSA JWT认证和通过JWT声明和laravel作用域的多租户

1.8.11 2020-11-26 06:42 UTC

README

基于laravel/lighthouse/graphql的web服务的共享工具,包括RSA JWT认证和通过JWT声明和laravel作用域的多租户

安装(创建新项目)

始终用您服务或应用的名称替换 helloTest

composer create-project --prefer-dist laravel/laravel helloTest
git clone git@github.com:mRaPGmbH/helloTest.git temp
mv temp/.git helloTest/.git
rm -rf temp
cd helloTest
composer require hellocash/hellomicroservice
php artisan vendor:publish --all
php artisan key:generate

配置

config/cors.php

修改

'paths' => ['api/*'],

'paths' => ['api/*', 'graphql/*', 'graphql'],

config/app.php

添加

'providers': => [
    ...
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
    HelloCash\HelloMicroservice\Providers\LaravelServiceProvider::class,
    App\Providers\GraphQLServiceProvider::class,
    Yab\MySQLScout\Providers\MySQLScoutServiceProvider::class,        
],

config/lighthouse.php

修改

'uri' => '/graphql',

'uri' => '/api/test/graphql',

(将 /test 替换为您的服务或应用的URL路径。)

修改

'guard' => null,

'guard' => 'api',

修改

'namespaces' => [
    ...
    'mutations' => 'App\\GraphQL\\Mutations',

'namespaces' => [
    ...
    'mutations' => [
        'HelloCash\\HelloMicroservice\\GraphQL\\Mutations',
        'App\\GraphQL\\Mutations'
    ],

添加

'error_handlers' => [
	...
    \HelloCash\HelloMicroservice\GraphQL\ClientAwareErrorHandler::class,
],

config/auth.php

修改

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
],

'providers' => [
    'users' => [
        'driver' => 'jwtuser'
    ],
],

config/jwt.php

修改

'algo' => env('JWT_ALGO', 'HS256'),
...
'required_claims' => [
    'iss',
    'iat',
    'exp',
    'nbf',
    'sub',
    'jti',
],

'algo' => env('JWT_ALGO', 'RS256'), // please note: R instead of H !
...
'required_claims' => [
    'exp',
],

config/scout.php

在 'algolia' 配置下方添加

'mysql' => [
    'mode' => 'LIKE_EXPANDED',
    'model_directories' => [app_path()],
    'min_search_length' => 0,
    'min_fulltext_search_length' => 4,
    'min_fulltext_search_fallback' => 'LIKE',
    'query_expansion' => false
],

环境

.env

修改

APP_URL=https://

APP_URL=put-your-app-url-here

修改

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=helloTest # replace with name of your service
DB_USERNAME=helloTest # replace with name of your service
DB_PASSWORD=helloTest # replace with name of your service

添加到底部

SENTRY_LARAVEL_DSN=put-your-sentry-url-here
JWT_PUBLIC_KEY=file:///var/www/html/jwtkey-public.pem
LIGHTHOUSE_CACHE_ENABLE=true
SCOUT_DRIVER=mysql

将文件 jwtkey-public.pem (RSA公钥) 复制到应用根目录。如果您还没有RSA密钥对,可以使用

openssl genrsa -des3 -out jwtkey-private.pem 2048
openssl rsa -in jwtkey-private.pem -outform PEM -pubout -out jwtkey-public.pem

.env.production

首先

cp .env .env.production

然后更改

APP_ENV=local
...
APP_DEBUG=true
...
LOG_CHANNEL=stack
...
SESSION_DRIVER=file

APP_ENV=production
...
APP_DEBUG=false
...
LOG_CHANNEL=stderr
...
SESSION_DRIVER=array

删除所有以

REDIS_*
MAIL_*
AWS_*
PUSHER_*
MIX_PUSHER_* 

.env.example

替换为您的新的 .env 文件

cp .env .env.example

路由

routes/web.php

修改

Route::get('/', function () {
    return view('welcome');
});

Route::namespace('\HelloCash\HelloMicroservice\Http\Controllers')->group(function () {"
    Route::get('/', 'HealthCheck');"
    Route::get('api/test/', 'HealthCheck');"
});"

(将 /test 替换为您的服务或应用的URL路径。)

Laravel相关

app/Providers/AppServiceProvider

添加

public function boot() {
    ...
    Builder::defaultStringLength(191); // required for compatibility with mysql 5.6 (and RDS Aurora 5.6-compatible)

(升级到mysql 5.7后,此部分将不再需要!)

routes/api.php

删除

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
}); 

graphql/schema.graphql

删除

type Query {
    ...
}

type User {
    ...
}

添加

"A datetime and timezone string in ISO 8601 format `Y-m-dTH:i:sO`, e.g. `2020-04-20T13:53:12+02:00`."
scalar DateTimeTz @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTimeTz")

"file upload"
scalar Upload @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Upload")

input DateRange {
    from: Date!
    to: Date!
}
input DateTimeRange {
    from: DateTime!
    to: DateTime!
}
input DateTimeTzRange {
    from: DateTimeTz!
    to: DateTimeTz!
}
input IntRange {
    from: Int
    to: Int
}
input FloatRange {
    from: Float
    to: Float
}

app/User

删除此文件。

database/seeds/UserSeeder

删除此文件。

附加功能

复合主键的自定义mutations

当您的模型使用复合主键或应通过除id以外的其他键加载数据时

在您的模型中实现 HelloCash\HelloMicroservice\Interfaces\CUstomMutations 接口

class MyClass extends Model implements CustomMutations
{

    public static function queryForMutations(array $args): Builder
    {
        return self::where('my_field', $args['my_field']);
    }        

方法 queryForMutations 必须返回一个预填充了成功加载模型所需一切内容的查询构建器。

$args 是一个数组,包含在GraphQL查询中找到的参数。相应的GraphQL查询可能如下所示

{
    myClass(my_field: 'value') {
        id
    }
}

多租户

如果您有一个希望成为租户感知的模型,将 HelloCash\HelloMicroservice\Traits\TenantScopeTrait 添加到您的模型中

class MyClass extends Model
{
    use HelloCash\HelloMicroservice\Traits\TenantScopeTrait;

tenant_id 必须在jwt中,作为名为/键为: tid 的声明

使用EnumTypes

要将枚举添加到您的GraphQL端点,您必须将每个所需的EnumType(位于HelloCash\HelloMicroservice\GraphQL\EnumTypes\)注册到您的 GraphQLServiceProvider 中的注册器中

public function boot(TypeRegistry $typeRegistry): void
{
    $typeRegistry->register(Countries::get());
    $typeRegistry->register(Languages::get());
}

您还可以添加自己的枚举。(参见helloCrm: app/GraphQL/EnumTypes/NewsletterStatuses.php 以获取示例。)