binarycamp/shared-library

A simple Laravel package of common Utils Classes and Basic functionality

v0.1.16 2024-02-28 22:15 UTC

README

Run the following command to pull in the latest version:

composer require binarycamp/shared-library

Add service provider

Add the service provider to the providers array in the config/app.php config file as follows:

'providers' => [
    ...
    BinaryCamp\sharedLibrary\Providers\BinaryCampSharedLibraryServiceProvider::class,
]

Publish the config Run the following command to publish the package config file:

php artisan vendor:publish --provider="BinaryCamp\sharedLibrary\Providers\BinaryCampSharedLibraryServiceProvider"

You should now have a config/shared_library.php file that allows you to configure the basics of this package.

Environment Variables

To enable automatic database query generation, add the following environment variables to .env file

IS_QUERY_LOG_ENABLE=true

or you can manually declare query log generation method

AppLog::setQueryLogStatus(status: true)->createQueryLog(file_name: "my_query_log");

Create Application Log

AppLog::createLog(action: "MY_EVENT_NAME", data: ["data1" => "John", "data2" => "Dao"],  type: AppLogLevel::Info);

If you want to set different log channel then

AppLog::setChanel(chanel: config("logging.channels.daily"))->createLog(action: "MY_EVENT_NAME", data:["data1" => "John", "data2" => "Dao"], type: AppLogLevel::Info);

DB Transaction

AppDB::transaction(function () use ($param1, $param2){
       //operation 1
            
       //operation 2
}, $attempt = 2);

Alternatively, you can declare like below:

try {
    AppDB::beginTransaction();

    //operation 1

    //operation 2
            
    AppDB::commit();
}catch (\Throwable $exception){
    AppDB::rollBack()->createLog($exception);
}

Api Response

Success Response

Return AppResponse::setSuccess(status_code: 100,  status_message: "Operation Successful", data: ["data1" => "John", "data2" => "Dao"],  http: 200)
            ->toJson();

If you want to log api response then:

AppResponse::setSuccess( status_code: 100,  status_message: "Operation Successful", data: ["data1" => "John", "data2" => "Dao"],  http: 200)
            ->createLog(action: "User Save Event")
            ->toJson();

Fail Response

AppResponse::setError( status_code: 99,  status_message: "Operation Failed",  errors: [],  http: 404)
            ->toJson();

If you want to log api response then:

AppResponse::setError( status_code: 99,  status_message:"Operation Failed", errors: [],  http:404)
            ->createLog(action: "User Save Event")
            ->toJson();

Authentication

Generate public key and private key

php artisan generate:jwtKey
    {audience : You must select an Audience. Audience is configured in shared_library.php file}
    {version : version of the key}
    {--length=4096}
    {--force=0}
    
    //example
    
    php artisan generate:jwtKey USERS  v2 --force=1

Route Configuration

Route::middleware('AppAuth')->get('/auth-check', function (Request $request) {

    if (AppAuth::check()){
        $authObj = AppAuth::getAuthInfo();

        return AppResponse::setSuccess(100, 'Auth Checked Successfully', [
            'authObj' => $authObj
        ], HttpCode::ACCEPTED)
            ->toJson();
    }
});

above example, AppAuth middleware is assigned. Here AppAuth is name of middleware.

Generate Token by email and password

Route::post('login', function (Request $request){
    $userObj = \App\Models\User::query()->where('email', $request->email)->first();

    if (!empty($userObj)){

        AppAuth::setAudience("USERS")->setCustomClaim([
                'user_id' => $userObj->id,
                'company_id' => $userObj->company_id,
                'usergroup_ids' => $userObj->usergroup_ids,
                'name' => $userObj->name,
                'email' => $userObj->email,
                'phone' => $userObj->phone,
                ]
        )->login();

        return AppResponse::setSuccess(100, 'Token Generated Successfully', [
            'access_token' => AppAuth::getToken(),
            'refresh_token' => AppAuth::getRefreshToken(),
            'authObj' => AppAuth::getAuthInfo(),
        ], HttpCode::ACCEPTED)
            ->toJson();
    }
});

This Audience is taken from config file name shared_library.php under config directory.

Generate Token by refresh token

Route::post('/refresh', function (Request $request){
    $refresh_token = $request->refresh_token;

    try {
        AppAuth::setToken($refresh_token)->validate()->verify();

        //we can allow only one time access token by a refresh token
        AppAuth::blackList();
        
        $payload = AppAuth::getPayload();

        $user_id = $payload['sub'];
        $userObj = \App\Models\User::query()->find($user_id);


        AppAuth::setAudience($payload['aud'])->setCustomClaim([
                'user_id' => $userObj->id,
                'company_id' => $userObj->company_id,
                'usergroup_ids' => $userObj->usergroup_ids,
                'name' => $userObj->name,
                'email' => $userObj->email,
                'phone' => $userObj->phone,
            ]
        )->login();

        return AppResponse::setSuccess(100, 'Token Generated Successfully', [
            'access_token' => AppAuth::getToken(),
            'refresh_token' => AppAuth::getRefreshToken(),
            'authObj' => AppAuth::getAuthInfo(),
        ], HttpCode::ACCEPTED)
            ->toJson();


    }catch (\Throwable $exception){
        return AppResponse::setError(99, "Invalid Token", [], 400)
            ->toJson();
    }
    
});

Permission Middleware

Route::middleware(['AppAuth', 'AppPermission'])->get('/check-permission', function (Request $request) {


    return AppResponse::setSuccess(100, 'Permission Checked Successfully', [
        'authObj' => AppAuth::getAuthInfo()
    ], HttpCode::ACCEPTED)
        ->toJson();
})->name('acl.check.permission');

To check Permission, AppAuth middleware is required. Then AppPermission needs to place.