Skip to content

Beautiful Open-Source Form Builder

Add OIDC linking functionality and related exception handling

JhumanJ3e02bf3e04b7
diff --git a/api/app/Enterprise/Oidc/Exceptions/OidcAccountLinkRequiredException.php b/api/app/Enterprise/Oidc/Exceptions/OidcAccountLinkRequiredException.php
new file mode 100644
index 000000000..7d737a3e3
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Exceptions/OidcAccountLinkRequiredException.php
@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Enterprise\Oidc\Exceptions;
+
+use Exception;
+
+class OidcAccountLinkRequiredException extends Exception
+{
+ public function __construct(
+ private readonly string $email,
+ private readonly string $subject,
+ private readonly int $connectionId,
+ private readonly array $claims,
+ string $message = 'An account with this email already exists. Please link your existing account to continue.'
+ ) {
+ parent::__construct($message);
+ }
+
+ public function getEmail(): string
+ {
+ return $this->email;
+ }
+
+ public function getSubject(): string
+ {
+ return $this->subject;
+ }
+
+ public function getConnectionId(): int
+ {
+ return $this->connectionId;
+ }
+
+ public function getClaims(): array
+ {
+ return $this->claims;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/OidcLinkService.php b/api/app/Enterprise/Oidc/OidcLinkService.php
new file mode 100644
index 000000000..b1a9083b6
--- /dev/null
+++ b/api/app/Enterprise/Oidc/OidcLinkService.php
@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Str;
+
+class OidcLinkService
+{
+ private const TOKEN_TTL_MINUTES = 15;
+
+ public function createLinkToken(int $connectionId, string $subject, string $email, array $claims): string
+ {
+ $token = Str::random(64);
+
+ Cache::put($this->cacheKey($token), [
+ 'connection_id' => $connectionId,
+ 'subject' => $subject,
+ 'email' => strtolower($email),
+ 'claims' => $claims,
+ ], now()->addMinutes(self::TOKEN_TTL_MINUTES));
+
+ return $token;
+ }
+
+ public function getLinkToken(string $token): ?array
+ {
+ $payload = Cache::get($this->cacheKey($token));
+
+ return is_array($payload) ? $payload : null;
+ }
+
+ public function consumeLinkToken(string $token): ?array
+ {
+ $payload = Cache::pull($this->cacheKey($token));
+
+ return is_array($payload) ? $payload : null;
+ }
+
+ private function cacheKey(string $token): string
+ {
+ return "oidc_link:{$token}";
+ }
+}
diff --git a/api/app/Enterprise/Oidc/ProvisioningService.php b/api/app/Enterprise/Oidc/ProvisioningService.php
index 5c4832dbd..85de18dd1 100644
--- a/api/app/Enterprise/Oidc/ProvisioningService.php
+++ b/api/app/Enterprise/Oidc/ProvisioningService.php
@@ -2,6 +2,7 @@
namespace App\Enterprise\Oidc;
+use App\Enterprise\Oidc\Exceptions\OidcAccountLinkRequiredException;
use App\Enterprise\Oidc\Models\IdentityConnection;
use App\Enterprise\Oidc\Models\UserIdentity;
use App\Models\User;
@@ -76,8 +77,11 @@ class ProvisioningService
'email' => $email,
]);
- throw new \Exception(
- 'An account with this email already exists. Please contact your administrator to link your accounts.'
+ throw new OidcAccountLinkRequiredException(
+ email: $email,
+ subject: $subject,
+ connectionId: $connection->id,
+ claims: $idTokenClaims,
);
}
diff --git a/api/app/Http/Controllers/Auth/OidcLinkController.php b/api/app/Http/Controllers/Auth/OidcLinkController.php
new file mode 100644
index 000000000..c3428f7ec
--- /dev/null
+++ b/api/app/Http/Controllers/Auth/OidcLinkController.php
@@ -0,0 +1,73 @@
+<?php
+
+namespace App\Http\Controllers\Auth;
+
+use App\Enterprise\Oidc\Models\UserIdentity;
+use App\Enterprise\Oidc\OidcLinkService;
+use App\Http\Controllers\Controller;
+use Illuminate\Http\Request;
+
+class OidcLinkController extends Controller
+{
+ public function link(Request $request, OidcLinkService $linkService)
+ {
+ $validated = $request->validate([
+ 'link_token' => ['required', 'string'],
+ ]);
+
+ $payload = $linkService->getLinkToken($validated['link_token']);
+
+ if (!$payload) {
+ return response()->json([
+ 'message' => 'This link request has expired. Please try again.',
+ 'error' => 'oidc_link_expired',
+ ], 410);
+ }
+
+ $user = $request->user();
+ $email = strtolower($user->email);
+
+ if ($email !== strtolower($payload['email'])) {
+ return response()->json([
+ 'message' => 'This link request does not match your account.',
+ 'error' => 'oidc_link_email_mismatch',
+ ], 403);
+ }
+
+ $existingIdentity = UserIdentity::where('connection_id', $payload['connection_id'])
+ ->where('subject', $payload['subject'])
+ ->first();
+
+ if ($existingIdentity && $existingIdentity->user_id !== $user->id) {
+ return response()->json([
+ 'message' => 'This SSO identity is already linked to another user.',
+ 'error' => 'oidc_link_already_linked',
+ ], 409);
+ }
+
+ $payload = $linkService->consumeLinkToken($validated['link_token']);
+
+ if (!$payload) {
+ return response()->json([
+ 'message' => 'This link request has expired. Please try again.',
+ 'error' => 'oidc_link_expired',
+ ], 410);
+ }
+
+ UserIdentity::updateOrCreate(
+ [
+ 'connection_id' => $payload['connection_id'],
+ 'subject' => $payload['subject'],
+ ],
+ [
+ 'user_id' => $user->id,
+ 'email' => $email,
+ 'claims' => $payload['claims'] ?? [],
+ ]
+ );
+
+ return response()->json([
+ 'linked' => true,
+ ]);
+ }
+}
diff --git a/api/app/Http/Controllers/Auth/SsoController.php b/api/app/Http/Controllers/Auth/SsoController.php
index 5b4263340..ebd7ecc1e 100644
--- a/api/app/Http/Controllers/Auth/SsoController.php
+++ b/api/app/Http/Controllers/Auth/SsoController.php
@@ -3,7 +3,9 @@
namespace App\Http\Controllers\Auth;
use App\Enterprise\Oidc\ConnectionManager;
+use App\Enterprise\Oidc\Exceptions\OidcAccountLinkRequiredException;
use App\Enterprise\Oidc\IdTokenVerifier;
+use App\Enterprise\Oidc\OidcLinkService;
use App\Http\Controllers\Auth\Traits\ManagesJWT;
use App\Http\Controllers\Controller;
use App\Enterprise\Oidc\ProvisioningService;
@@ -17,7 +19,8 @@ class SsoController extends Controller
public function __construct(
private ConnectionManager $connectionManager,
private ProvisioningService $provisioningService,
- private IdTokenVerifier $idTokenVerifier
+ private IdTokenVerifier $idTokenVerifier,
+ private OidcLinkService $oidcLinkService
) {
}
@@ -175,6 +178,19 @@ class SsoController extends Controller
'new_user' => $isNewUser,
'redirect_url' => $request->cookie('intended_url') ?? '/home',
]);
+ } catch (OidcAccountLinkRequiredException $e) {
+ $linkToken = $this->oidcLinkService->createLinkToken(
+ connectionId: $e->getConnectionId(),
+ subject: $e->getSubject(),
+ email: $e->getEmail(),
+ claims: $e->getClaims(),
+ );
+
+ return response()->json([
+ 'message' => $e->getMessage(),
+ 'error' => 'oidc_account_link_required',
+ 'link_token' => $linkToken,
+ ], 409);
} catch (HttpException $e) {
// Handle HTTP exceptions (like 403 for blocked users) - preserve status code
return response()->json([
diff --git a/api/routes/api.php b/api/routes/api.php
index dad74f349..5a891b54c 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -3,6 +3,7 @@
use App\Http\Controllers\Auth\ForgotPasswordController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\OAuthController;
+use App\Http\Controllers\Auth\OidcLinkController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\Auth\ResetPasswordController;
use App\Http\Controllers\Auth\UserController;
@@ -47,6 +48,7 @@ if (config('app.self_hosted')) {
Route::group(['middleware' => 'auth.multi'], function () {
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
+ Route::post('auth/oidc/link', [OidcLinkController::class, 'link'])->name('oidc.link');
// Unsplash
Route::get('/unsplash', [\App\Http\Controllers\Content\UnsplashController::class, 'index'])->name('unsplash.index');
diff --git a/api/tests/Feature/Enterprise/Oidc/OidcLinkControllerTest.php b/api/tests/Feature/Enterprise/Oidc/OidcLinkControllerTest.php
new file mode 100644
index 000000000..d303afaff
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/OidcLinkControllerTest.php
@@ -0,0 +1,107 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Models\UserIdentity;
+use App\Enterprise\Oidc\OidcLinkService;
+use Illuminate\Support\Facades\Cache;
+use Tests\TestHelpers;
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+afterEach(function () {
+ Cache::flush();
+});
+
+describe('OidcLinkController', function () {
+ it('links an existing account with a valid token', function () {
+ $user = $this->actingAsUser();
+ $connection = IdentityConnection::factory()->create();
+
+ $linkToken = app(OidcLinkService::class)->createLinkToken(
+ connectionId: $connection->id,
+ subject: 'sub-123',
+ email: $user->email,
+ claims: ['email' => $user->email]
+ );
+
+ $response = $this->postJson('/auth/oidc/link', [
+ 'link_token' => $linkToken,
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'linked' => true,
+ ]);
+
+ $this->assertDatabaseHas('user_identities', [
+ 'user_id' => $user->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-123',
+ 'email' => $user->email,
+ ]);
+ });
+
+ it('rejects expired or unknown tokens', function () {
+ $this->actingAsUser();
+
+ $response = $this->postJson('/auth/oidc/link', [
+ 'link_token' => 'missing-token',
+ ]);
+
+ $response->assertStatus(410);
+ $response->assertJson([
+ 'error' => 'oidc_link_expired',
+ ]);
+ });
+
+ it('rejects when the token email does not match the logged in user', function () {
+ $user = $this->actingAsUser();
+ $connection = IdentityConnection::factory()->create();
+
+ $linkToken = app(OidcLinkService::class)->createLinkToken(
+ connectionId: $connection->id,
+ subject: 'sub-456',
+ email: '[email protected]',
+ claims: ['email' => '[email protected]']
+ );
+
+ $response = $this->postJson('/auth/oidc/link', [
+ 'link_token' => $linkToken,
+ ]);
+
+ $response->assertStatus(403);
+ $response->assertJson([
+ 'error' => 'oidc_link_email_mismatch',
+ ]);
+ });
+
+ it('rejects when the subject is already linked to another user', function () {
+ $user = $this->actingAsUser();
+ $otherUser = $this->createUser();
+ $connection = IdentityConnection::factory()->create();
+
+ UserIdentity::factory()->create([
+ 'user_id' => $otherUser->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-789',
+ 'email' => $otherUser->email,
+ ]);
+
+ $linkToken = app(OidcLinkService::class)->createLinkToken(
+ connectionId: $connection->id,
+ subject: 'sub-789',
+ email: $user->email,
+ claims: ['email' => $user->email]
+ );
+
+ $response = $this->postJson('/auth/oidc/link', [
+ 'link_token' => $linkToken,
+ ]);
+
+ $response->assertStatus(409);
+ $response->assertJson([
+ 'error' => 'oidc_link_already_linked',
+ ]);
+ });
+});
diff --git a/client/api/oidc.js b/client/api/oidc.js
index f2be935e2..82bc0f359 100644
--- a/client/api/oidc.js
+++ b/client/api/oidc.js
@@ -32,5 +32,7 @@ export const oidcApi = {
}
})
},
+
+ link: (linkToken) => apiService.post('/auth/oidc/link', { link_token: linkToken }),
}
diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vue
index f6b38edb3..9207ce19c 100644
--- a/client/components/pages/auth/components/LoginForm.vue
+++ b/client/components/pages/auth/components/LoginForm.vue
@@ -136,6 +136,7 @@ const router = useRouter()
const { login: loginMutationFactory } = useAuth()
const authFlow = useAuthFlow()
const { showTwoFactorModal, pendingAuthToken, handleTwoFactorVerified, handleTwoFactorCancel, handleTwoFactorError } = authFlow
+const { completeLinkIfNeeded } = useOidcLinking()
// Feature flags
const oidcAvailable = computed(() => useFeatureFlag('oidc.available', false))
@@ -240,7 +241,11 @@ const login = () => {
form.mutate(loginMutation).then(() => {
// If 2FA modal is shown, don't redirect yet (handled in handleTwoFactorVerified)
if (!showTwoFactorModal.value) {
- redirect()
+ completeLinkIfNeeded().then((shouldRedirect) => {
+ if (shouldRedirect) {
+ redirect()
+ }
+ })
}
}).catch((error) => {
// Check if this is a 2FA requirement (422 with requires_2fa flag)
@@ -292,8 +297,13 @@ const signInwithGoogle = () => {
}
}
-const handleTwoFactorVerifiedAndRedirect = async (tokenData) => {
- await handleTwoFactorVerified(tokenData)
- redirect()
+const handleTwoFactorVerifiedAndRedirect = (tokenData) => {
+ handleTwoFactorVerified(tokenData).then(() => {
+ completeLinkIfNeeded().then((shouldRedirect) => {
+ if (shouldRedirect) {
+ redirect()
+ }
+ })
+ })
}
</script>
diff --git a/client/composables/useOidcLinking.js b/client/composables/useOidcLinking.js
new file mode 100644
index 000000000..ac3b3ad0d
--- /dev/null
+++ b/client/composables/useOidcLinking.js
@@ -0,0 +1,63 @@
+import { oidcApi } from "~/api"
+
+export const useOidcLinking = () => {
+ const router = useRouter()
+ const route = useRoute()
+ const alert = useAlert()
+
+ const linkToken = computed(() => {
+ const token = route.query.oidc_link_token
+ if (Array.isArray(token)) {
+ return token[0]
+ }
+ return token || null
+ })
+
+ const startLink = (token) => {
+ if (!token) {
+ return
+ }
+
+ router.push({
+ name: 'login',
+ query: { oidc_link_token: token },
+ })
+ }
+
+ const clearLinkToken = () => {
+ if (!linkToken.value) {
+ return
+ }
+
+ const nextQuery = { ...route.query }
+ delete nextQuery.oidc_link_token
+ router.replace({ query: nextQuery })
+ }
+
+ const completeLinkIfNeeded = () => {
+ if (!linkToken.value) {
+ return Promise.resolve(true)
+ }
+
+ return oidcApi.link(linkToken.value)
+ .then(() => {
+ alert.success("Your SSO account has been linked.")
+ return true
+ })
+ .catch((error) => {
+ const errorMessage = error.response?._data?.message || 'Failed to link your SSO account.'
+ alert.error(errorMessage)
+ return false
+ })
+ .finally(() => {
+ clearLinkToken()
+ })
+ }
+
+ return {
+ linkToken,
+ startLink,
+ clearLinkToken,
+ completeLinkIfNeeded,
+ }
+}
diff --git a/client/pages/auth/[slug]/callback.vue b/client/pages/auth/[slug]/callback.vue
index ac24af8d8..b9e490ced 100644
--- a/client/pages/auth/[slug]/callback.vue
+++ b/client/pages/auth/[slug]/callback.vue
@@ -29,6 +29,12 @@
class="w-full"
:description="error"
/>
+ <UButton
+ v-if="linkToken"
+ color="primary"
+ label="Link existing account"
+ @click="goToLinkLogin"
+ />
<UButton
:to="{ name: 'login' }"
label="Back to login"
@@ -45,6 +51,8 @@ const router = useRouter()
const route = useRoute()
const loading = ref(true)
const error = ref(null)
+const linkToken = ref(null)
+const { startLink } = useOidcLinking()
const authFlow = useAuthFlow()
const { showTwoFactorModal, pendingAuthToken, handleTwoFactorVerified, handleTwoFactorCancel: handleTwoFactorCancelFromFlow, handleTwoFactorError } = authFlow
@@ -102,11 +110,15 @@ const handleCallback = async () => {
} catch (err) {
console.error("[OIDC Callback] Authentication error:", err)
- const errorMessage = err.response?._data?.message || err.message || "Authentication failed"
+ const errorResponse = err.response?._data || {}
+ const errorMessage = errorResponse.message || err.message || "Authentication failed"
error.value = errorMessage
// Handle specific error cases
- if (errorMessage.includes('account with this email already exists')) {
+ if (errorResponse.error === 'oidc_account_link_required' && errorResponse.link_token) {
+ error.value = 'An account with this email already exists. Please link your existing account to continue.'
+ linkToken.value = errorResponse.link_token
+ } else if (errorMessage.includes('account with this email already exists')) {
error.value = 'An account with this email already exists. Please contact your administrator to link your accounts.'
} else if (errorMessage.includes('blocked')) {
error.value = 'Your account has been blocked. Please contact support.'
@@ -121,6 +133,10 @@ const handleTwoFactorCancel = () => {
router.push({ name: 'login' })
}
+const goToLinkLogin = () => {
+ startLink(linkToken.value)
+}
+
const handleTwoFactorVerifiedAndRedirect = async (tokenData) => {
await handleTwoFactorVerified(tokenData)
diff --git a/client/plugins/pinia-history.js b/client/plugins/pinia-history.js
index a410b14e5..372fe1d62 100644
--- a/client/plugins/pinia-history.js
+++ b/client/plugins/pinia-history.js
@@ -171,5 +171,8 @@ const PiniaHistory = (context) => {
}
export default defineNuxtPlugin(nuxtApp => {
+ if (!nuxtApp?.$pinia) {
+ return
+ }
nuxtApp.$pinia.use(PiniaHistory)
})
diff --git a/client/test/nuxt/oidc-link-flow.spec.ts b/client/test/nuxt/oidc-link-flow.spec.ts
new file mode 100644
index 000000000..7af7d3a2d
--- /dev/null
+++ b/client/test/nuxt/oidc-link-flow.spec.ts
@@ -0,0 +1,206 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { mount, flushPromises } from '@vue/test-utils'
+import { ref } from 'vue'
+import OidcCallbackPage from '~/pages/auth/[slug]/callback.vue'
+import LoginForm from '~/components/pages/auth/components/LoginForm.vue'
+
+const { startLinkSpy, completeLinkIfNeededSpy } = vi.hoisted(() => ({
+ startLinkSpy: vi.fn(),
+ completeLinkIfNeededSpy: vi.fn(() => Promise.resolve(true)),
+}))
+
+vi.mock('~/middleware/01.check-auth.global', () => ({
+ default: () => { },
+}))
+
+vi.mock('~/plugins/pinia-history', () => ({
+ default: () => { },
+}))
+
+vi.mock('~/plugins/pinia-history.js', () => ({
+ default: () => { },
+}))
+
+vi.mock('~/composables/useAuthFlow', () => ({
+ useAuthFlow: () => ({
+ showTwoFactorModal: ref(false),
+ pendingAuthToken: ref(null),
+ handleTwoFactorVerified: vi.fn(() => Promise.resolve()),
+ handleTwoFactorCancel: vi.fn(),
+ handleTwoFactorError: vi.fn(() => null),
+ }),
+ useIsAuthenticated: () => ({
+ isAuthenticated: ref(false),
+ }),
+}))
+
+vi.mock('~/composables/query/useOAuth', () => ({
+ useOAuth: () => ({
+ guestConnect: vi.fn(),
+ }),
+}))
+
+vi.mock('~/composables/query/useAuth', () => ({
+ useAuth: () => ({
+ login: () => vi.fn(),
+ }),
+}))
+
+vi.mock('~/composables/useOidcLinking', () => ({
+ useOidcLinking: () => ({
+ linkToken: ref(null),
+ startLink: startLinkSpy,
+ clearLinkToken: vi.fn(),
+ completeLinkIfNeeded: completeLinkIfNeededSpy,
+ }),
+}))
+
+vi.mock('~/api', () => ({
+ oidcApi: {
+ callback: vi.fn(),
+ link: vi.fn(),
+ },
+}))
+
+describe('OIDC link flow', () => {
+ const setupGlobals = (routeOverrides = {}) => {
+ const router = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ }
+
+ const route = {
+ params: { slug: 'test-sso' },
+ query: {},
+ ...routeOverrides,
+ }
+
+ vi.stubGlobal('useRouter', () => router)
+ vi.stubGlobal('useRoute', () => route)
+ vi.stubGlobal('useAuthFlow', () => ({
+ showTwoFactorModal: ref(false),
+ pendingAuthToken: ref(null),
+ handleTwoFactorVerified: vi.fn(() => Promise.resolve()),
+ handleTwoFactorCancel: vi.fn(),
+ handleTwoFactorError: vi.fn(() => null),
+ }))
+ vi.stubGlobal('useAlert', () => ({
+ success: vi.fn(),
+ error: vi.fn(),
+ }))
+ vi.stubGlobal('useAuthStore', () => ({
+ token: null,
+ initStore: vi.fn(),
+ clearToken: vi.fn(),
+ }))
+ vi.stubGlobal('useQueryClient', () => ({
+ getQueryData: vi.fn(),
+ clear: vi.fn(),
+ }))
+ vi.stubGlobal('useAuth', () => ({
+ user: () => ({ suspense: vi.fn() }),
+ }))
+ vi.stubGlobal('useWorkspaces', () => ({
+ list: () => ({ suspense: vi.fn() }),
+ }))
+ vi.stubGlobal('useFeatureFlag', () => false)
+ vi.stubGlobal('useForm', () => ({
+ email: '',
+ password: '',
+ remember: false,
+ busy: false,
+ post: vi.fn(),
+ mutate: vi.fn(),
+ }))
+ vi.stubGlobal('useAuth', () => ({
+ login: () => vi.fn(),
+ }))
+ vi.stubGlobal('useWindowMessage', () => ({
+ listen: vi.fn(),
+ send: vi.fn(),
+ }))
+
+ return { router, route }
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it('shows link CTA when callback returns link required error', async () => {
+ vi.useFakeTimers()
+ const apiModule = await import('~/api') as { oidcApi: any }
+ const oidcApi = apiModule.oidcApi
+ setupGlobals()
+
+ oidcApi.callback.mockRejectedValue({
+ response: {
+ _data: {
+ error: 'oidc_account_link_required',
+ link_token: 'token-123',
+ message: 'Link required',
+ },
+ },
+ })
+
+ const wrapper = mount(OidcCallbackPage, {
+ global: {
+ stubs: {
+ TwoFactorVerificationModal: true,
+ Loader: true,
+ UAlert: {
+ template: '<div class="alert">{{ description }}</div>',
+ props: ['description'],
+ },
+ UButton: {
+ template: '<button>{{ label }}<slot /></button>',
+ props: ['label', 'color', 'variant', 'to'],
+ emits: ['click'],
+ },
+ },
+ },
+ })
+
+ await flushPromises()
+ vi.runAllTimers()
+ await flushPromises()
+
+ expect(wrapper.text()).toContain('Link existing account')
+ vi.useRealTimers()
+ })
+
+ it('links account after two-factor verification when token is present', async () => {
+ setupGlobals({
+ query: { oidc_link_token: 'link-token-123' },
+ })
+
+ const wrapper = mount(LoginForm, {
+ global: {
+ stubs: {
+ ForgotPasswordModal: true,
+ TwoFactorVerificationModal: true,
+ VForm: {
+ template: '<form><slot /></form>',
+ props: ['form'],
+ },
+ TextInput: true,
+ CheckboxInput: true,
+ UButton: true,
+ VTransition: true,
+ NuxtLink: true,
+ ClientOnly: true,
+ GoogleOneTap: true,
+ },
+ },
+ })
+
+ const vm = wrapper.vm as any
+ await vm.handleTwoFactorVerifiedAndRedirect({ token: 'verified-token' })
+
+ expect(completeLinkIfNeededSpy).toHaveBeenCalled()
+ })
+})
diff --git a/client/test/nuxt/setup.ts b/client/test/nuxt/setup.ts
new file mode 100644
index 000000000..6665debb2
--- /dev/null
+++ b/client/test/nuxt/setup.ts
@@ -0,0 +1,61 @@
+import { computed, ref } from 'vue'
+import { vi } from 'vitest'
+
+vi.mock('~/middleware/auth', () => ({
+ default: () => {},
+}))
+
+vi.mock('~/middleware/auth.js', () => ({
+ default: () => {},
+}))
+
+globalThis.useAuthStore = () => ({
+ token: null,
+ initStore: vi.fn(),
+ clearToken: vi.fn(),
+})
+
+globalThis.useQueryClient = () => ({
+ getQueryData: vi.fn(),
+ clear: vi.fn(),
+})
+
+globalThis.useAuth = () => ({
+ user: () => ({ suspense: vi.fn() }),
+})
+
+globalThis.useWorkspaces = () => ({
+ list: () => ({ suspense: vi.fn() }),
+})
+
+globalThis.useOverlay = () => ({
+ create: () => ({
+ open: vi.fn(),
+ close: vi.fn(),
+ }),
+})
+
+globalThis.useRoute = () => ({
+ query: {},
+})
+
+globalThis.useRouter = () => ({
+ replace: vi.fn(),
+ push: vi.fn(),
+})
+
+globalThis.useRouteQuery = () => ref(null)
+
+globalThis.useIsAuthenticated = () => ({
+ isAuthenticated: computed(() => false),
+})
+
+globalThis.useGtm = () => ({
+ trackEvent: vi.fn(),
+})
+
+globalThis.navigateTo = vi.fn()
+
+globalThis.useCookie = () => ({
+ value: null,
+})
diff --git a/client/test/unit/useOidcLinking.test.ts b/client/test/unit/useOidcLinking.test.ts
new file mode 100644
index 000000000..2e843b9cf
--- /dev/null
+++ b/client/test/unit/useOidcLinking.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { computed } from 'vue'
+import { useOidcLinking } from '../../composables/useOidcLinking.js'
+
+vi.mock('~/api', () => ({
+ oidcApi: {
+ link: vi.fn(),
+ },
+}))
+
+describe('useOidcLinking', () => {
+ let router
+ let route
+ let alert
+
+ beforeEach(() => {
+ router = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ }
+ route = {
+ query: {},
+ }
+ alert = {
+ success: vi.fn(),
+ error: vi.fn(),
+ }
+
+ globalThis.computed = computed
+ globalThis.useRouter = () => router
+ globalThis.useRoute = () => route
+ globalThis.useAlert = () => alert
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ delete globalThis.computed
+ delete globalThis.useRouter
+ delete globalThis.useRoute
+ delete globalThis.useAlert
+ })
+
+ it('starts linking by pushing login with token', () => {
+ const { startLink } = useOidcLinking()
+ startLink('token-123')
+
+ expect(router.push).toHaveBeenCalledWith({
+ name: 'login',
+ query: { oidc_link_token: 'token-123' },
+ })
+ })
+
+ it('links account and clears query on success', async () => {
+ const { oidcApi } = await import('~/api')
+ oidcApi.link.mockResolvedValue({ linked: true })
+
+ route.query = { oidc_link_token: 'token-123', extra: 'keep' }
+ const { completeLinkIfNeeded } = useOidcLinking()
+
+ await completeLinkIfNeeded()
+
+ expect(oidcApi.link).toHaveBeenCalledWith('token-123')
+ expect(alert.success).toHaveBeenCalled()
+ expect(router.replace).toHaveBeenCalledWith({
+ query: { extra: 'keep' },
+ })
+ })
+
+ it('shows error when linking fails', async () => {
+ const { oidcApi } = await import('~/api')
+ oidcApi.link.mockRejectedValue({
+ response: {
+ _data: {
+ message: 'Link failed',
+ },
+ },
+ })
+
+ route.query = { oidc_link_token: 'token-123' }
+ const { completeLinkIfNeeded } = useOidcLinking()
+
+ await completeLinkIfNeeded()
+
+ expect(alert.error).toHaveBeenCalledWith('Link failed')
+ expect(router.replace).toHaveBeenCalledWith({
+ query: {},
+ })
+ })
+})
diff --git a/client/vitest.config.ts b/client/vitest.config.ts
index 2f1de3806..44bbaa0dd 100644
--- a/client/vitest.config.ts
+++ b/client/vitest.config.ts
@@ -26,6 +26,7 @@ export default defineConfig({
include: ['test/nuxt/**/*.{test,spec}.ts'],
environment: 'nuxt',
testTimeout: 20000,
+ setupFiles: ['test/nuxt/setup.ts'],
environmentOptions: {
nuxt: {
domEnvironment: 'jsdom',