Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: connect SSO after login (closes #52) #58

Merged
merged 2 commits into from
Jun 17, 2024
Merged
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
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 @@ -9,6 +9,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 @@ -56,6 +57,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 @@ -89,6 +124,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>
Loading