backend:
actor {
public shared (msg) func whoami() : async Principal {
msg.caller;
};
};
front end context
import { AuthClient } from “@dfinity/auth-client”;
import React, { createContext, useContext, useEffect, useState } from “react”;
const AuthContext = createContext();
const defaultOptions = {
/**
- @type {import(“@dfinity/auth-client”).AuthClientCreateOptions}
/
createOptions: {
idleOptions: {
// Set to true if you do not want idle functionality
disableIdle: true,
},
},
/* - @type {import(“@dfinity/auth-client”).AuthClientLoginOptions}
*/
loginOptions: {
identityProvider:
process.env.DFX_NETWORK === “ic”
? “https://identity.ic0.app”
:http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943
,
},
};
/**
*
- @param options - Options for the AuthClient
- @param {AuthClientCreateOptions} options.createOptions - Options for the AuthClient.create() method
- @param {AuthClientLoginOptions} options.loginOptions - Options for the AuthClient.login() method
- @returns
*/
export const useAuthClient = (options = defaultOptions) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [authClient, setAuthClient] = useState(null);
const [identity, setIdentity] = useState(null);
const [principal, setPrincipal] = useState(null);
useEffect(() => {
// Initialize AuthClient
AuthClient.create(options.createOptions).then(async (client) => {
updateClient(client);
});
}, );
const login = () => {
authClient.login({
…options.loginOptions,
onSuccess: () => {
updateClient(authClient);
},
});
};
async function updateClient(client) {
try {
const isAuthenticated = await client.isAuthenticated();
setIsAuthenticated(isAuthenticated);
const identity = client.getIdentity();
setIdentity(identity);
const principal = identity.getPrincipal();
setPrincipal(principal);
console.log("this is the object", JSON.stringify(identity));
console.log('is authenticated id is ', JSON.stringify(principal));
setAuthClient(client);
} catch (error) {
console.error("Error updating client:", error);
// Handle error gracefully
}
}
async function logout() {
try {
await authClient?.logout();
await updateClient(null); // Reset the state
} catch (error) {
console.error(“Error logging out:”, error);
// Handle error gracefully
}
}
return {
isAuthenticated,
login,
logout,
authClient,
identity,
principal
};
};
/**
- @type {React.FC}
*/
export const AuthProvider = ({ children }) => {
const auth = useAuthClient();
return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;
};
export const useAuth = () => useContext(AuthContext);