Skip to content

Instantly share code, notes, and snippets.

@paolodina
Created July 31, 2023 12:42
Show Gist options
  • Save paolodina/653e0609c8268f5d7081fb30728e9a3b to your computer and use it in GitHub Desktop.
Save paolodina/653e0609c8268f5d7081fb30728e9a3b to your computer and use it in GitHub Desktop.
Access auth info in (every) component
// src/routes/+layout.server.ts
// Ref. https://discord.com/channels/1004048134218981416/1135138484944900156
export const load = ({ locals }) => {
return {
isLoggedIn: locals.isLoggedIn
};
};
<!--
src/routes/+layout.svelte
Ref. https://discord.com/channels/1004048134218981416/1135138484944900156
-->
<script lang="ts">
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
export let data;
const userLoggedIn = writable<boolean>();
$: userLoggedIn.set(data.isLoggedIn);
setContext('userLoggedIn', userLoggedIn);
};
</script>
// Ref. https://discord.com/channels/1004048134218981416/1135138484944900156
import type { Session } from 'lucia';
declare global {
namespace App {
interface Locals {
auth: import('lucia').AuthRequest;
isLoggedIn: boolean;
}
}
namespace Lucia {
type Auth = import('$lib/server/lucia').Auth;
type DatabaseUserAttributes = {
username: string;
};
type DatabaseSessionAttributes = Record<string, string>;
}
}
export {};
// Ref. https://discord.com/channels/1004048134218981416/1135138484944900156
import { auth } from '$lib/server/lucia';
export const handle = async ({ event, resolve }) => {
event.locals.auth = auth.handleRequest(event);
// I need to add if the user is logged in or not:
const session = await event.locals.auth.validate();
event.locals.isLoggedIn = session?.user.userId ? true : false;
return await resolve(event);
};
<!--
Wherever this component lives, we have access to user auth info.
Ref. https://discord.com/channels/1004048134218981416/1135138484944900156
-->
<script lang="ts">
import { getContext } from 'svelte';
import type { Writable } from 'svelte/store';
const userLoggedIn: Writable<boolean> = getContext('userLoggedIn');
</script>
userLoggedIn: {$userLoggedIn}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment