tiding up GoogleAuth

This commit is contained in:
Samuel Andert 2023-07-25 12:16:44 +02:00
parent f2e9100766
commit c47cf1e338
3 changed files with 71 additions and 146 deletions

View File

@ -7,171 +7,99 @@
import { createLitSession } from '$lib/services/createLitSession/createLitSession';
const redirectUri = 'http://localhost:5173/';
let view = 'sign_in';
let error;
let currentProviderType;
let authMethod;
let pkps = [];
let currentPKP;
let sessionSigs;
let isLoading = false;
export let setupLitProvider;
let view = 'sign_in';
let sessionSigs;
let error;
let isLoading = false;
let currentPKP;
let pkps: IRelayPKP[] = [];
let authMethod;
let provider;
onMount(async () => {
provider = await setupLitProvider.setupLitProvider();
isLoading = true;
console.log('Component mounted.');
function logMessage(text, type = 'SYSTEM') {
console.log(text);
createMessage({
text: 'Component mounted.',
text,
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
type
});
}
onMount(async () => {
try {
console.log('Checking if isSignInRedirect...');
if (!authMethod && isSignInRedirect(redirectUri)) {
console.log('Redirect detected, handling...');
createMessage({
text: 'Redirect detected, handling...',
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
provider = await setupLitProvider.setupLitProvider();
logMessage('Component mounted.');
if (!authMethod && isSignInRedirect(redirectUri)) {
logMessage('Redirect detected, handling...');
const providerName = getProviderFromUrl();
if (providerName) {
await handleRedirect(providerName);
} else {
console.error('No provider detected in the URL.');
logMessage('No provider detected in the URL.', 'ERROR');
}
} else {
console.log('No redirect detected.');
createMessage({
text: 'No redirect detected.',
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
logMessage('No redirect detected.');
}
} catch (err) {
console.error(err);
error = err;
view = 'ERROR';
} finally {
isLoading = false;
setError(err);
}
});
async function authWithGoogle() {
isLoading = true;
error = null;
try {
await provider.signIn();
await handleRedirect(ProviderType.Google);
} catch (err) {
error = err;
view = 'ERROR';
} finally {
isLoading = false;
setError(err);
}
}
async function handleRedirect(providerName: string) {
isLoading = true;
createMessage({
text: `Handling redirect for ${providerName}`,
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
logMessage(`Handling redirect for ${providerName}`);
// As we're now using the global provider, we no longer need to fetch it again based on the providerName
currentProviderType = providerName as ProviderType;
if (!provider) throw new Error('Invalid provider.');
authMethod = await provider.authenticate();
await tick();
try {
console.log('Handling redirect...');
view = 'fetching';
pkps = await provider.fetchPKPsThroughRelayer(authMethod);
view = pkps.length > 0 ? 'fetched' : 'NO_PKPS';
if (!provider) {
throw new Error('Invalid provider.');
}
// Get auth method object that has the OAuth token from redirect callback
authMethod = await provider.authenticate();
await tick(); // Allow Svelte to update the view
// Fetch PKPs associated with social account
view = 'fetching';
const fetchedPkps: IRelayPKP[] = await provider.fetchPKPsThroughRelayer(authMethod);
await tick(); // Allow Svelte to update the view
if (fetchedPkps.length > 0) {
pkps = fetchedPkps;
view = 'fetched';
} else {
view = 'NO_PKPS';
}
} catch (err) {
console.error(err);
error = err;
view = 'ERROR';
} finally {
isLoading = false;
}
console.log(`Handling redirect for ${providerName}`);
console.log(`Fetched PKPs: ${pkps.length}`);
createMessage({
text: `Fetched PKPs: ${pkps.length}`,
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
logMessage(`Fetched PKPs: ${pkps.length}`);
}
async function mint() {
isLoading = true;
error = null;
try {
view = 'MINTING';
const newPKP: IRelayPKP = await mintPkp(provider, authMethod); // Ensure provider implements IProvider
const newPKP: IRelayPKP = await mintPkp(provider, authMethod);
pkps = [...pkps, newPKP];
await createSession(newPKP);
view = 'MINTED';
} catch (err) {
console.error(err);
error = err;
view = 'ERROR';
} finally {
isLoading = false;
setError(err);
}
}
async function createSession(pkp: IRelayPKP) {
isLoading = true;
error = null;
try {
console.log('Creating session...');
createMessage({
text: 'Creating session...',
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
view = 'CREATING_SESSION';
logMessage('Creating session...');
view = 'CREATING_SESSION';
sessionSigs = await createLitSession(provider, pkp.publicKey, authMethod);
currentPKP = pkp;
sessionSigs = await createLitSession(provider, pkp.publicKey, authMethod);
currentPKP = pkp;
createMessage({
text: 'Session created.',
sender: '$lib/components/GoogleAuth.svelte',
type: 'SYSTEM'
});
view = 'SESSION_CREATED';
} catch (err) {
console.error(err);
error = err;
view = 'ERROR';
} finally {
isLoading = false;
}
logMessage('Session created.');
view = 'SESSION_CREATED';
}
function setError(err) {
console.error(err);
error = err;
view = 'ERROR';
}
function resetView() {
@ -184,14 +112,12 @@
{#if error}
<h1>Error</h1>
<p>{error.message}</p>
<button on:click={() => resetView()}>Got it</button>
<button on:click={resetView}>Got it</button>
{:else if isLoading}
<h1>Loading...</h1>
{:else if view === 'sign_in'}
<h1>Sign in with Lit</h1>
<button on:click={authWithGoogle}>Google</button>
{:else if view === 'HANDLE_REDIRECT'}
<h1>Handling Google Authentication...</h1>
{:else if view === 'fetching'}
<h1>Fetching your PKPs...</h1>
{:else if view === 'NO_PKPS'}
@ -199,13 +125,9 @@
<button on:click={mint}>Mint a PKP</button>
{:else if view === 'fetched'}
<h1>Select a PKP to continue</h1>
<div>
{#each pkps as pkp}
<button on:click={async () => await createSession(pkp)}>
{pkp.ethAddress}
</button>
{/each}
</div>
{#each pkps as pkp}
<button on:click={async () => await createSession(pkp)}>{pkp.ethAddress}</button>
{/each}
{:else if view === 'MINTING'}
<h1>Minting your PKP...</h1>
{:else if view === 'MINTED'}

View File

@ -7,7 +7,10 @@
const store = getComponentStore(id);
$: console.log('store:', $store);
export let messages;
onMount(async () => {
console.log('messages: ' + JSON.stringify(messages));
console.log('hello Earth');
});
</script>

View File

@ -5,31 +5,31 @@
layout: `
grid-template-areas:
"auth",
"login",
"play",
"hello"
grid-template-rows: auto 1fr 1fr;
"hello",
"google"
grid-template-rows: 1fr 1fr;
`,
children: [
{
id: 'authsig',
componentName: 'AuthSig',
slot: 'auth'
},
{
id: 'wallet1',
componentName: 'Wallet',
slot: 'play',
state: {
rpcURL: 'https://rpc.gnosischain.com/',
pkpPubKey:
'046da3ba67065fd1e2726242ca01cd4601524893f4aa4b0042578fa6cbec28fa8c9a28eb9f7893932fc09717edc9e1db57e157a21eed346247c1db5a722a01f571'
}
},
{
id: 'hello',
componentName: 'GoogleAuth',
componentName: 'HelloEarth',
slot: 'hello',
services: ['messages']
},
// {
// id: 'wallet1',
// componentName: 'Wallet',
// slot: 'play',
// state: {
// rpcURL: 'https://rpc.gnosischain.com/',
// pkpPubKey:
// '046da3ba67065fd1e2726242ca01cd4601524893f4aa4b0042578fa6cbec28fa8c9a28eb9f7893932fc09717edc9e1db57e157a21eed346247c1db5a722a01f571'
// }
// },
{
id: 'google',
componentName: 'GoogleAuth',
slot: 'google',
services: ['setupLitProvider']
}
]