feat: authentication with OAuth
All checks were successful
ci / ci (push) Successful in 16m22s

This commit is contained in:
2025-12-07 21:27:23 +01:00
parent 4e9b4a19b8
commit 40ae2145cc
25 changed files with 3114 additions and 1466 deletions

View File

@@ -1,5 +1,7 @@
<template>
<UUser name="name" description="email" />
<UUser v-if="user" :name="user.name" :description="user.email" :avatar="{ src: user.avatar }" />
</template>
<script lang="ts" setup></script>
<script lang="ts" setup>
const { user } = useAuth();
</script>

View File

@@ -0,0 +1,17 @@
<template>
<UButton
color="neutral"
size="xl"
class="flex cursor-pointer items-center justify-center gap-3 overflow-hidden"
@click="login(provider.name)"
>
Continue with {{ provider.displayName }}
</UButton>
</template>
<script lang="ts" setup>
import type { AuthProviderInfo } from 'pocketbase';
const { login } = useAuth();
const { provider } = defineProps<{ provider: AuthProviderInfo }>();
</script>

View File

@@ -1,3 +1,18 @@
<template>
<UButton color="neutral" variant="ghost" icon="i-lucide-log-out" size="xl"> Log Out </UButton>
<UButton color="neutral" variant="ghost" icon="i-lucide-log-out" size="xl" @click="onLogout"> Log Out </UButton>
</template>
<script setup lang="ts">
const { logout } = useAuth();
const toast = useToast();
const onLogout = () => {
logout();
navigateTo('/');
toast.add({
title: 'Successfully logged out!',
description: 'You successfully logged out of your account and have been taken back to the websites welcome page.',
color: 'success',
});
};
</script>

View File

@@ -0,0 +1,444 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { mockNuxtImport } from '@nuxt/test-utils/runtime';
import type { AuthProviderInfo, AuthModel, RecordModel } from 'pocketbase';
/**
* Comprehensive tests for useAuth composable
* Based on specs from private/specs.md section 3.1 (Authentication API)
*
* These tests verify actual behavior, not just API existence.
*/
// Mock PocketBase
const mockAuthStore = {
isValid: false,
record: null as AuthModel | null,
clear: vi.fn(),
onChange: vi.fn(),
};
const mockCollection = vi.fn();
const mockAuthWithOAuth2 = vi.fn();
const mockListAuthMethods = vi.fn();
const mockAuthRefresh = vi.fn();
vi.mock('../usePocketbase', () => ({
usePocketbase: () => ({
authStore: mockAuthStore,
collection: mockCollection,
}),
}));
// Mock router using Nuxt's test utils
const mockRouterPush = vi.fn();
const mockRouter = {
push: mockRouterPush,
};
mockNuxtImport('useRouter', () => {
return () => mockRouter;
});
describe('useAuth', () => {
beforeEach(async () => {
// Reset all mocks
vi.clearAllMocks();
mockAuthStore.isValid = false;
mockAuthStore.record = null;
// Setup default mock implementations
mockCollection.mockReturnValue({
authWithOAuth2: mockAuthWithOAuth2,
listAuthMethods: mockListAuthMethods,
authRefresh: mockAuthRefresh,
});
// Clear module cache to get fresh imports
vi.resetModules();
});
describe('Composable Export', () => {
it('should be exported as a function', async () => {
const { useAuth } = await import('../useAuth');
expect(useAuth).toBeDefined();
expect(typeof useAuth).toBe('function');
});
it('should return an object with auth methods and state', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
expect(auth).toBeDefined();
expect(typeof auth).toBe('object');
});
});
describe('Initial State', () => {
it('should initialize with user as null', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
expect(auth.user.value).toBeNull();
});
it('should initialize with isAuthenticated as false', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
expect(auth.isAuthenticated.value).toBe(false);
});
it('should initialize with loading as false', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
expect(auth.loading.value).toBe(false);
});
it('should initialize with error as null', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
expect(auth.error.value).toBeNull();
});
});
describe('initAuth', () => {
it('should sync user from authStore', async () => {
const mockUser: AuthModel = {
id: 'user123',
email: 'test@example.com',
} as unknown as AuthModel;
mockAuthStore.record = mockUser;
mockAuthStore.isValid = true;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
expect(auth.user.value).toEqual(mockUser);
});
it('should register onChange listener', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
expect(mockAuthStore.onChange).toHaveBeenCalled();
});
it('should update user when authStore changes', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
// Get the onChange callback
const onChangeCallback = mockAuthStore.onChange.mock.calls[0]?.[0];
// Simulate auth change
const newUser = {
id: 'newUser456',
email: 'new@example.com',
};
onChangeCallback('token123', newUser);
expect(auth.user.value).toEqual(newUser);
});
});
describe('login', () => {
const mockProviders: AuthProviderInfo[] = [
{
name: 'google',
displayName: 'Google',
state: 'state123',
codeVerifier: 'verifier',
codeChallenge: 'challenge',
codeChallengeMethod: 'S256',
authURL: 'https://google.com/oauth',
},
{
name: 'microsoft',
displayName: 'Microsoft',
state: 'state456',
codeVerifier: 'verifier2',
codeChallenge: 'challenge2',
codeChallengeMethod: 'S256',
authURL: 'https://microsoft.com/oauth',
},
];
beforeEach(() => {
mockListAuthMethods.mockResolvedValue({
oauth2: {
enabled: true,
providers: mockProviders,
},
});
});
it('should set loading to true when login starts', async () => {
mockAuthWithOAuth2.mockImplementation(() => new Promise(() => {})); // Never resolves
const { useAuth } = await import('../useAuth');
const auth = useAuth();
const loginPromise = auth.login('google');
expect(auth.loading.value).toBe(true);
// Cleanup
await Promise.race([loginPromise, new Promise((resolve) => setTimeout(resolve, 10))]);
});
it('should clear previous errors when starting new login', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
// Set an error first
auth.error.value = new Error('Previous error');
mockAuthWithOAuth2.mockResolvedValue({});
await auth.login('google');
expect(auth.error.value).toBeNull();
});
it('should call authWithOAuth2 with correct provider', async () => {
mockAuthWithOAuth2.mockResolvedValue({});
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('google');
expect(mockAuthWithOAuth2).toHaveBeenCalledWith({ provider: 'google' });
});
it('should set loading to false after login completes', async () => {
mockAuthWithOAuth2.mockResolvedValue({});
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('google');
expect(auth.loading.value).toBe(false);
});
it('should throw error if provider is not configured', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('github'); // Not in mockProviders
expect(auth.error.value).toBeDefined();
expect(auth.error.value?.message).toContain('github');
expect(auth.error.value?.message).toContain('not configured');
});
it('should handle OAuth errors gracefully', async () => {
const mockError = new Error('OAuth failed');
mockAuthWithOAuth2.mockRejectedValue(mockError);
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('google');
expect(auth.error.value).toEqual(mockError);
expect(auth.loading.value).toBe(false);
});
it('should support multiple OAuth providers', async () => {
mockAuthWithOAuth2.mockResolvedValue({});
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('google');
expect(mockAuthWithOAuth2).toHaveBeenCalledWith({ provider: 'google' });
await auth.login('microsoft');
expect(mockAuthWithOAuth2).toHaveBeenCalledWith({ provider: 'microsoft' });
});
it('should return empty array when OAuth is disabled', async () => {
mockListAuthMethods.mockResolvedValue({
oauth2: {
enabled: false,
providers: [],
},
});
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.login('google');
expect(auth.error.value).toBeDefined();
expect(auth.error.value?.message).toContain('not configured');
});
});
describe('handleOAuthCallback', () => {
it('should sync user from authStore', async () => {
const mockUser: AuthModel = {
id: 'user123',
email: 'test@example.com',
} as unknown as AuthModel;
mockAuthStore.record = mockUser;
mockAuthStore.isValid = true;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.handleOAuthCallback();
expect(auth.user.value).toEqual(mockUser);
});
it('should redirect to dashboard when authenticated', async () => {
mockAuthStore.record = {
id: 'user123',
email: 'test@example.com',
} as unknown as RecordModel;
mockAuthStore.isValid = true;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.handleOAuthCallback();
expect(mockRouterPush).toHaveBeenCalledWith('/dashboard');
});
it('should redirect to home when not authenticated', async () => {
mockAuthStore.record = null;
mockAuthStore.isValid = false;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.handleOAuthCallback();
expect(mockRouterPush).toHaveBeenCalledWith('/');
});
});
describe('refreshAuth', () => {
it('should call authRefresh on users collection', async () => {
mockAuthRefresh.mockResolvedValue({
token: 'newToken',
record: { id: 'user123', email: 'test@example.com' },
});
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.refreshAuth();
expect(mockCollection).toHaveBeenCalledWith('users');
expect(mockAuthRefresh).toHaveBeenCalled();
});
it('should return the refresh result', async () => {
const mockResult = {
token: 'newToken',
record: { id: 'user123', email: 'test@example.com' },
};
mockAuthRefresh.mockResolvedValue(mockResult);
const { useAuth } = await import('../useAuth');
const auth = useAuth();
const result = await auth.refreshAuth();
expect(result).toEqual(mockResult);
});
});
describe('logout', () => {
it('should clear authStore', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
auth.logout();
expect(mockAuthStore.clear).toHaveBeenCalled();
});
it('should clear authStore even when user is authenticated', async () => {
mockAuthStore.record = {
id: 'user123',
email: 'test@example.com',
} as unknown as RecordModel;
mockAuthStore.isValid = true;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
auth.logout();
expect(mockAuthStore.clear).toHaveBeenCalled();
});
});
describe('isAuthenticated computed', () => {
it('should be false when authStore is invalid', async () => {
mockAuthStore.isValid = false;
mockAuthStore.record = { id: 'user123', email: 'test@example.com' } as unknown as RecordModel;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
expect(auth.isAuthenticated.value).toBe(false);
});
it('should be false when user is null', async () => {
mockAuthStore.isValid = true;
mockAuthStore.record = null;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
expect(auth.isAuthenticated.value).toBe(false);
});
it('should be true when authStore is valid and user exists', async () => {
mockAuthStore.isValid = true;
mockAuthStore.record = { id: 'user123', email: 'test@example.com' } as unknown as RecordModel;
const { useAuth } = await import('../useAuth');
const auth = useAuth();
await auth.initAuth();
expect(auth.isAuthenticated.value).toBe(true);
});
});
describe('Exposed API', () => {
it('should expose all required methods and properties', async () => {
const { useAuth } = await import('../useAuth');
const auth = useAuth();
// State
expect(auth.user).toBeDefined();
expect(auth.isAuthenticated).toBeDefined();
expect(auth.loading).toBeDefined();
expect(auth.error).toBeDefined();
// Methods
expect(typeof auth.initAuth).toBe('function');
expect(typeof auth.login).toBe('function');
expect(typeof auth.logout).toBe('function');
expect(typeof auth.handleOAuthCallback).toBe('function');
expect(typeof auth.refreshAuth).toBe('function');
});
});
});

View File

@@ -0,0 +1,158 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { usePageTitle } from '../usePageTitle';
/**
* Unit tests for usePageTitle composable
*
* This composable manages page titles throughout the application.
*/
describe('usePageTitle', () => {
beforeEach(() => {
// Reset modules to ensure clean state
vi.resetModules();
});
describe('Initialization', () => {
it('should initialize with default title "Tímmál"', () => {
const { title } = usePageTitle();
expect(title.value).toBe('Tímmál');
});
it('should initialize with empty page name', () => {
const { pageName } = usePageTitle();
expect(pageName.value).toBe(null);
});
});
describe('Setting Page Name', () => {
it('should update page name when setPageName is called', () => {
const { pageName, setPageName } = usePageTitle();
setPageName('Dashboard');
expect(pageName.value).toBe('Dashboard');
});
it('should update title to include page name', () => {
const { title, setPageName } = usePageTitle();
setPageName('Dashboard');
expect(title.value).toBe('Dashboard - Tímmál');
});
it('should handle empty string gracefully', () => {
const { title, setPageName } = usePageTitle();
// First set a name
setPageName('Dashboard');
expect(title.value).toBe('Dashboard - Tímmál');
// Then clear it
setPageName('');
expect(title.value).toBe('Tímmál');
});
it('should handle multiple page name changes', () => {
const { title, setPageName } = usePageTitle();
setPageName('Dashboard');
expect(title.value).toBe('Dashboard - Tímmál');
setPageName('Projects');
expect(title.value).toBe('Projects - Tímmál');
setPageName('Settings');
expect(title.value).toBe('Settings - Tímmál');
});
});
describe('Title Formatting', () => {
it('should format title as "PageName - Tímmál" when page name is set', () => {
const { title, setPageName } = usePageTitle();
setPageName('Reports');
expect(title.value).toBe('Reports - Tímmál');
});
it('should format title as "Tímmál" when page name is empty', () => {
const { title, setPageName } = usePageTitle();
setPageName(null);
expect(title.value).toBe('Tímmál');
});
it('should preserve special characters in page name', () => {
const { title, setPageName } = usePageTitle();
setPageName('Reports & Analytics');
expect(title.value).toBe('Reports & Analytics - Tímmál');
});
it('should preserve unicode characters', () => {
const { title, setPageName } = usePageTitle();
setPageName('Paramètres');
expect(title.value).toBe('Paramètres - Tímmál');
});
});
describe('State Sharing', () => {
it('should share state across multiple calls', () => {
const instance1 = usePageTitle();
const instance2 = usePageTitle();
// Set via first instance
instance1.setPageName('Dashboard');
// Should be visible in second instance
expect(instance2.title.value).toBe('Dashboard - Tímmál');
expect(instance2.pageName.value).toBe('Dashboard');
});
});
describe('Exposed API', () => {
it('should expose title as computed', () => {
const { title } = usePageTitle();
expect(title).toBeDefined();
expect(title.value).toBeDefined();
});
it('should expose pageName as readonly', () => {
const { pageName } = usePageTitle();
expect(pageName).toBeDefined();
expect(pageName.value).toBeDefined();
});
it('should expose setPageName method', () => {
const { setPageName } = usePageTitle();
expect(setPageName).toBeDefined();
expect(typeof setPageName).toBe('function');
});
it('title should be readonly (TypeScript enforced)', () => {
const { title } = usePageTitle();
// readonly() is enforced by TypeScript, not at runtime
// This test just verifies the property exists
expect(title).toBeDefined();
expect(title.value).toBeDefined();
});
it('pageName should be readonly (TypeScript enforced)', () => {
const { pageName } = usePageTitle();
// readonly() is enforced by TypeScript, not at runtime
// This test just verifies the property exists
expect(pageName).toBeDefined();
expect(pageName.value).toBeDefined();
});
});
});

View File

@@ -0,0 +1,85 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { usePocketbase } from '../usePocketbase';
import PocketBase from 'pocketbase';
/**
* Tests for usePocketbase composable
*
* This composable provides a singleton PocketBase client instance.
*/
describe('usePocketbase', () => {
beforeEach(() => {
// Reset modules to clear singleton between test suites
vi.resetModules();
});
describe('Instance Creation', () => {
it('should return a PocketBase instance', () => {
const pb = usePocketbase();
expect(pb).toBeInstanceOf(PocketBase);
});
it('should return the same instance on multiple calls (singleton)', () => {
const pb1 = usePocketbase();
const pb2 = usePocketbase();
expect(pb1).toBe(pb2);
});
});
describe('Configuration', () => {
it('should initialize with URL from runtime config or fallback to default', () => {
const pb = usePocketbase();
// Should have a baseURL set (either from config or default)
expect(pb.baseURL).toBeDefined();
expect(typeof pb.baseURL).toBe('string');
expect(pb.baseURL).toMatch(/^https?:\/\//); // Valid URL format
});
it('should use a valid URL format', () => {
const pb = usePocketbase();
// URL should be a valid HTTP/HTTPS URL
expect(pb.baseURL).toMatch(/^https?:\/\/[\w\d.:]+/);
});
});
describe('Singleton Behavior', () => {
it('should maintain singleton across multiple imports', () => {
const pb1 = usePocketbase();
const pb2 = usePocketbase();
const pb3 = usePocketbase();
expect(pb1).toBe(pb2);
expect(pb2).toBe(pb3);
});
it('should share auth state across all consumers', () => {
const pb1 = usePocketbase();
const pb2 = usePocketbase();
// Both should share the same authStore
expect(pb1.authStore).toBe(pb2.authStore);
});
});
describe('PocketBase Features', () => {
it('should have authStore available', () => {
const pb = usePocketbase();
expect(pb.authStore).toBeDefined();
});
it('should have collection method available', () => {
const pb = usePocketbase();
expect(pb.collection).toBeDefined();
expect(typeof pb.collection).toBe('function');
});
it('should be able to access collections', () => {
const pb = usePocketbase();
const usersCollection = pb.collection('users');
expect(usersCollection).toBeDefined();
});
});
});

View File

@@ -0,0 +1,84 @@
import type { AuthProviderInfo, RecordModel } from 'pocketbase';
import { usePocketbase } from './usePocketbase';
export interface LoggedInUser extends RecordModel {
id: string;
email: string;
emailVisibility: boolean;
verified: boolean;
name: string;
avatar?: string;
created: Date;
updated: Date;
}
const user = ref<LoggedInUser | null>(null);
const loading = ref<boolean>(false);
const error = ref<Error | null>(null);
export const useAuth = () => {
const pb = usePocketbase();
const router = useRouter();
const userCollection = 'users';
const isAuthenticated = computed<boolean>(() => pb.authStore.isValid && !!user.value);
const initAuth = async () => {
user.value = pb.authStore.record as LoggedInUser;
pb.authStore.onChange((_token, model) => (user.value = model as LoggedInUser));
};
const authProviders = async (): Promise<AuthProviderInfo[]> => {
const authMethods = await pb.collection(userCollection).listAuthMethods();
return authMethods.oauth2.enabled ? authMethods.oauth2.providers : [];
};
const login = async (provider: string) => {
loading.value = true;
error.value = null;
try {
const providers = await authProviders();
const providerData = providers.find((p) => p.name === provider);
if (!providerData) {
throw new Error(`${provider} OAuth is not configured`);
}
const response = await pb.collection(userCollection).authWithOAuth2({ provider });
user.value = response.record as LoggedInUser;
} catch (pbError) {
error.value = pbError as Error;
} finally {
loading.value = false;
}
};
const refreshAuth = async () => await pb.collection(userCollection).authRefresh();
const handleOAuthCallback = async () => {
user.value = pb.authStore.record as LoggedInUser;
if (isAuthenticated.value) {
await router.push('/dashboard');
} else {
await router.push('/');
}
};
const logout = () => {
pb.authStore.clear();
user.value = null;
error.value = null;
};
return {
user,
loading,
error,
isAuthenticated,
login,
logout,
initAuth,
refreshAuth,
handleOAuthCallback,
authProviders,
};
};

View File

@@ -1,8 +1,8 @@
export const usePageTitle = () => {
const pageName = useState<string>('pageName', () => '');
const title = computed<string>(() => (pageName.value.length > 0 ? `${pageName.value} - Tímmál` : 'Tímmál'));
const pageName = useState<string | null>('pageName', () => null);
const title = computed<string>(() => ((pageName.value ?? '').length > 0 ? `${pageName.value} - Tímmál` : 'Tímmál'));
const setPageName = (newName: string) => {
const setPageName = (newName: string | null) => {
pageName.value = newName;
useHead({ title: title.value });
};

View File

@@ -0,0 +1,15 @@
import PocketBase from 'pocketbase';
let pbInstance: PocketBase | null = null;
export const usePocketbase = () => {
if (!pbInstance) {
const config = useRuntimeConfig();
pbInstance = new PocketBase(config.pocketbaseUrl || 'http://localhost:8090');
if (import.meta.server) {
pbInstance.autoCancellation(false);
}
}
return pbInstance;
};

View File

@@ -1,9 +1,9 @@
<template>
<UDashboardGroup>
<UiSidebar />
<UiSidebar class="min-w-60" />
<UDashboardPanel>
<template #header>
<UDashboardNavbar :title="pageName">
<UDashboardNavbar :title="pageName ?? ''">
<template #right>
<UColorModeButton />
</template>

View File

@@ -0,0 +1,156 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { mockNuxtImport } from '@nuxt/test-utils/runtime';
import type { RouteLocationNormalized } from 'vue-router';
/**
* Tests for auth middleware
* Based on specs from private/specs.md:
*
* Scenario: Access protected page without auth
* Given I am not logged in
* When I try to access "/dashboard"
* Then I should be redirected to "/login"
*/
// Create mocks at module level to avoid hoisting issues
const mockState = {
isAuthenticated: false,
navigateToSpy: vi.fn(),
};
// Mock useAuth
mockNuxtImport('useAuth', () => {
return () => ({
isAuthenticated: {
get value() {
return mockState.isAuthenticated;
},
},
});
});
// Mock navigateTo
mockNuxtImport('navigateTo', () => {
return (path: string) => mockState.navigateToSpy(path);
});
describe('auth middleware', () => {
beforeEach(async () => {
// Reset state
mockState.isAuthenticated = false;
mockState.navigateToSpy.mockClear();
});
it('should redirect to /login when user is not authenticated', async () => {
mockState.isAuthenticated = false;
const { default: authMiddleware } = await import('../auth.global');
const to = {
path: '/dashboard',
fullPath: '/dashboard',
} as RouteLocationNormalized;
const from = {
path: '/',
fullPath: '/',
} as RouteLocationNormalized;
await authMiddleware(to, from);
expect(mockState.navigateToSpy).toHaveBeenCalledWith({
path: '/login',
query: {
redirect: '/dashboard',
},
});
});
it('should allow access when user is authenticated', async () => {
mockState.isAuthenticated = true;
const { default: authMiddleware } = await import('../auth.global');
const to = {
path: '/dashboard',
fullPath: '/dashboard',
} as RouteLocationNormalized;
const from = {
path: '/login',
fullPath: '/login',
} as RouteLocationNormalized;
const result = await authMiddleware(to, from);
expect(mockState.navigateToSpy).not.toHaveBeenCalled();
expect(result).toBeUndefined(); // No redirect = allow access
});
it('should not redirect if already on login page', async () => {
mockState.isAuthenticated = false;
const { default: authMiddleware } = await import('../auth.global');
const to = {
path: '/login',
fullPath: '/login',
} as RouteLocationNormalized;
const from = {
path: '/dashboard',
fullPath: '/dashboard',
} as RouteLocationNormalized;
const result = await authMiddleware(to, from);
expect(mockState.navigateToSpy).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
it('should allow access to home page without authentication', async () => {
mockState.isAuthenticated = false;
const { default: authMiddleware } = await import('../auth.global');
const to = {
path: '/',
fullPath: '/',
} as RouteLocationNormalized;
const from = {
path: '/somewhere',
fullPath: '/somewhere',
} as RouteLocationNormalized;
const result = await authMiddleware(to, from);
expect(mockState.navigateToSpy).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
it('should redirect to /login for any protected route', async () => {
mockState.isAuthenticated = false;
const { default: authMiddleware } = await import('../auth.global');
const to = {
path: '/projects',
fullPath: '/projects',
} as RouteLocationNormalized;
const from = {
path: '/',
fullPath: '/',
} as RouteLocationNormalized;
await authMiddleware(to, from);
expect(mockState.navigateToSpy).toHaveBeenCalledWith({
path: '/login',
query: {
redirect: '/projects',
},
});
});
});

View File

@@ -0,0 +1,14 @@
export default defineNuxtRouteMiddleware((to, _from) => {
const { isAuthenticated } = useAuth();
const allowedUnauthenticatedPaths: string[] = ['/', '/login'];
if (allowedUnauthenticatedPaths.find((p) => p === to.path)) {
return;
}
if (!isAuthenticated.value) {
return navigateTo({
path: '/login',
query: { redirect: to.fullPath },
});
}
return;
});

37
app/pages/login.vue Normal file
View File

@@ -0,0 +1,37 @@
<template>
<div>
<UPageHero title="Tímmál" />
<UPageSection id="login" title="Log in to your account" description="Welcome back to your workspace">
<div class="full-w flex justify-center">
<div class="flex flex-1 gap-3 max-w-200 flex-col items-stretch px-4 py-3 justify-center">
<UAlert
v-if="error"
title="Something went wrong!"
description="We couldn't log you in due to an error. Try again later. If the issue persists, try contacting the website's administrator."
color="error"
icon="i-lucide-circle-alert"
/>
<AuthOAuthProvider v-for="provider of providers" :key="provider.name" :provider="provider" />
</div>
</div>
</UPageSection>
</div>
</template>
<script lang="ts" setup>
definePageMeta({
layout: 'unauthenticated',
});
const route = useRoute();
const redirectPath = (route.query.redirect as string) || '/dashboard';
const { authProviders, error, isAuthenticated } = useAuth();
const providers = await authProviders();
watch(isAuthenticated, (authenticated) => {
if (authenticated) {
navigateTo(redirectPath);
}
});
</script>

View File

@@ -1,11 +0,0 @@
<template>
<UPage>
<span> Signin </span>
</UPage>
</template>
<script lang="ts" setup>
definePageMeta({
layout: 'unauthenticated',
});
</script>