Skip to content

Commit 9ea19e2

Browse files
committed
Redirect users back to previous URL upon sign in
1 parent 44bcd57 commit 9ea19e2

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/Http/Requests/AuthKitAuthenticationRequest.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
use Illuminate\Auth\Events\Registered;
77
use Illuminate\Foundation\Http\FormRequest;
88
use Illuminate\Support\Facades\Auth;
9+
use Inertia\Inertia;
910
use Laravel\WorkOS\User;
1011
use Laravel\WorkOS\WorkOS;
12+
use Symfony\Component\HttpFoundation\Response;
1113
use WorkOS\UserManagement;
1214

1315
class AuthKitAuthenticationRequest extends FormRequest
@@ -34,7 +36,7 @@ public function authenticate(?callable $findUsing = null, ?callable $createUsing
3436
$user->user,
3537
$user->access_token,
3638
$user->refresh_token,
37-
$user->organization_id,
39+
$user->organizationId,
3840
];
3941

4042
$user = new User(
@@ -66,6 +68,20 @@ public function authenticate(?callable $findUsing = null, ?callable $createUsing
6668
return $existingUser;
6769
}
6870

71+
/**
72+
* Redirect the user to the previous or default URL.
73+
*/
74+
public function redirect(string $default = '/'): Response
75+
{
76+
$url = rtrim(base64_decode($this->session()->get('state')), '/') ?: null;
77+
78+
$to = $url !== null && $url !== url('/') ? $url : $default;
79+
80+
return class_exists(Inertia::class)
81+
? Inertia::location($to)
82+
: redirect($to);
83+
}
84+
6985
/**
7086
* Find the user with the given WorkOS ID.
7187
*/
@@ -104,7 +120,7 @@ protected function updateUsing(AppUser $user, User $userFromWorkOS): AppUser
104120
*/
105121
protected function ensureStateIsValid(): void
106122
{
107-
$state = json_decode($this->query('state'), true)['state'] ?? false;
123+
$state = json_decode($this->query('state'), true)['state'] ?? null;
108124

109125
if ($state !== $this->session()->get('state')) {
110126
abort(403);

src/Http/Requests/AuthKitLoginRequest.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
namespace Laravel\WorkOS\Http\Requests;
44

55
use Illuminate\Foundation\Http\FormRequest;
6-
use Illuminate\Support\Str;
76
use Inertia\Inertia;
87
use Laravel\WorkOS\WorkOS;
98
use Symfony\Component\HttpFoundation\Response;
@@ -20,7 +19,7 @@ public function redirect(): Response
2019

2120
$url = (new UserManagement)->getAuthorizationUrl(
2221
config('services.workos.redirect_url'),
23-
['state' => $state = Str::random(20)],
22+
['state' => $state = base64_encode(url()->previous())],
2423
'authkit',
2524
);
2625

0 commit comments

Comments
 (0)