Skip to content

Commit

Permalink
docs: Add session management example for SvelteKit (#6184)
Browse files Browse the repository at this point in the history
* chore(docs): Session management sample for Svelte

Added a code sample for managing the session through the $page store.
The sample demonstrates how to retrieve the session data in the root
+page.server.ts file and make it globally accessible through the $page
store, simplifying state management in the application. The previous
examples already used the data available in this store but did not show
how to set it.

* docs: Add authorization section to SvelteKit docs

This authorization section was added to make sure a few caveats with
SvelteKit were well documented to anyone using the library.

The problem is documented here: sveltejs/kit#6315

Essentially, propagation of data between leafs is not guaranteed when
using the +layout.server.ts file as its load function is not guaranteed
to rerun every page change. The current approach to solve this is to do
authorization in each +page.server.ts file and additionally make sure to
grab the session data by awaiting the parent instead of directly
accessing the $page store, to make sure the information there is
current.

* docs: Fix small typesafety mistake in SvelteKit

PageLoad type should actually be PageServerLoad. Not setting this does
not actually generate any problems other than TypeScript complaining
that this type is not actually exported.

* docs: Add handle hook authorization management

Another way to handle authorization is through a path-based method. This
added part of the documentation uses the handle hook to protect certain
routes based on their path. The previous method which is per-component
is still present.

* docs: Simplify component approach for Svelte auth

Using event.locals.getSession() exposed by SvelteKitAuth instead of
relying in the root layout file making that available in the $page
store.

* docs: Complete SvelteKit authorization docs

Finalize the explanation for the URI-based approach and also clarify
interactions with the component-based approach.

* docs: Add formatting to vars in the SvelteKit docs

Format the variables like this: `var` so that it appears clearly as code
when reading the documentation.

Co-authored-by: Thang Vu <[email protected]>
  • Loading branch information
DoodlesEpic and ThangHuuVu authored Jan 4, 2023
1 parent 8cf4cc2 commit 7c96351
Showing 1 changed file with 108 additions and 0 deletions.
108 changes: 108 additions & 0 deletions packages/frameworks-sveltekit/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
*
* ## Signing in and signing out
*
* The data for the current session in this example was made available through the `$page` store which can be set through you root `+page.server.ts` file.
* It is not necessary to store the data there, however, this makes it globally accessible throughout your application simplifying state management.
*
* ```ts
* <script>
* import { signIn, signOut } from "@auth/sveltekit/client"
Expand Down Expand Up @@ -65,6 +68,111 @@
* </p>
* ```
*
* ## Managing the session
*
* The above example checks for a session available in `$page.data.session`, however that needs to be set by us somewhere.
* If you want this data to be available to all your routes you can add this to your root `+page.server.ts` file.
* The following code sets the session data in the `$page` store to be available to all routes.
*
* ```ts
* import type { LayoutServerLoad } from './$types';
*
* export const load: LayoutServerLoad = async (event) => {
* return {
* session: await event.locals.getSession()
* };
* };
* ```
*
* What you return in the function `LayoutServerLoad` will be available inside the `$page` store, in the `data` property: `$page.data`.
* In this case we return an object with the 'session' property which is what we are accessing in the other code paths.
*
* ## Handling authorization
*
* In SvelteKit there are a few ways you could protect routes from unauthenticated users.
*
* ### Per component
*
* The simplest case is protecting a single page, in which case you should put the logic in the `+page.server.ts` file.
* Notice in this case that you could also await event.parent and grab the session from there, however this implementation works even if you haven't done the above in your root `+layout.server.ts`
*
* ```ts
* import { redirect } from '@sveltejs/kit';
* import type { PageServerLoad } from './$types';
*
* export const load: PageServerLoad = async (event) => {
* const session = await event.locals.getSession();
* if (!session?.user) throw redirect(303, '/auth');
* return {};
* };
* ```
*
* :::danger
* Make sure to ALWAYS grab the session information from the parent instead of using the store in the case of a `PageLoad`.
* Not doing so can lead to users being able to incorrectly access protected information in the case the `+layout.server.ts` does not run for that page load.
* This code sample already implements the correct method by using `const { session } = await parent();`
* :::
*
* You should NOT put authorization logic in a `+layout.server.ts` as the logic is not guaranteed to propragate to leafs in the tree.
* Prefer to manually protect each route through the `+page.server.ts` file to avoid mistakes.
* It is possible to force the layout file to run the load function on all routes, however that relies certain behaviours that can change and are not easily checked.
* For more information about these caveats make sure to read this issue in the SvelteKit repository: https:/sveltejs/kit/issues/6315
*
* ### Per path
*
* Another method that's possible for handling authorization is by restricting certain URIs from being available.
* For many projects this is better because:
* - This automatically protects actions and api routes in those URIs
* - No code duplication between components
* - Very easy to modify
*
* The way to handle authorization through the URI is to override your handle hook.
* The handle hook, available in `hooks.server.ts`, is a function that receives ALL requests sent to your SvelteKit webapp.
* You may intercept them inside the handle hook, add and modify things in the request, block requests, etc.
* Some readers may notice we are already using this handle hook for SvelteKitAuth which returns a handle itself, so we are going to use SvelteKit's sequence to provide middleware-like functions that set the handle hook.
*
* ```ts
* import { SvelteKitAuth } from '@auth/sveltekit';
* import GitHub from '@auth/core/providers/github';
* import { GITHUB_ID, GITHUB_SECRET } from '$env/static/private';
* import { redirect, type Handle } from '@sveltejs/kit';
* import { sequence } from '@sveltejs/kit/hooks';
*
* async function authorization({ event, resolve }) {
* // Protect any routes under /authenticated
* if (event.url.pathname.startsWith('/authenticated')) {
* const session = await event.locals.getSession();
* if (!session) {
* throw redirect(303, '/auth');
* }
* }
*
* // If the request is still here, just proceed as normally
* const result = await resolve(event, {
* transformPageChunk: ({ html }) => html
* });
* return result;
* }
*
* // First handle authentication, then authorization
* // Each function acts as a middleware, receiving the request handle
* // And returning a handle which gets passed to the next function
* export const handle: Handle = sequence(
* SvelteKitAuth({
* providers: [GitHub({ clientId: GITHUB_ID, clientSecret: GITHUB_SECRET })]
* }),
* authorization
* );
* ```
*
* :::info
* Learn more about SvelteKit's handle hooks and sequence [here](https://kit.svelte.dev/docs/modules#sveltejs-kit-hooks-sequence).
* :::
*
* Now any routes under `/authenticated` will be transparently protected by the handle hook.
* You may add more middleware-like functions to the sequence and also implement more complex authorization business logic inside this file.
* This can also be used along with the component-based approach in case you need a specific page to be protected and doing it by URI could be faulty.
*
* ## Notes
*
* :::info
Expand Down

1 comment on commit 7c96351

@vercel
Copy link

@vercel vercel bot commented on 7c96351 Jan 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.