Skip to content

Instantly share code, notes, and snippets.

@peterpeterparker
Last active February 17, 2024 17:28
Show Gist options
  • Save peterpeterparker/43c087610687862c9c3ae4f3fe22018e to your computer and use it in GitHub Desktop.
Save peterpeterparker/43c087610687862c9c3ae4f3fe22018e to your computer and use it in GitHub Desktop.
Integrating Internet Identity into a Client App: The Basics
/**
*
* Simplified Gist to showcase the basics of how to intergrate Internet Identity with agent-js in a frontend app.
*
* - Sign-in
* - Sign-out
* - Sync
*
*/
import { AuthClient } from '@dfinity/auth-client';
// I disable the idle callback because I've got a custom observer that sign-out the user automatically when the session is over. This observer is not described in this Gist therefore, you might want to not disable those options. Your call.
const authClient = await AuthClient.create({
idleOptions: {
disableIdle: true,
disableDefaultIdleCallback: true
}
});
/**
* Sign-in
*/
const II_CANISTER_ID = 'the-canister-id-from-the-environment';
const DEV = true; // a flag to detect if we are developing locally or on mainnet
// Safari does not support subdomain for localhost. Chrome requires subdomain for the canister ID. Therefore the check navigator checks for local development.
const identityProvider =
DEV
? /apple/i.test(navigator?.vendor)
? `http://localhost:4943?canisterId=${II_CANISTER_ID}`
: `http://${II_CANISTER_ID}.localhost:4943`
: `https://identity.ic0.app'`; // Replace with https://identity.internetcomputer.org' if you prefer that domain
// How long the delegation identity - session - should remain valid?
// e.g. BigInt(60 * 60 * 1000 * 1000 * 1000) = 1 hour in nanoseconds
const AUTH_MAX_TIME_TO_LIVE = BigInt(60 * 60 * 1000 * 1000 * 1000);
await authClient.login({
maxTimeToLive: AUTH_MAX_TIME_TO_LIVE,
onSuccess: () => {
// Here the user is signed-in, we can retrieve its identity
console.log(authClient.getIdentity());
},
onError: (error?: string) => {
if (error === 'UserInterrupt') {
// Here I advise to ignore UserInterrupt error because if the user interupted the sign-in flow, they most probably know it already
// But only my two cents
return;
}
console.error(error);
},
identityProvider
// If you want the sign-in to happen in a popup and not a new window
// windowOpenerFeatures: yourPopupOptions()
});
/**
* Sign-out
*/
await authClient.logout();
// This is a must for Safari otherwise when user does sign-in -> sign-out -> sign-in, II popup/new window will be blocked
window.location.reload();
/**
* Sync
*/
// If a user returns to your app you want to know if the user is sign-in or not - i.e. if the session is still active
const isAuthenticated = await authClient.isAuthenticated();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment