Svelte
Handle authentication with Secrecy in a Svelte app
Get an authenticated Secrecy client
First initialize the Secrecy library with setup
method. if it hasn't been done yet.
Then, attempt to retrieve an authenticated client, either from the current session or local storage with getSecrecyClient
.
If no client is found, initiates a login process with the login
. Finally, on success the client SecrecyClient
is returned.
If there's an error or the login is not completed, it returns null.
App.svelte
<script>
import { onMount } from 'svelte';
import { getSecrecyClient, login, setup } from '@secrecy/lib';
let client = null;
onMount(() => {
// Check if client is already initialized
if (client !== null) {
return;
}
// Initialize the Secrecy library
setup();
// Attempt to retrieve an authenticated client from the current session or local storage
const sessionClient = getSecrecyClient(true);
const localStorageClient = getSecrecyClient(false);
const storedClient = sessionClient ?? localStorageClient;
// If a client is found from the session or local storage, store it
if (storedClient) {
client = storedClient;
return;
}
// If no client is found, initiate the secrecy login process
login({
appId: import.meta.env.VITE_SECRECY_APP_ID, // Ensure app ID is properly configured in your environment
redirect: true,
path: window.location.pathname,
scopes: {
email: true,
},
backPath: document.referrer,
})
.then((newClient) => {
// On success, store the client in the state
client = newClient;
})
.catch((e) => {
console.error(e);
});
});
</script>
{#if client}
<p>Client authenticated</p>
{:else}
<p>Authenticating...</p>
{/if}
<style scoped>
/* Optional styling */
</style>
Get user from Secrecy client
The method secrecyClient.me
is used for fetching the user's data once the client is initialized to get the user data. It returns a SelfUser
object.
App.svelte
<script>
import { onMount } from 'svelte';
import type { SelfUser, SecrecyClient } from '@secrecy/lib';
// Reactive variables for user and client states
let user = null;
let client = null;
// Function to fetch user details when client is available
function fetchUserDetails() {
if (client && !user) {
client.me()
.then((fetchedUser) => {
user = fetchedUser;
})
.catch((e) => {
console.error(e);
});
}
}
// Run this when the component mounts
onMount(() => {
// Optionally set up `client` here, if not done elsewhere in the app.
fetchUserDetails();
});
// Reactive statement to call fetchUserDetails when client changes
$: if (client && !user) {
fetchUserDetails();
}
</script>
{#if user}
<p>User authenticated: {user.name}</p>
{:else}
<p>Authenticating user...</p>
{/if}
<style scoped>
/* Optional styling */
</style>