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

Expose Wallet Data #29

Merged
merged 6 commits into from
Nov 30, 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
Binary file modified example-dimo-auth/dimo-network-login-with-dimo-0.0.9.tgz
Binary file not shown.
41 changes: 22 additions & 19 deletions example-dimo-auth/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion example-dimo-auth/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {

function App() {
const [permissionsEnabled, setPermissionsEnabled] = useState(false);
const { isAuthenticated, getValidJWT } = useDimoAuthState();
const { isAuthenticated, getValidJWT, email, getEmail, walletAddress } =
useDimoAuthState();

const sampleAbi = [
{
Expand Down Expand Up @@ -1120,6 +1121,14 @@ function App() {
</label>
</div>

{isAuthenticated && (
<div>
<p>Connected User</p>
<p>Wallet Address:{walletAddress}</p>
{email && <p>{email}</p>}
</div>
)}

<div>
<h3>Popup Example</h3>

Expand Down
19 changes: 17 additions & 2 deletions sdk/src/auth/context/DimoAuthContext.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// DimoAuthContext.tsx
import React, { createContext, useContext, useEffect, useState } from "react";
import { getJWTFromCookies } from "../../storage/storageManager";
import { getEmailFromLocalStorage, getJWTFromCookies, getWalletAddressFromLocalStorage } from "../../storage/storageManager";
import { isTokenExpired } from "../../token/tokenManager";

// Define the type of the context
type DimoAuthContextType = {
isAuthenticated: boolean; // Read-only for app developers
walletAddress: string | null;
email: string | null;
getValidJWT: () => string | null;
getEmail: () => string | null;
};

// Create the context
Expand All @@ -29,6 +32,18 @@ export const DimoAuthProvider = ({
children: React.ReactNode;
}) => {
const [isAuthenticated, setAuthenticated] = useState(false);

const hasEmailPermission = !!getEmailFromLocalStorage();
const email = hasEmailPermission ? getEmailFromLocalStorage() : "";
const walletAddress = getWalletAddressFromLocalStorage();

const getEmail = () => {
if (hasEmailPermission) {
return email;
} else {
throw new Error("No permission to access email");
}
};


const getValidJWT = () => {
Expand All @@ -47,7 +62,7 @@ export const DimoAuthProvider = ({
}, []);

return (
<DimoAuthContext.Provider value={{ isAuthenticated, getValidJWT }}>
<DimoAuthContext.Provider value={{ isAuthenticated, getValidJWT, email, getEmail, walletAddress }}>
<DimoAuthUpdaterContext.Provider value={{ setAuthenticated }}>
{children}
</DimoAuthUpdaterContext.Provider>
Expand Down
34 changes: 12 additions & 22 deletions sdk/src/components/BaseDimoButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@ const BaseDimoButton: React.FC<BaseDimoButtonProps> = ({
? "https://login.dev.dimo.org"
: "https://login.dimo.org";

const handleButtonClick = () => {
const basePayload = {
entryState,
onSuccess,
onError,
setAuthenticated,
dimoLogin,
clientId,
redirectUri,
apiKey,
};
const basePayload = {
entryState,
onSuccess,
onError,
setAuthenticated,
dimoLogin,
clientId,
redirectUri,
apiKey,
};

const handleButtonClick = () => {
switch (mode) {
case "popup":
popupAuth(basePayload, payload);
Expand All @@ -72,17 +72,7 @@ const BaseDimoButton: React.FC<BaseDimoButtonProps> = ({
// Trigger embedAuth only once the iframe has fully loaded
const handleIframeLoad = () => {
if (mode === "embed") {
embedAuth({
entryState,
onSuccess,
onError,
setAuthenticated,
dimoLogin,
clientId,
redirectUri,
apiKey,
...payload, // Include dynamic payload data
});
embedAuth(basePayload, payload);
}
};

Expand Down
35 changes: 29 additions & 6 deletions sdk/src/storage/storageManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,36 @@
*/

export const storeJWTInCookies = (jwt: string): void => {
const expirationDate = new Date();
expirationDate.setFullYear(expirationDate.getFullYear() + 10); // Set expiration to 10 years in the future

document.cookie = `dimo_auth_token=${jwt}; expires=${expirationDate.toUTCString()}; path=/`;
const expirationDate = new Date();
expirationDate.setFullYear(expirationDate.getFullYear() + 10); // Set expiration to 10 years in the future

document.cookie = `dimo_auth_token=${jwt}; expires=${expirationDate.toUTCString()}; path=/`;
};

// Utility function to store user properties in localStorage for a given clientId
export const storeWalletAddressInLocalStorage = (
walletAddress: string
): void => {
localStorage.setItem(`dimo_wallet_address`, walletAddress);
};

export const storeEmailInLocalStorage = (email: string): void => {
localStorage.setItem(`dimo_user_email`, email);
};

export const getJWTFromCookies = (): string | null => {
const cookie = document.cookie.split('; ').find(row => row.startsWith(`dimo_auth_token=`));
return cookie ? cookie.split('=')[1] : null;
const cookie = document.cookie
.split("; ")
.find((row) => row.startsWith(`dimo_auth_token=`));
return cookie ? cookie.split("=")[1] : null;
};

export const getWalletAddressFromLocalStorage = (): string | null => {
const walletAddress = localStorage.getItem("dimo_wallet_address");
return walletAddress;
};

export const getEmailFromLocalStorage = (): string | null => {
const email = localStorage.getItem("dimo_user_email");
return email;
};
91 changes: 64 additions & 27 deletions sdk/src/utils/eventHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { EntryState } from "../enums/globalEnums";
import { storeJWTInCookies } from "../storage/storageManager";
import {
storeEmailInLocalStorage,
storeJWTInCookies,
storeWalletAddressInLocalStorage,
} from "../storage/storageManager";
import { BasePayload } from "../types/BasePayload";
import { TransactionData } from "../types/TransactionData";

Expand Down Expand Up @@ -42,7 +46,15 @@ export const handleMessageForPopup = (
return;
}

const { eventType, token, authType, transactionHash, message } = event.data;
const {
eventType,
token,
walletAddress,
email,
authType,
transactionHash,
message,
} = event.data;

if (eventType === "READY") {
// Send only the relevant data based on the payload
Expand All @@ -61,7 +73,6 @@ export const handleMessageForPopup = (
onError(new Error("Popup window not available to send credentials"));
}
}, 0);

}

if (eventType === data.eventType) {
Expand All @@ -74,13 +85,23 @@ export const handleMessageForPopup = (
} else {
onError(new Error("Popup window not available to send credentials"));
}
}, 0);
}, 0);
}

if (authType === "popup" && token) {
storeJWTInCookies(token);
setAuthenticated(true);
onSuccess({ token });
if (authType === "popup") {
if (walletAddress) {
storeWalletAddressInLocalStorage(walletAddress);
}

if (email) {
storeEmailInLocalStorage(email);
}

if (token) {
storeJWTInCookies(token);
setAuthenticated(true);
onSuccess({ token });
}

if (popup && !popup.closed) {
popup.close();
Expand All @@ -106,25 +127,31 @@ export const handleMessageForPopup = (
};

export const handleMessageForEmbed = (basePayload: BasePayload, data: any) => {
const {
entryState,
onSuccess,
onError,
setAuthenticated,
clientId,
redirectUri,
apiKey,
dimoLogin,
} = basePayload;
const embedListener = (event: MessageEvent) => {
const {
entryState,
onSuccess,
onError,
setAuthenticated,
clientId,
redirectUri,
apiKey,
dimoLogin,
} = basePayload;

if (getDomain(event.origin) !== getDomain(dimoLogin)) {
console.warn("Received message from an unknown origin:", event.origin);
return;
}

const { eventType, token, authType, transactionHash, transactionReceipt } =
event.data;
const {
eventType,
token,
walletAddress,
email,
authType,
transactionHash,
transactionReceipt,
} = event.data;

if (eventType === "READY") {
// Once the "READY" message is received, send the credentials
Expand All @@ -150,13 +177,23 @@ export const handleMessageForEmbed = (basePayload: BasePayload, data: any) => {
const dataMessage = { ...data, eventType: data.eventType };

//@ts-ignore
iframe.contentWindow.postMessage(dataMessage, dimoLogin);
}
iframe.contentWindow.postMessage(dataMessage, dimoLogin);
}

if (authType === "embed") {
if (walletAddress) {
storeWalletAddressInLocalStorage(walletAddress);
}

if (authType === "embed" && token) {
storeJWTInCookies(token);
setAuthenticated(true);
onSuccess({ token });
if (email) {
storeEmailInLocalStorage(email);
}

if (token) {
storeJWTInCookies(token);
setAuthenticated(true);
onSuccess({ token });
}
}

if (eventType === "transactionResponse") {
Expand Down