Skip to content

Commit

Permalink
feat: connect SSO after login (#58)
Browse files Browse the repository at this point in the history
Giving the ability for users to connect their SSO after creating
accounts using passwords, simply by going to the account page and click
the button "Link my account with [provider]"

Closes: #52
  • Loading branch information
kimlimjustin committed Jun 17, 2024
1 parent b89e1be commit e6cfc54
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 6 deletions.
21 changes: 18 additions & 3 deletions src/routes/auth/v1/account/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { PageServerLoad } from './$types';
import { backendFetch } from '$lib/backend';
import { getSession } from '$lib/rauthy/server';
import { checkResponse } from '$lib/utils';

export interface Provider {
id: string;
name: string;
}

export interface Profile {
username?: string;
Expand All @@ -16,14 +22,23 @@ export interface Profile {
export type WorkCapacity = 'full_time' | 'part_time';
export type WorkCompensation = 'paid' | 'volunteer';

export const load: PageServerLoad = async ({ fetch, request }): Promise<{ profile?: Profile }> => {
export const load: PageServerLoad = async ({ fetch, request }): Promise<{ profile?: Profile, providers: Provider[] }> => {
let providers: Provider[] = [];
try {
const providersResp = await fetch('/auth/v1/providers/minimal');
await checkResponse(providersResp);
providers = await providersResp.json();
} catch (e) {
console.error('Error getting providers:', e);
}

let { userInfo } = await getSession(fetch, request);
if (userInfo) {
const resp = await backendFetch(fetch, `/profile/${userInfo.id}`);
const profile: Profile = await resp.json();

return { profile };
return { profile, providers };
} else {
return {};
return {providers};
}
};
44 changes: 44 additions & 0 deletions src/routes/auth/v1/account/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { env } from '$env/dynamic/public';
const { data }: { data: PageData } = $props();
const providers = data.providers;
const userInfo = getUserInfo();
const PKCE_VERIFIER = 'pkce_verifier';
Expand Down Expand Up @@ -64,6 +65,40 @@
});
}
});
const providerLinkPkce = async (provider_id: string, pkce_challenge: string) => {
const data = {
pkce_challenge,
redirect_uri: window.location.href,
client_id: 'rauthy',
email: userInfo?.email,
provider_id,
}
await fetch(`/auth/v1/providers/${provider_id}/link`, {
method: 'POST',
headers: [['csrf-token', localStorage.getItem('csrfToken')!]],
body: JSON.stringify(data),
}).then(() => {
getPkce(64, async (error, { challenge, verifier }) => {
if (!error) {
localStorage.setItem(PKCE_VERIFIER, verifier);
const nonce = getKey(24);
const s = 'account';
const redirect_uri = encodeURIComponent(`${window.location.origin}/auth/v1/oidc/callback`);
window.location.href = `/auth/v1/oidc/logout?post_logout_redirect_uri=%2Fauth%2Fv1%2Foidc%2Fauthorize%3Fclient_id%3Drauthy%26redirect_uri%3D${redirect_uri}%26response_type%3Dcode%26code_challenge%3D${challenge}%26code_challenge_method%3DS256%26scope%3Dopenid%2Bprofile%2Bemail%26nonce%3D${nonce}%26state%3D${s}`;
}
});
})
.catch(err => console.log(err, 'a'))
}
const AddProvider = (provider_id: string) => {
getPkce(64, (error, { challenge, verifier }) => {
if(!error){
localStorage.setItem('pkceVerifierUpstream', verifier);
providerLinkPkce(provider_id, challenge);
}
})
}
</script>

<svelte:head>
Expand Down Expand Up @@ -97,6 +132,15 @@
</span>
</div>
</div>
{#if providers && userInfo.account_type === 'password'}
{#each providers as provider}
<button onclick={(e) => {
e.preventDefault();
AddProvider(provider.id)
}} class="variant-ghost btn">Link my account with {provider.name}</button>
{/each}
{/if}
<!-- <button onclick={AddProvider} class="variant-ghost btn">Log in anyway</button> -->

<label class="label">
<span>Username</span>
Expand Down
6 changes: 3 additions & 3 deletions src/routes/auth/v1/oidc/logout/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
onMount(async () => {
const url = new URL(window.location.href);
const postLogoutUri = url.searchParams.get('post_logout_redirect_uri');
const postLogoutUri = decodeURIComponent(url.searchParams.get('post_logout_redirect_uri') || '/');
const token = url.searchParams.get('id_token_hint');
const state = url.searchParams.get('state');
const csrf = localStorage.getItem('csrfToken');
const req = {
id_token_hint: token || undefined,
post_logout_redirect_uri: postLogoutUri || '/',
post_logout_redirect_uri: postLogoutUri,
state: state || undefined
};
Expand All @@ -27,7 +27,7 @@
console.log(e);
} finally {
localStorage.removeItem('csrfToken');
window.location.href = postLogoutUri || '/';
window.location.href = postLogoutUri;
}
});
</script>

0 comments on commit e6cfc54

Please sign in to comment.