forked from cerc-io/snowballtools-base
Implement authentication with SIWE (#99)
* Create web3 modal provider with SIWE * Add auth router to handle SIWE authentication * Use axios instance to make request * Add button for SIWE authentication * Add changes to access session in web-app GQL requests * Add auth check in GQL context and load/create user * Use authenticated user from context * Redirect to sign in page if unauthenticated and logout button * Change sign-in route to login * Get project domain from config file * Set user ethAddress column as unique * Use formatted user name * Get session secret and origin url from config file * Add unique constraint for eth address * Get secure and samesite from origin url * Get wallet connect id and backend url from env file * Format user email in member tab panel * Add backend config isProduction to set trust proxy * Use only one server url config * Add tool tip for displaying email * Add trustProxy and domain in server.session config * Add SERVER_GQL_PATH constant in frontend --------- Co-authored-by: neeraj <neeraj.rtly@gmail.com>
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
REACT_APP_GQL_SERVER_URL = 'http://localhost:8000/graphql'
|
||||
REACT_APP_SERVER_URL = 'http://localhost:8000'
|
||||
|
||||
REACT_APP_GITHUB_CLIENT_ID =
|
||||
REACT_APP_GITHUB_TEMPLATE_REPO =
|
||||
|
||||
REACT_APP_WALLET_CONNECT_ID =
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@material-tailwind/react": "^2.1.7",
|
||||
"@tanstack/react-query": "^5.22.2",
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
@@ -11,7 +12,10 @@
|
||||
"@types/node": "^16.18.68",
|
||||
"@types/react": "^18.2.42",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@web3modal/siwe": "^4.0.5",
|
||||
"@web3modal/wagmi": "^4.0.5",
|
||||
"assert": "^2.1.0",
|
||||
"axios": "^1.6.7",
|
||||
"date-fns": "^3.0.1",
|
||||
"downshift": "^8.2.3",
|
||||
"eslint-config-react-app": "^7.0.1",
|
||||
@@ -29,9 +33,12 @@
|
||||
"react-router-dom": "^6.20.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"react-timer-hook": "^3.0.7",
|
||||
"siwe": "^2.1.4",
|
||||
"typescript": "^4.9.5",
|
||||
"usehooks-ts": "^2.10.0",
|
||||
"vertical-stepper-nav": "^1.0.2",
|
||||
"viem": "^2.7.11",
|
||||
"wagmi": "^2.5.7",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
projectsRoutesWithoutSearch,
|
||||
} from './pages/org-slug/projects/routes';
|
||||
import ProjectSearchLayout from './layouts/ProjectSearch';
|
||||
import { OctokitProvider } from './context/OctokitContext';
|
||||
import Index from './pages';
|
||||
import Login from './pages/Login';
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
@@ -44,14 +44,14 @@ const router = createBrowserRouter([
|
||||
path: '/',
|
||||
element: <Index />,
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
element: <Login />,
|
||||
},
|
||||
]);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<OctokitProvider>
|
||||
<RouterProvider router={router} />
|
||||
</OctokitProvider>
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Link, NavLink, useNavigate, useParams } from 'react-router-dom';
|
||||
import { Organization } from 'gql-client';
|
||||
|
||||
import { Typography, Option } from '@material-tailwind/react';
|
||||
import { useDisconnect } from 'wagmi';
|
||||
|
||||
import { useGQLClient } from '../context/GQLClientContext';
|
||||
import AsyncSelect from './shared/AsyncSelect';
|
||||
@@ -11,6 +12,7 @@ const Sidebar = () => {
|
||||
const { orgSlug } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const client = useGQLClient();
|
||||
const { disconnect } = useDisconnect();
|
||||
|
||||
const [selectedOrgSlug, setSelectedOrgSlug] = useState(orgSlug);
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
@@ -25,6 +27,11 @@ const Sidebar = () => {
|
||||
setSelectedOrgSlug(orgSlug);
|
||||
}, [orgSlug]);
|
||||
|
||||
const handleLogOut = useCallback(() => {
|
||||
disconnect();
|
||||
navigate('/login');
|
||||
}, [disconnect, navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full p-4">
|
||||
<div className="grow">
|
||||
@@ -76,8 +83,11 @@ const Sidebar = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grow flex flex-col justify-end">
|
||||
<div>Documentation</div>
|
||||
<div>Support</div>
|
||||
<a className="cursor-pointer" onClick={handleLogOut}>
|
||||
Log Out
|
||||
</a>
|
||||
<a className="cursor-pointer">Documentation</a>
|
||||
<a className="cursor-pointer">Support</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+3
-1
@@ -24,6 +24,7 @@ import DeploymentDialogBodyCard from './DeploymentDialogBodyCard';
|
||||
import AssignDomainDialog from './AssignDomainDialog';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
import { SHORT_COMMIT_HASH_LENGTH } from '../../../../constants';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
interface DeployDetailsCardProps {
|
||||
deployment: Deployment;
|
||||
@@ -117,7 +118,8 @@ const DeploymentDetailsCard = ({
|
||||
</div>
|
||||
<div className="col-span-2 flex items-center">
|
||||
<Typography color="gray" className="grow">
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^ {deployment.createdBy.name}
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
|
||||
{formatAddress(deployment.createdBy.name ?? '')}
|
||||
</Typography>
|
||||
<Menu placement="bottom-start">
|
||||
<MenuHandler>
|
||||
|
||||
+3
-1
@@ -5,6 +5,7 @@ import { Typography, Chip, Card } from '@material-tailwind/react';
|
||||
import { color } from '@material-tailwind/react/types/components/chip';
|
||||
import { relativeTimeMs } from '../../../../utils/time';
|
||||
import { SHORT_COMMIT_HASH_LENGTH } from '../../../../constants';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
interface DeploymentDialogBodyCardProps {
|
||||
deployment: Deployment;
|
||||
@@ -39,7 +40,8 @@ const DeploymentDialogBodyCard = ({
|
||||
{deployment.commitMessage}
|
||||
</Typography>
|
||||
<Typography variant="small">
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^ {deployment.createdBy.name}
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
|
||||
{formatAddress(deployment.createdBy.name ?? '')}
|
||||
</Typography>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -7,9 +7,11 @@ import {
|
||||
Option,
|
||||
Chip,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import ConfirmDialog from '../../../shared/ConfirmDialog';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
const PERMISSION_OPTIONS = [
|
||||
{
|
||||
@@ -48,6 +50,7 @@ const MemberCard = ({
|
||||
onRemoveProjectMember,
|
||||
onUpdateProjectMember,
|
||||
}: MemberCardProps) => {
|
||||
const [ethAddress, emailDomain] = member.email.split('@');
|
||||
const [selectedPermission, setSelectedPermission] = useState(
|
||||
permissions.join('+'),
|
||||
);
|
||||
@@ -79,8 +82,16 @@ const MemberCard = ({
|
||||
>
|
||||
<div>^</div>
|
||||
<div className="basis-1/2">
|
||||
{member.name && <Typography variant="small">{member.name}</Typography>}
|
||||
<Typography variant="small">{member.email}</Typography>
|
||||
{member.name && (
|
||||
<Typography variant="small">
|
||||
{formatAddress(member.name ?? '')}
|
||||
</Typography>
|
||||
)}
|
||||
<Tooltip content={member.email}>
|
||||
<p>
|
||||
{formatAddress(ethAddress)}@{emailDomain}
|
||||
</p>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="basis-1/2">
|
||||
{!isPending ? (
|
||||
@@ -142,8 +153,9 @@ const MemberCard = ({
|
||||
color="red"
|
||||
>
|
||||
<Typography variant="small">
|
||||
Once removed, {member.name} ({member.email}) will not be able to
|
||||
access this project.
|
||||
Once removed, {formatAddress(member.name ?? '')} (
|
||||
{formatAddress(ethAddress)}@{emailDomain}) will not be able to access
|
||||
this project.
|
||||
</Typography>
|
||||
</ConfirmDialog>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export const GIT_TEMPLATE_LINK = `https://github.com/${process.env.REACT_APP_GITHUB_TEMPLATE_REPO}`;
|
||||
|
||||
export const SHORT_COMMIT_HASH_LENGTH = 8;
|
||||
|
||||
export const SERVER_GQL_PATH = 'graphql';
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import React, { ReactNode } from 'react';
|
||||
import { SiweMessage } from 'siwe';
|
||||
import { WagmiProvider } from 'wagmi';
|
||||
import { arbitrum, mainnet } from 'wagmi/chains';
|
||||
import axios from 'axios';
|
||||
|
||||
import { createWeb3Modal } from '@web3modal/wagmi/react';
|
||||
import { defaultWagmiConfig } from '@web3modal/wagmi/react/config';
|
||||
import { createSIWEConfig } from '@web3modal/siwe';
|
||||
import type {
|
||||
SIWECreateMessageArgs,
|
||||
SIWEVerifyMessageArgs,
|
||||
} from '@web3modal/core';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: process.env.REACT_APP_SERVER_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
const metadata = {
|
||||
name: 'Web3Modal',
|
||||
description: 'Snowball Web3Modal',
|
||||
url: window.location.origin,
|
||||
icons: ['https://avatars.githubusercontent.com/u/37784886'],
|
||||
};
|
||||
|
||||
const chains = [mainnet, arbitrum] as const;
|
||||
const config = defaultWagmiConfig({
|
||||
chains,
|
||||
projectId: process.env.REACT_APP_WALLET_CONNECT_ID,
|
||||
metadata,
|
||||
});
|
||||
|
||||
const siweConfig = createSIWEConfig({
|
||||
createMessage: ({ nonce, address, chainId }: SIWECreateMessageArgs) =>
|
||||
new SiweMessage({
|
||||
version: '1',
|
||||
domain: window.location.host,
|
||||
uri: window.location.origin,
|
||||
address,
|
||||
chainId,
|
||||
nonce,
|
||||
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
|
||||
statement: 'Sign in With Ethereum.',
|
||||
}).prepareMessage(),
|
||||
getNonce: async () => {
|
||||
const nonce = (await axiosInstance.get('/auth/nonce')).data;
|
||||
if (!nonce) {
|
||||
throw new Error('Failed to get nonce!');
|
||||
}
|
||||
|
||||
return nonce;
|
||||
},
|
||||
getSession: async () => {
|
||||
try {
|
||||
const session = (await axiosInstance.get('/auth/session')).data;
|
||||
const { address, chainId } = session;
|
||||
|
||||
return { address, chainId };
|
||||
} catch (err) {
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
throw new Error('Failed to get session!');
|
||||
}
|
||||
},
|
||||
verifyMessage: async ({ message, signature }: SIWEVerifyMessageArgs) => {
|
||||
try {
|
||||
const { success } = (
|
||||
await axiosInstance.post('/auth/validate', {
|
||||
message,
|
||||
signature,
|
||||
})
|
||||
).data;
|
||||
|
||||
return success;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
signOut: async () => {
|
||||
try {
|
||||
const { success } = (await axiosInstance.post('/auth/logout')).data;
|
||||
return success;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
onSignOut: () => {
|
||||
window.location.href = '/login';
|
||||
},
|
||||
onSignIn: () => {
|
||||
window.location.href = '/';
|
||||
},
|
||||
});
|
||||
|
||||
if (!process.env.REACT_APP_WALLET_CONNECT_ID) {
|
||||
throw new Error('Error: REACT_APP_WALLET_CONNECT_ID env config is not set');
|
||||
}
|
||||
|
||||
createWeb3Modal({
|
||||
siweConfig,
|
||||
wagmiConfig: config,
|
||||
projectId: process.env.REACT_APP_WALLET_CONNECT_ID,
|
||||
});
|
||||
|
||||
export default function Web3ModalProvider({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<WagmiProvider config={config}>
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
</WagmiProvider>
|
||||
);
|
||||
}
|
||||
@@ -10,23 +10,30 @@ import './index.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import { GQLClientProvider } from './context/GQLClientContext';
|
||||
import Web3ModalProvider from './context/Web3ModalProvider';
|
||||
import { SERVER_GQL_PATH } from './constants';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement,
|
||||
);
|
||||
|
||||
const gqlEndpoint = process.env.REACT_APP_GQL_SERVER_URL;
|
||||
assert(gqlEndpoint, 'GQL server URL not provided');
|
||||
assert(
|
||||
process.env.REACT_APP_SERVER_URL,
|
||||
'REACT_APP_SERVER_URL is not set in env',
|
||||
);
|
||||
const gqlEndpoint = `${process.env.REACT_APP_SERVER_URL}/${SERVER_GQL_PATH}`;
|
||||
|
||||
const gqlClient = new GQLClient({ gqlEndpoint });
|
||||
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider>
|
||||
<GQLClientProvider client={gqlClient}>
|
||||
<App />
|
||||
<Toaster position="bottom-center" />
|
||||
</GQLClientProvider>
|
||||
<Web3ModalProvider>
|
||||
<GQLClientProvider client={gqlClient}>
|
||||
<App />
|
||||
<Toaster position="bottom-center" />
|
||||
</GQLClientProvider>
|
||||
</Web3ModalProvider>
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { Outlet, useNavigate } from 'react-router-dom';
|
||||
import { User } from 'gql-client';
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IconButton, Tooltip, Typography } from '@material-tailwind/react';
|
||||
import HorizontalLine from '../components/HorizontalLine';
|
||||
import ProjectSearchBar from '../components/projects/ProjectSearchBar';
|
||||
import { useGQLClient } from '../context/GQLClientContext';
|
||||
import { formatAddress } from '../utils/format';
|
||||
|
||||
const ProjectSearch = () => {
|
||||
const navigate = useNavigate();
|
||||
@@ -18,20 +19,6 @@ const ProjectSearch = () => {
|
||||
setUser(user);
|
||||
}, []);
|
||||
|
||||
const formattedAddress = useMemo(() => {
|
||||
const address = user?.name || '';
|
||||
|
||||
if (address.length <= 8) {
|
||||
return address;
|
||||
}
|
||||
|
||||
if (address.startsWith('0x')) {
|
||||
return address.slice(0, 4) + '..' + address.slice(-4);
|
||||
}
|
||||
|
||||
return address;
|
||||
}, [user?.name]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, []);
|
||||
@@ -57,7 +44,7 @@ const ProjectSearch = () => {
|
||||
</div>
|
||||
<div className="px-2 py-1 bg-blue-gray-50 rounded-lg flex items-center">
|
||||
{user?.name && (
|
||||
<Tooltip content={user.name}>{formattedAddress}</Tooltip>
|
||||
<Tooltip content={user.name}>{formatAddress(user.name)}</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
|
||||
const Login = () => {
|
||||
return (
|
||||
<div className="grid grid-cols-5 h-screen bg-light-blue-50 py-10">
|
||||
<div className="col-span-2"></div>
|
||||
<div className="col-span-1">
|
||||
<w3m-button />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
|
||||
import Sidebar from '../components/Sidebar';
|
||||
import { OctokitProvider } from '../context/OctokitContext';
|
||||
|
||||
const OrgSlug = () => {
|
||||
return (
|
||||
@@ -12,7 +13,9 @@ const OrgSlug = () => {
|
||||
</div>
|
||||
<div className="col-span-4 h-full p-3 overflow-y-hidden">
|
||||
<div className="bg-white rounded-3xl h-full overflow-y-auto">
|
||||
<Outlet />
|
||||
<OctokitProvider>
|
||||
<Outlet />
|
||||
</OctokitProvider>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -10,6 +10,7 @@ import { relativeTimeMs } from '../../../../utils/time';
|
||||
import { useOctokit } from '../../../../context/OctokitContext';
|
||||
import { GitCommitWithBranch, OutletContextType } from '../../../../types';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
const COMMITS_PER_PAGE = 4;
|
||||
|
||||
@@ -122,9 +123,9 @@ const OverviewTabPanel = () => {
|
||||
color="green"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex justify-between items-center w-full m-2">
|
||||
<div className="flex items-center">
|
||||
<Chip
|
||||
className="normal-case inline font-normal"
|
||||
className="normal-case inline font-normal mx-2"
|
||||
size="sm"
|
||||
value="Not connected"
|
||||
icon="^"
|
||||
@@ -157,7 +158,7 @@ const OverviewTabPanel = () => {
|
||||
<p>^ Created</p>
|
||||
<p>
|
||||
{relativeTimeMs(project.deployments[0].createdAt)} by ^{' '}
|
||||
{project.deployments[0].createdBy.name}
|
||||
{formatAddress(project.deployments[0].createdBy.name ?? '')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export const formatAddress = (address: string) => {
|
||||
if (address.startsWith('0x') && address.length > 8) {
|
||||
return address.slice(0, 4) + '..' + address.slice(-4);
|
||||
}
|
||||
|
||||
return address;
|
||||
};
|
||||
Reference in New Issue
Block a user