Skip to content

Commit

Permalink
fixed custom domain logic
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtisassad committed Nov 20, 2024
1 parent bceca47 commit 2990d53
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 34 deletions.
38 changes: 28 additions & 10 deletions packages/commonwealth/client/scripts/controllers/app/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
} from '@hicommonwealth/shared';
import { CosmosExtension } from '@magic-ext/cosmos';
import { FarcasterExtension } from '@magic-ext/farcaster';
import { OAuthExtension } from '@magic-ext/oauth2';
import { OAuthExtension } from '@magic-ext/oauth';
import { OAuthExtension as OAuthExtensionV2 } from '@magic-ext/oauth2';
import axios from 'axios';
import { notifyError } from 'controllers/app/notifications';
import { getMagicCosmosSessionSigner } from 'controllers/server/sessions';
Expand All @@ -36,11 +37,16 @@ import { z } from 'zod';
import Account from '../../models/Account';
import AddressInfo from '../../models/AddressInfo';
import type BlockInfo from '../../models/BlockInfo';
import { fetchCachedCustomDomain } from '../../state/api/configuration/index';

// need to instantiate it early because the farcaster sdk has an async constructor which will cause a race condition
// if instantiated right before the login is called;
export const defaultMagic = new Magic(process.env.MAGIC_PUBLISHABLE_KEY!, {
extensions: [new FarcasterExtension(), new OAuthExtension()],
extensions: [
new FarcasterExtension(),
new OAuthExtension(),
new OAuthExtensionV2(),
],
});

function storeActiveAccount(account: Account) {
Expand Down Expand Up @@ -307,6 +313,7 @@ async function constructMagic(isCosmos: boolean, chain?: string) {
return new Magic(process.env.MAGIC_PUBLISHABLE_KEY, {
extensions: [
new OAuthExtension(),
new OAuthExtensionV2(),
new CosmosExtension({
// Magic has a strict cross-origin policy that restricts rpcs to whitelisted URLs,
// so we can't use app.chain.meta?.node?.url
Expand All @@ -331,6 +338,8 @@ export async function startLoginWithMagicLink({
}) {
if (!email && !phoneNumber && !provider)
throw new Error('Must provide email or SMS or SSO provider');

const { isCustomDomain } = fetchCachedCustomDomain() || {};
const magic = await constructMagic(isCosmos, chain);

if (email) {
Expand Down Expand Up @@ -368,15 +377,24 @@ export async function startLoginWithMagicLink({
localStorage.setItem('magic_chain', chain!);
localStorage.setItem('magic_redirect_to', window.location.href);

let redirectURI = new URL('/finishsociallogin', window.location.origin)
.href;
if (process.env.APP_ENV === 'production') {
redirectURI = 'https://commonwealth.im/finishsociallogin';
if (isCustomDomain) {
const redirectTo = document.location.pathname + document.location.search;
const params = `?redirectTo=${
redirectTo ? encodeURIComponent(redirectTo) : ''
}&chain=${chain || ''}&sso=${provider}`;
await magic.oauth.loginWithRedirect({
provider,
redirectURI: new URL(
'/finishsociallogin' + params,
window.location.origin,
).href,
});
} else {
await magic.oauth2.loginWithRedirect({
provider,
redirectURI: new URL('/finishsociallogin', window.location.origin).href,
});
}
await magic.oauth2.loginWithRedirect({
provider,
redirectURI,
});

// magic should redirect away from this page, but we return after 5 sec if it hasn't
await new Promise<void>((resolve) => setTimeout(() => resolve(), 5000));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
import { handleSocialLoginCallback } from 'controllers/app/login';
import { useCommonNavigate } from 'navigation/helpers';
import React, { useEffect, useState } from 'react';
import { initAppState } from 'state';
import { useFetchCustomDomainQuery } from 'state/api/configuration';
import useUserStore from 'state/ui/user';
import ErrorPage from 'views/pages/error';
import { PageLoading } from 'views/pages/loading';

const validate = async (
setRoute: (route: string) => void,
isLoggedIn: boolean,
isCustomDomain?: boolean,
) => {
const chain = localStorage.getItem('magic_chain');
const walletSsoSource = localStorage.getItem('magic_provider');
// localstorage for magic v2
let chain = localStorage.getItem('magic_chain');
let walletSsoSource = localStorage.getItem('magic_provider');
// this redirect_to contains the whole url
let redirectTo = localStorage.getItem('magic_redirect_to');

localStorage.removeItem('chain');
localStorage.removeItem('provider');
localStorage.removeItem('redirectTo');

// params for magic v1, only used for custom domains
const params = new URLSearchParams(window.location.search);
const isMagicV1 =
params.get('chain') || params.get('sso') || params.get('redirectTo');
if (isMagicV1) {
chain = params.get('chain');
walletSsoSource = params.get('sso');
// this redirect_to contains the only the path after the domain
redirectTo = params.get('redirectTo');
}

if (redirectTo?.startsWith('/finishsociallogin')) redirectTo = null;

try {
Expand All @@ -28,11 +44,19 @@ const validate = async (
isLoggedIn,
});

const currentDomain = window.location.hostname;
const redirectToUrl = new URL(redirectTo!);
const redirectToDomain = redirectToUrl.hostname;
const isCustomDomain = currentDomain !== redirectToDomain;
if (isMagicV1) {
await initAppState();

if (redirectTo) {
setRoute(redirectTo);
} else if (chain && !isCustomDomain) {
setRoute(`/${chain}`);
} else {
setRoute('/');
}
}

const redirectToUrl = new URL(redirectTo!);
if (!isCustomDomain) {
setRoute(redirectToUrl.pathname);
} else if (redirectTo) {
Expand All @@ -49,23 +73,26 @@ const FinishSocialLogin = () => {
const navigate = useCommonNavigate();
const [validationError, setValidationError] = useState<string>('');
const user = useUserStore();
const { data: domain } = useFetchCustomDomainQuery();

useEffect(() => {
validate(navigate, user.isLoggedIn).catch((error) => {
// useEffect will be called twice in development because of React strict mode,
// causing an error to be displayed until validate() finishes
if (document.location.host === 'localhost:8080') {
return;
}
if (typeof error === 'string') {
setValidationError(error);
} else if (error && typeof error.message === 'string') {
setValidationError(error.message);
} else {
setValidationError('Error logging in, please try again');
}
});
}, [navigate, user.isLoggedIn]);
validate(navigate, user.isLoggedIn, domain?.isCustomDomain).catch(
(error) => {
// useEffect will be called twice in development because of React strict mode,
// causing an error to be displayed until validate() finishes
if (document.location.host === 'localhost:8080') {
return;
}
if (typeof error === 'string') {
setValidationError(error);
} else if (error && typeof error.message === 'string') {
setValidationError(error.message);
} else {
setValidationError('Error logging in, please try again');
}
},
);
}, [domain?.isCustomDomain, navigate, user.isLoggedIn]);

if (validationError) {
return <ErrorPage message={validationError} />;
Expand Down
1 change: 1 addition & 0 deletions packages/commonwealth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"@libp2p/peer-id": "^5.0.4",
"@magic-ext/cosmos": "^12.4.0",
"@magic-ext/farcaster": "^0.16.0",
"@magic-ext/oauth": "^22.17.0",
"@magic-ext/oauth2": "^9.16.0",
"@magic-sdk/admin": "^2.4.1",
"@metamask/detect-provider": "^2.0.0",
Expand Down
16 changes: 13 additions & 3 deletions pnpm-lock.yaml

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

0 comments on commit 2990d53

Please sign in to comment.