Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@playwright/test": "^1.28.1",
"@sveltejs/adapter-auto": "^1.0.0",
"@sveltejs/kit": "^1.0.0",
"@types/lodash": "^4.14.191",
"@typescript-eslint/eslint-plugin": "^5.45.0",
"@typescript-eslint/parser": "^5.45.0",
"autoprefixer": "^10.4.13",
Expand All @@ -34,5 +35,10 @@
"vite": "^4.0.0",
"vitest": "^0.25.3"
},
"type": "module"
"type": "module",
"dependencies": {
"firebase": "^9.15.0",
"firebase-admin": "^11.4.0",
"lodash": "^4.17.21"
}
}
7 changes: 6 additions & 1 deletion src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
// and what to do when importing types
declare namespace App {
// interface Error {}
// interface Locals {}
interface Locals {
user: null | {
uid: string;
email?: string;
};
}
// interface PageData {}
// interface Platform {}
}
16 changes: 16 additions & 0 deletions src/components/AuthStatus.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script lang="ts">
import { auth } from "../stores/auth";
</script>

<div class="my-4">
{#if $auth}
<div class="text-gray-400">
Authenticated as <span class="font-bold text-black">{$auth.email}</span>
</div>
{:else}
<div class="text-gray-400">
No one is authenticated
</div>
{/if}
</div>

18 changes: 18 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Handle } from '@sveltejs/kit';
import cookie from 'cookie';
import { decodeToken } from '$lib/server/firebase';
import { SESSION_COOKIE_NAME } from '$lib/constants';

export const handle = (async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');

const token = cookies[SESSION_COOKIE_NAME];
if (token) {
const decodedToken = await decodeToken(token);
if (decodedToken) {
event.locals.user = decodedToken;
}
}

return resolve(event);
}) satisfies Handle;
26 changes: 26 additions & 0 deletions src/lib/client/firebase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Import the functions you need from the SDKs you need
import { memoize } from 'lodash';
import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
import { getAuth } from 'firebase/auth';

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: 'AIzaSyC_UMni0U3jBJJ4VZEZtuGhHveffKbQDyA',
authDomain: 'svelte-examples.firebaseapp.com',
projectId: 'svelte-examples',
storageBucket: 'svelte-examples.appspot.com',
messagingSenderId: '918304336401',
appId: '1:918304336401:web:aa984db8c26e706eb0dfb0',
measurementId: 'G-K2FDD80558'
};

// Initialize Firebase
export const initFirebase = memoize(() => {
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth(app);

return { app, analytics, auth };
});
1 change: 1 addition & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const SESSION_COOKIE_NAME = 'svelte-examples-session';
27 changes: 27 additions & 0 deletions src/lib/server/firebase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { FIREBASE_ADMIN_SDK_KEY } from '$env/static/private';
import admin from 'firebase-admin';
import type { DecodedIdToken } from 'firebase-admin/lib/auth/token-verifier';

const initializeFirebase = () => {
if (!admin.apps.length) {
const serviceAccount = JSON.parse(FIREBASE_ADMIN_SDK_KEY);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
}
};

export async function decodeToken(token: string): Promise<DecodedIdToken | null> {
if (!token) {
return null;
}

try {
initializeFirebase();

return await admin.auth().verifyIdToken(token);
} catch (err) {
console.error('An error occurred validating token', (err as Error).message);
return null;
}
}
5 changes: 5 additions & 0 deletions src/routes/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { LayoutServerLoad } from './$types';
export const load = (async (event) => {
const user = event.locals.user;
return { user };
}) satisfies LayoutServerLoad;
10 changes: 8 additions & 2 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<script>
import Navbar from '../ui/Navbar.svelte';
<script lang="ts">
import '../app.css';
import { onMount } from 'svelte';
import { initFirebase } from '$lib/client/firebase';
import { onAuthStateChanged, getAuth } from 'firebase/auth';
import { auth } from '../stores/auth'
import Navbar from '../ui/Navbar.svelte';

onMount(initFirebase);
</script>

<Navbar />
Expand Down
6 changes: 6 additions & 0 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
<script>
import AuthStatus from "../components/AuthStatus.svelte";

</script>
<div class="container mx-auto mt-8">
<h1 class="text-4xl mb-4">Welcome to SvelteKit</h1>
<p>Visit <a class="text-blue-600 hover:text-blue-700 hover:underline" rel="noopener noreferrer" target="_blank" href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

<AuthStatus />
</div>
23 changes: 23 additions & 0 deletions src/routes/login/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { SESSION_COOKIE_NAME } from '$lib/constants';
import { fail } from '@sveltejs/kit';
import type { Actions } from './$types';

export const actions: Actions = {
default: async ({ request, cookies }) => {
const formData = await request.formData();

const token = formData.get('token')?.valueOf();

if (!token || typeof token !== 'string') {
return fail(400, { message: 'Token is a required field and must be a string' });
}

cookies.set(SESSION_COOKIE_NAME, token, {
httpOnly: true,
path: '/',
secure: true
});

return { success: true };
}
};
116 changes: 116 additions & 0 deletions src/routes/login/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<script lang="ts">
import { applyAction, deserialize } from "$app/forms";
import { goto, invalidateAll } from "$app/navigation";
import type { ActionResult } from "@sveltejs/kit";
import { getAuth, signInWithEmailAndPassword, type User, type UserCredential } from "firebase/auth";
import { onMount } from "svelte";
import { auth } from '../../stores/auth'
import type { ActionData } from "./$types";

export let form: ActionData;

onMount(() => {
return auth.subscribe((user) => {
if (user) {
goto('/')
}
});
});

const login = async (email: string | undefined, password: string | undefined): Promise<ActionResult<{credential: UserCredential}, Record<string, string>>> => {
if (!email || !password) {
return { type: 'failure', status: 400, data: { message: 'Email or password are missing' }}
}

const auth = getAuth();

try {
const credential = await signInWithEmailAndPassword(auth, email, password);
return {
type: 'success',
status: 200,
data: { credential },
}
} catch (error) {
return {
type: 'failure',
status: 403,
data: { message: (error as Error).message }
}
}

}

async function handleSubmit(this: HTMLFormElement, event: unknown): Promise<void> {
const formData = new FormData(this);

const email = formData.get('email')?.toString();
const password = formData.get('password')?.toString();

try {
const loginResult = await login(email, password);

if (loginResult.type !== 'success') {
applyAction(loginResult);

return;
}

const { data } = loginResult;
if (!data?.credential) {
throw new Error('Login returned success but no user credential data');
}

const { credential: { user } } = data;
formData.set('token', await user.getIdToken());

const response = await fetch(this.action, {
method: 'POST',
body: formData,
});

const result = deserialize(await response.text());

if (result.type === 'success') {
await invalidateAll();
}
} catch (error) {
applyAction({
type: 'error',
error,
});
}
}
</script>


<div class="container mt-8 mx-auto">
<div class="w-1/3 mx-auto">
{#if form && !form.success && form.message}
<div class="text-red-700">
{form.message}
</div>
{/if}

<form class="mt-4" method="POST" on:submit|preventDefault="{handleSubmit}">
<div>
<label>
Email
<input class="block border border-gray-400 rounded py-1 px-2 mt-2 mb-4 w-full" name="email" type="email" required />
</label>
</div>
<div>
<label>
Password
<input class="block border border-gray-400 rounded py-1 px-2 mt-2 mb-4 w-full" name="password" type="password" required />
</label>
</div>

<div>
<button class="block mx-auto bg-indigo-700 hover:bg-indigo-600 text-gray-200 hover:text-white rounded py-2 px-4" type="submit">
Submit
</button>
</div>
</form>
</div>
</div>
15 changes: 15 additions & 0 deletions src/routes/logout/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { SESSION_COOKIE_NAME } from '$lib/constants';
import type { RequestHandler } from '@sveltejs/kit';
import cookie from 'cookie';

export const POST = (async () => {
return new Response('', {
headers: {
'set-cookie': cookie.serialize(SESSION_COOKIE_NAME, '', {
path: '/',
httpOnly: true,
maxAge: -1
})
}
});
}) satisfies RequestHandler;
21 changes: 21 additions & 0 deletions src/stores/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { page } from '$app/stores';
import { derived } from 'svelte/store';

type User = {
uid: string;
email?: string;
};

export const auth = derived<typeof page, User | null>(
page,
($page, set) => {
const { user } = $page.data;
if (!user) {
set(null);
return;
}

set(user);
},
null
);
22 changes: 22 additions & 0 deletions src/ui/Navbar.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
<script lang="ts">
import { invalidateAll } from '$app/navigation';
import { getAuth, signOut } from 'firebase/auth';
import { auth } from '../stores/auth'

const logout = async () => {
const firebaseAuth = getAuth();
await signOut(firebaseAuth);
await fetch('/logout', { method: 'POST' });
await invalidateAll();
}

</script>
<div class="bg-slate-700">
<div class="container flex items-center mx-auto py-4 text-gray-400">
<div class="mr-12">
Expand All @@ -14,5 +27,14 @@
<a href="/contact" class="hover:text-gray-300">Contact</a>
</div>
</div>
<div>
{#if $auth !== null}
<button class="hover:text-gray-300" on:click={logout}>
Log out
</button>
{:else}
<a href="/login" class="hover:text-gray-300">Log in</a>
{/if}
</div>
</div>
</div>
Loading