jamesmills / laravel-timezone

Enable user Timezones in your application.
MIT License
675 stars 89 forks source link

Stateless support - Illuminate\\Auth\\RequestGuard::loginUsingId does not exist #83

Open logan-jobzmall opened 2 years ago

logan-jobzmall commented 2 years ago

It seems like this package doesn't support stateless requests (only web middleware). If we aren't using Web routes, we get Illuminate\\Auth\\RequestGuard::loginUsingId does not exist - how can we use this? Thanks for the help.

cedlinx commented 2 years ago

I encountered the same issue using this in my REST API... A workaround would be highly appreciated

cedlinx commented 2 years ago

I encountered the same issue using this in my REST API... A workaround would be highly appreciated

I found the source of the error:

The handle function in "...vendor/jamesmills/laravel-timezone/src/Listeners/Auth/UpdateUsersTimezone.php"

Then found "loginUsingId" in the first IF block

` if ($event instanceof AccessTokenCreated) { Auth::loginUsingId($event->userId);

        return;

} `

and replaced Auth::loginUsingId($event->userId); with $user = User::find($event->userId);

DO NOT forget to include your user model at the begining of the file like this use App\Models\User;

I also had to comment out the return statement in the IF block above before my change had any effect.

PS: I believe this is safe since according to the comment in the file, that IF block is required ONLY to trigger the the Login Event which in turn only returns the user object. If anyone finds a better solution, I'd be glad to use it, but for now, this works for me besides the fact that my timezone is wrongly captured.

obrunopolo commented 1 year ago

I encountered a similar issue, and cedlinx provided a helpful workaround. In my case, I had a function for support where authorized people could access user accounts. I could get this error when calling an API using the Laravel\Passport\HasApiTokens::createToken method. This dispatches an AccessTokenCreated event, which calls Auth::loginUsingId, triggering the error.

Following cedlinx's suggestion, I found that the source of the error lies in the handle function within vendor/jamesmills/laravel-timezone/src/Listeners/Auth/UpdateUsersTimezone.php. Inside the function, there is an if block with the following code:

if ($event instanceof AccessTokenCreated) {
    Auth::loginUsingId($event->userId);
    return;
}

cedlinx proposed a workaround by replacing the line Auth::loginUsingId($event->userId) with $user = User::find($event->userId). Additionally, they mentioned the need to include the user model at the beginning of the file using use App\Models\User;.

It's important to note that before the proposed change takes effect, the return statement within the if block needs to be commented out.

I appreciate cedlinx's contribution, as this workaround resolved the issue for me. However, I'm open to other suggestions or alternative solutions from the community.