Implement authentication with SIWE #4

Merged
nabarun merged 6 commits from nv-siwe into main 2024-10-18 12:47:12 +00:00
8 changed files with 54 additions and 309 deletions
Showing only changes of commit 249e1079c4 - Show all commits

View File

@ -16,11 +16,11 @@
"apollo-server-core": "^3.13.0",
"apollo-server-express": "^3.13.0",
"cookie-session": "^2.1.0",
"cors": "^2.8.5",
"cors": "2.8.5",
"debug": "^4.3.1",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"express-session": "^1.18.0",
"express-session": "1.18.0",
"fs-extra": "^11.2.0",
"graphql": "^16.8.1",
"luxon": "^3.4.4",
@ -51,7 +51,7 @@
},
"devDependencies": {
"@types/cookie-session": "^2.0.49",
"@types/express-session": "^1.17.10",
"@types/express-session": "1.17.10",
"@types/fs-extra": "^11.0.4",
"better-sqlite3": "^9.2.2",
"copyfiles": "^2.4.1",

View File

@ -69,7 +69,6 @@ router.post('/validate', async (req, res) => {
signature,
});
console.log("VALIDATE CALL",message, signature )
if (!success) {
return res.send({ success, error: 'SIWE verifcation failed' } );
}
@ -90,7 +89,6 @@ router.post('/validate', async (req, res) => {
req.session.address = user.id;
req.session.chainId = data.chainId;
}
console.log("VALIDATE CALL FINISHED", req.session)
res.send({ success });
});

View File

@ -8,7 +8,7 @@ import {
ApolloServerPluginLandingPageLocalDefault,
AuthenticationError,
} from 'apollo-server-core';
import cookieSession from 'cookie-session';
import session from 'express-session';
import { TypeSource } from '@graphql-tools/utils';
import { makeExecutableSchema } from '@graphql-tools/schema';
@ -62,7 +62,6 @@ export const createAndStartServer = async (
}
const user = await service.getUser(address);
return { user };
},
plugins: [
@ -81,20 +80,26 @@ export const createAndStartServer = async (
}),
);
const sessionOptions: session.SessionOptions = {
secret: secret,
resave: false,
saveUninitialized: true,
cookie: {
secure: new URL(appOriginUrl).protocol === 'https:',
// 23 hours (less than 24 hours to avoid sessionSigs expiration issues)
maxAge: 23 * 60 * 60 * 1000,
domain: domain || undefined,
sameSite: new URL(appOriginUrl).protocol === 'https:' ? 'none' : 'lax',
}
};
if (trustProxy) {
// trust first proxy
app.set('trust proxy', 1);
}
app.use(
cookieSession({
secret: secret,
secure: new URL(appOriginUrl).protocol === 'https:',
// 23 hours (less than 24 hours to avoid sessionSigs expiration issues)
maxAge: 23 * 60 * 60 * 1000,
sameSite: new URL(appOriginUrl).protocol === 'https:' ? 'none' : 'lax',
domain: domain || undefined,
}),
session(sessionOptions)
);
server.applyMiddleware({

View File

@ -50,28 +50,24 @@ const router = createBrowserRouter([
path: '/login',
element: <AuthPage />,
},
{
path: '/signup',
element: <AuthPage />,
},
]);
function App() {
// Hacky way of checking session
// TODO: Handle redirect backs
// useEffect(() => {
// fetch(`${baseUrl}/auth/session`, {
// credentials: 'include',
// }).then((res) => {
// if (res.status !== 200) {
// localStorage.clear();
// const path = window.location.pathname;
// if (path !== '/login' && path !== '/signup') {
// window.location.pathname = '/login';
// }
// }
// });
// }, []);
useEffect(() => {
fetch(`${baseUrl}/auth/session`, {
credentials: 'include',
}).then((res) => {
if (res.status !== 200) {
localStorage.clear();
const path = window.location.pathname;
if (path !== '/login') {
window.location.pathname = '/login';
}
}
});
}, []);
return (
<Web3Provider>

View File

@ -1,4 +1,4 @@
import React, { ReactNode } from 'react';
import React, { ReactNode, Suspense } from 'react';
import { SiweMessage, generateNonce } from 'siwe';
import { WagmiProvider } from 'wagmi';
import { arbitrum, mainnet } from 'wagmi/chains';
@ -12,18 +12,17 @@ import type {
} from '@web3modal/core';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// if (!process.env.VITE_WALLET_CONNECT_ID) {
// throw new Error('Error: VITE_WALLET_CONNECT_ID env config is not set');
// }
// TODO: Use environment variable
const WALLET_CONNECT_ID="d37f5a2f09d22f5e3ccaff4bbc93d37c"
const queryClient = new QueryClient();
const axiosInstance = axios.create({
baseURL: 'http://127.0.0.1:8000',
// headers: {
// 'Content-Type': 'application/json',
// 'Access-Control-Allow-Origin': '*',
// },
// withCredentials: true,
// TODO: Use environment variable
baseURL: 'http://localhost:8000',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
withCredentials: true,
});
const metadata = {
name: 'Web3Modal',
@ -78,13 +77,12 @@ const siweConfig = createSIWEConfig({
}
},
signOut: async () => {
// try {
// const { success } = (await axiosInstance.post('/auth/logout')).data;
// return success;
// } catch (error) {
// return false;
// }
return false
try {
const { success } = (await axiosInstance.post('/auth/logout')).data;
return success;
} catch (error) {
return false;
}
},
onSignOut: () => {
window.location.href = '/login';

View File

@ -1,101 +1,6 @@
import { Button } from 'components/shared/Button';
import {
ArrowRightCircleFilledIcon,
GithubIcon,
LinkIcon,
LoaderIcon,
QuestionMarkRoundFilledIcon,
} from 'components/shared/CustomIcon';
import { GoogleIcon } from 'components/shared/CustomIcon/GoogleIcon';
import { DotBorder } from 'components/shared/DotBorder';
import { WavyBorder } from 'components/shared/WavyBorder';
import { useEffect, useState } from 'react';
import { CreatePasskey } from './CreatePasskey';
import { AppleIcon } from 'components/shared/CustomIcon/AppleIcon';
import { KeyIcon } from 'components/shared/CustomIcon/KeyIcon';
import { useToast } from 'components/shared/Toast';
import { Link } from 'react-router-dom';
import { PKPEthersWallet } from '@lit-protocol/pkp-ethers';
import { signInWithEthereum } from 'utils/siwe';
import { useSnowball } from 'utils/use-snowball';
import { logError } from 'utils/log-error';
// type Provider = 'google' | 'github' | 'apple' | 'email' | 'passkey';
type Props = {
onDone: () => void;
};
export const Login = ({ onDone }: Props) => {
// const snowball = useSnowball();
// const [error, setError] = useState<string>('');
// const [provider, setProvider] = useState<Provider | false>(false);
// const loading = snowball.auth.state.loading && provider;
// const loading = provider;
// const { toast } = useToast();
console.log(">>ondone", onDone)
// if (provider === 'email') {
// return <CreatePasskey onDone={onDone} />;
// }
// async function handleSigninRedirect() {
// let wallet: PKPEthersWallet | undefined;
// const { google } = snowball.auth;
// if (google.canHandleOAuthRedirectBack()) {
// setProvider('google');
// console.log('Handling google redirect back');
// try {
// await google.handleOAuthRedirectBack();
// // @ts-ignore
// wallet = await google.getEthersWallet();
// // @ts-ignore
// const result = await signInWithEthereum(1, 'login', wallet);
// if (result.error) {
// setError(result.error);
// setProvider(false);
// wallet = undefined;
// logError(new Error(result.error));
// return;
// }
// } catch (err: any) {
// setError(err.message);
// logError(err);
// setProvider(false);
// return;
// }
// }
// if (apple.canHandleOAuthRedirectBack()) {
// setProvider('apple');
// console.log('Handling apple redirect back');
// try {
// await apple.handleOAuthRedirectBack();
// wallet = await apple.getEthersWallet();
// const result = await signInWithEthereum(1, 'login', wallet);
// if (result.error) {
// setError(result.error);
// setProvider(false);
// wallet = undefined;
// return;
// }
// } catch (err: any) {
// setError(err.message);
// console.log(err.message, err.name, err.details);
// setProvider(false);
// return;
// }
// }
// if (wallet) {
// window.location.pathname = '/';
// }
// }
// useEffect(() => {
// handleSigninRedirect();
// }, []);
export const Login = () => {
return (
<div>
<div className="self-stretch p-3 xs:p-6 flex-col justify-center items-center gap-5 flex">
@ -106,161 +11,8 @@ export const Login = ({ onDone }: Props) => {
<WavyBorder className="self-stretch" variant="stroke" />
<div className="self-stretch p-4 xs:p-6 flex-col justify-center items-center gap-8 flex">
{/* <div className="self-stretch p-5 bg-slate-50 rounded-xl shadow flex-col justify-center items-center gap-6 flex"> */}
{/* <div className="self-stretch flex-col justify-center items-center gap-4 flex">
<KeyIcon />
<div className="self-stretch flex-col justify-center items-center gap-2 flex">
<div className="self-stretch text-center text-sky-950 text-lg font-medium font-display leading-normal">
Got a Passkey?
</div>
<div className="self-stretch text-center text-slate-600 text-sm font-normal font-['Inter'] leading-tight">
Use it to sign in securely without using a password.
</div>
</div>
</div> */}
{/* <div className="self-stretch justify-center items-stretch xxs:items-center gap-3 flex flex-col xxs:flex-row"> */}
{/* <Button
as="a"
leftIcon={<QuestionMarkRoundFilledIcon />}
variant={'tertiary'}
target="_blank"
href="https://safety.google/authentication/passkey/"
>
Learn more
</Button> */}
{/* <Button
rightIcon={
loading && loading === 'passkey' ? (
<LoaderIcon className="animate-spin" />
) : (
<ArrowRightCircleFilledIcon height="16" />
)
}
className="flex-1"
disabled={!!loading}
onClick={async () => {
setProvider('passkey');
}}
>
Sign In with Passkey
</Button> */}
{/* </div> */}
{/* <div className="h-5 justify-center items-center gap-2 inline-flex">
<div className="text-center text-slate-600 text-sm font-normal font-['Inter'] leading-tight">
Lost your passkey?
</div>
<div className="justify-center items-center gap-1.5 flex">
<button className="text-sky-950 text-sm font-normal font-['Inter'] underline leading-tight">
Recover account
</button>
<LinkIcon />
</div>
</div> */}
{/* </div> */}
{/* <div className="self-stretch justify-start items-center gap-8 inline-flex">
<DotBorder className="flex-1" />
<div className="text-center text-slate-400 text-xs font-normal font-['JetBrains Mono'] leading-none">
OR
</div>
<DotBorder className="flex-1" />
</div> */}
<div className="self-stretch flex-col justify-center items-center gap-3 flex">
<w3m-button />
{/* <Button
leftIcon={<GoogleIcon />}
rightIcon={
loading && loading === 'google' ? (
<LoaderIcon className="animate-spin" />
) : null
}
onClick={() => {
setProvider('google');
// snowball.auth.google.startOAuthRedirect();
}}
className="flex-1 self-stretch"
variant={'tertiary'}
disabled={!!loading}
>
Continue with Google
</Button> */}
{/* <Button
leftIcon={<GithubIcon />}
rightIcon={
loading && loading === 'github' ? (
<LoaderIcon className="animate-spin" />
) : null
}
onClick={async () => {
setProvider('github');
// await new Promise((resolve) => setTimeout(resolve, 800));
// setProvider(false);
// toast({
// id: 'coming-soon',
// title: 'Sign-in with GitHub is coming soon!',
// variant: 'info',
// onDismiss() {},
// });
}}
className="flex-1 self-stretch"
variant={'tertiary'}
disabled={!!loading}
>
Continue with GitHub
</Button> */}
{/* <Button
leftIcon={<AppleIcon />}
rightIcon={
loading && loading === 'apple' ? (
<LoaderIcon className="animate-spin text-white" />
) : null
}
onClick={async () => {
setProvider('apple');
// snowball.auth.apple.startOAuthRedirect();
// await new Promise((resolve) => setTimeout(resolve, 800));
// setProvider(false);
// toast({
// id: 'coming-soon',
// title: 'Sign-in with Apple is coming soon!',
// variant: 'info',
// onDismiss() {},
// });
}}
className={`flex-1 self-stretch border-black enabled:bg-black text-white ${
loading && loading === 'apple' ? 'disabled:bg-black' : ''
}`}
variant={'tertiary'}
disabled={!!loading}
>
Continue with Apple
</Button> */}
</div>
<div className="flex flex-col gap-3">
{/* {error && (
<div className="justify-center items-center gap-2 inline-flex">
<div className="text-red-500 text-sm">Error: {error}</div>
</div>
)} */}
{/* <div className="h-5 justify-center items-center gap-2 inline-flex">
<div className="text-center text-slate-600 text-sm font-normal font-['Inter'] leading-tight">
Don't have an account?
</div>
<div className="justify-center items-center gap-1.5 flex">
<Link
to="/signup"
className="text-sky-950 text-sm font-normal font-['Inter'] underline leading-tight"
>
Sign up now
</Link>
</div>
</div> */}
</div>
</div>
</div>

View File

@ -40,11 +40,7 @@ export const SnowballAuth: React.FC = () => {
}
if (screen === 'login') {
return (
<Login
onDone={() => {
setScreen('success');
}}
/>
<Login />
);
}
if (screen === 'success') {

View File

@ -7495,10 +7495,10 @@
"@types/range-parser" "*"
"@types/send" "*"
"@types/express-session@^1.17.10":
version "1.18.0"
resolved "https://registry.yarnpkg.com/@types/express-session/-/express-session-1.18.0.tgz#7c6f25c3604b28d6bc08a2e3929997bbc7672fa2"
integrity sha512-27JdDRgor6PoYlURY+Y5kCakqp5ulC0kmf7y+QwaY+hv9jEFuQOThgkjyA53RP3jmKuBsH5GR6qEfFmvb8mwOA==
"@types/express-session@1.17.10":
version "1.17.10"
resolved "https://registry.yarnpkg.com/@types/express-session/-/express-session-1.17.10.tgz#3a9394f1f314a4c657af3fb1cdb52f00fc207fd2"
integrity sha512-U32bC/s0ejXijw5MAzyaV4tuZopCh/K7fPoUDyNbsRXHvPSeymygYD1RFL99YOLhF5PNOkzswvOTRaVHdL1zMw==
dependencies:
"@types/express" "*"
@ -10416,7 +10416,7 @@ core-util-is@~1.0.0:
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"
integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==
cors@^2.8.5:
cors@2.8.5, cors@^2.8.5:
version "2.8.5"
resolved "https://registry.yarnpkg.com/cors/-/cors-2.8.5.tgz#eac11da51592dd86b9f06f6e7ac293b3df875d29"
integrity sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==
@ -11760,7 +11760,7 @@ express-async-errors@^3.1.1:
resolved "https://registry.yarnpkg.com/express-async-errors/-/express-async-errors-3.1.1.tgz#6053236d61d21ddef4892d6bd1d736889fc9da41"
integrity sha512-h6aK1da4tpqWSbyCa3FxB/V6Ehd4EEB15zyQq9qe75OZBp0krinNKuH4rAY+S/U/2I36vdLAUFSjQJ+TFmODng==
express-session@^1.18.0:
express-session@1.18.0:
version "1.18.0"
resolved "https://registry.yarnpkg.com/express-session/-/express-session-1.18.0.tgz#a6ae39d9091f2efba5f20fc5c65a3ce7c9ce16a3"
integrity sha512-m93QLWr0ju+rOwApSsyso838LQwgfs44QtOP/WBiwtAgPIo/SAh1a5c6nn2BR6mFNZehTpqKDESzP+fRHVbxwQ==