dcblogdev / laravel-microsoft-graph

Laravel package for Microsoft Graph API (Microsoft365)
https://dcblog.dev/docs/laravel-microsoft-graph
Other
120 stars 51 forks source link

Token retrieved from DB is not the good one in NewMicrosoft365SignInListener.php #49

Closed SPepoli closed 1 year ago

SPepoli commented 1 year ago

Hello,

I just ran into an issue while implementing the library. The token retrieved from the DB in the listener is not the good one. It seems like it is always the first one because of the line 14 :

$token = MsGraphToken::find($tokenId)->first();

The call to "first()" on "find()" result leads to erroneous behaviour because every user will be authenticated as the first one. I suggest fixing it like this (adding a check on existence as well, with findOrFail()) :

$token = MsGraphToken::findOrFail($tokenId);

dcblogdev commented 1 year ago

Yes, I'm working on a fix for this, it will be ready shortly. Part of a bigger re-write.

dcblogdev commented 1 year ago

I've just released https://github.com/dcblogdev/laravel-microsoft-graph/releases/tag/v3.2.0. the only changes required are updating the listener to the following if you're using the provided listener.

<?php

namespace App\Listeners;

use App\Models\User;
use Dcblogdev\MsGraph\MsGraph;
use Illuminate\Support\Facades\Auth;

class NewMicrosoft365SignInListener
{
    public function handle($event)
    {
        $user  = User::firstOrCreate([
            'email' => $event->token['info']['mail'],
        ], [
            'name'     => $event->token['info']['displayName'],
            'email'    => $event->token['info']['mail'] ?? $event->token['info']['userPrincipalName'],
            'password' => '',
        ]);

        (new MsGraph())->storeToken(
            $event->token['accessToken'],
            $event->token['refreshToken'],
            $event->token['expires'],
            $user->id,
            $user->email
        );

        Auth::login($user);
    }
}

Also updated the docs to make them more clear.