Embed the SaaSus SDK into your Web Application and make it multi-tenant

Embed the SaaSus SDK in your web application

*Programming knowledge is required

Reconfirm SaaS ID, API Key and Client Secret

First, check the API key on the SaaSus Development Console. Use this in your application settings
(Be careful not to expose your API key to other people. The API key displayed in this tutorial has already been deactivated.)

Prepare to use the SaaSus SDK

Open the sample application we prepared earlier in the development environment.

As we did at the beginning, make sure that the docker container is started using init.sh and the sample application is running on http://localhost/board.

First, to easily use the SaaSus Platform, embed the SaaSus SDK into your application.

In this setup the SDK is PHP based, the next step is using Composer.

Enter the php container and setup using composer.

repo$ docker compose exec php bash
root@xxx:/var/www# cd api
root@xxx:/var/www/api# composer config repositories.saasus-platform/saasus-sdk-php vcs https://github.com/saasus-platform/saasus-sdk-php

In the api directory add the SDK using the following composer command

root@xxx:/var/www/api# composer require saasus-platform/saasus-sdk-php:1.0.0

After installing the SaaSus SDK, define the environment variables necessary for using the SaaSus SDK.

Create a .env file by copying the .env.example file in the api directory and edit the following part at the bottom of the .env file

### for SaaS Platform
SAASUS_SAAS_ID="saasid_98tjo3wifaoua (SaaS ID of the screen)"
SAASUS_API_KEY="apikey_kjntowjfoasnkjntwonsflajsno4as (Screen API KEY)"
SAASUS_SECRET_KEY=" (screen client secret)"
SAASUS_LOGIN_URL="https://auth.sample.saasus.jp/ (Login screen URL)"

SAASUS_SAAS_ID, SAASUS_API_KEY, SAASUS_SECRET_KEY are the SaaS ID, API Key, and client secret displayed on the console page,
SAASUS_LOGIN_URL sets the URL of the login page created on the SaaSus development console.

Include Authentication Module

Next, include the SaaSus Platform's authentication module.

In this application, authentication is required at the root of all URIs. If not authenticated, the application cannot be used. The SaaSus authentication function is incorporated as middleware through Laravel.

As default in

api/routes/web.php

, the Laravel standard authentication function is used, replace it with the SaaSus authentication function.

Default code

Route::middleware('auth')->group(function () {
    Route::get('/', function () {
        return view('welcome');
    });
    Route::get('/dispatch', 'App\Http\Controllers\DispatchController@index')->name('dispatch');
    Route::get('/board', 'App\Http\Controllers\MessageController@index')->name('board');
    Route::post('/post', 'App\Http\Controllers\MessageController@post')->name('post');
});

require __DIR__ . '/auth.php';

Change to the following in order to incorporate the SaaSus authentication function

// Route::middleware('auth')->group(function () {
// Route::get('/', function () {
// return view('welcome');
// });
// Use SaaSus SDK standard Auth Middleware
Route::middleware(\AntiPatternInc\Saasus\Laravel\Middleware\Auth::class)->group(function () {
    Route::get('/dispatch', 'App\Http\Controllers\DispatchController@index')->name('dispatch');
    Route::get('/board', 'App\Http\Controllers\MessageController@index')->name('board');
    Route::post('/post', 'App\Http\Controllers\MessageController@post')->name('post');

    Route::redirect('/', '/board');
});

// require __DIR__ . '/auth.php';

Next prepare a receiver for callback from the authentication screen. Earlier in the set up on the SaaSus development console, the callback destination is defined as http://localhost/callback, thus receivable it at /callback .

In order to set up the callback, add the following to the last line of api/routes/web.php:

// Use the SaaS SDK standard Callback Controller to store JWT in Cookie or Local Storage
Route::get('/callback', 'AntiPatternInc\Saasus\Laravel\Controllers\CallbackController@index');

In addition, add the path to api/config/view.php so that the views provided by the SaaSus SDK can be used

    'paths' => [
        resource_path('views'),
        # ↓Add this line: View directory provided by SaaSus SDK
        resource_path('../vendor/saasus-platform/saasus-sdk-php/src/Laravel/Views'),
    ],

With this setup, the authentication information set in the SaaSus Platform will be passed as part of the request when the controller of the application is reached.

Add a request argument to the index function of api/app/Http/Controllers/MessageController.php and use dd to check if $request contains userinfo

Change the following 4 lines.

    public function index(Request $request)
    {
        // Check if user information is passed from SaaSus Platform
        dd($request->userinfo);

Once this step is completed the basic SDK setup is complete.

Now, log in from the SaaSus Platform and check the operation.

Confirmation of SaaSus SDK Integration

Access the login page created on the SaaSus Platform.

Access the login page on the domain set on the console, such as https://auth.sample.saasus.jp.

Log in with the email address and password of the user created earlier, then the page will be redirected to the URL set in the Callback URL along with the authentication information.

For example, log in with [email protected].

If there are no problems with the previous code, the following should be displayed after login.

On the application side, you can see that the user information and tenant information set earlier on the SaaSus Platform.

The redirect URL is received by the Callback processing of the SaaS SDK standard (http://localhost/callback), and in that process the authentication information is stored in the browser's local storage and cookies.

Then, with the Auth Middleware of the SaaSus SDK, use the SaaSus Platform to validate the authentication information, get the user information, and put in the Request object.

After that, the application's controller will take over, so at this point the application already has the logged-in person's information.

Now let's use this information to make the sample bulletin board application multi-tenant ready!

Making the Sample Application Multi-Tenant

As api/app/Http/Controllers/MessageController.php contains the main process, the processing for multi-tenant support will be put here.

First, change the display part.
Rewrite the whole public function index.

    public function index(Request $request)
    {
        // $request->userinfo contains various user information and tenant information, so use it
        $messages = Message::where('tenant_id', $request->userinfo['tenants'][0]['id'])->get();
        return view('messageBoard.index', ['messages' => $messages, 'plans' => $this::PLANS, 'tenant_name' => $request->userinfo['tenants'][0]['name ']]);
    }

In this way, search the DB based on the passed tenant ID.

Below is the post function.

    public function post(Request $request)
    {
        $validated = $request->validate([
            'message' => 'required|max:255'
        ]);

        // Acquire various information from userinfo of $request and use it for judgment
        $message = Message::create([
             'tenant_id' => $request->userinfo['tenants'][0]['id'],
             'user_id' => $request->userinfo['tenants'][0]['user_attribute']['username'],
             'message' => $request->message,
         ]);

        $request->session()->regenerateToken();
        return redirect()->route('board');
    }

Store tenant ID and user name as a set based on the passed user attributes.

Next, display the user ID on the page display.

Edit api/resources/views/messageBoard/index.blade.php.

Change this $message->user->name part to $message->user_id around line 32.

Before change:

                    <div class="mt-4">
                        <p>
                            {{ $message->user->name }}
                            <span class="text-xs text-gray-500">
                                {{ $message->created_at->format('Y/m/d H:i') }}
                            </span>
                        </p>

Revised:

                    <div class="mt-4">
                        <p>
                            {{ $message->user_id }}
                            <span class="text-xs text-gray-500">
                                {{ $message->created_at->format('Y/m/d H:i') }}
                            </span>
                        </p>

Multi-tenant support is now available!

Now log in and try it out.

As before, log in from the login page created on the SaaSus Platform.

When you log in, you can see that the tenant name has changed to what was set in the SaaS development console earlier.

There isn't any data yet, so let's post some.

The user name is also displayed.

Go back to the login screen, and log in as [email protected], and make some posts.

It will be reflected on the page.

Next log in with another tenant's user, [email protected]

The displayed tenant name has changed, and the content is empty.

This shows that displayed information is limited to each specific tenant.

Now, after posting several posts in the same way, log in with [email protected] and confirm that the information of the same tenant can be displayed.

Thus, per-tenant isolation is complete.

As for the current separation method, a pool model to separate tenants within the same DB and separated tenants using a simple method. Even if a different tenant separation method per your requirements, such as schema separation or database separation, you can also use the SaaSus SDK to acquire tenant information and implement it.

Now that the tenants are separated, next is the implementation of billing-related functions.

Let's implement the first steps of pricing, metering, and billing. For billing, we use a billing SaaS called Stripe. If you don't use Stripe, skip the billing part.


What’s Next