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

Feat/siwe #40

Merged
merged 11 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_BASE_URL=https://onchain.togethercrew.de/api/v1/
20,969 changes: 16,758 additions & 4,211 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,18 @@
"@fontsource/roboto": "^5.0.13",
"@mui/icons-material": "^5.16.0",
"@mui/material": "^5.16.0",
"@rainbow-me/rainbowkit": "^2.1.3",
"@react-icons/all-files": "^4.1.0",
"@tanstack/react-query": "^5.50.1",
"@tanstack/react-query": "^5.51.16",
"@tanstack/react-query-devtools": "^5.50.1",
"axios": "^1.7.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.52.1",
"react-icons": "^5.2.1",
"react-router-dom": "^6.24.1",
"viem": "^2.18.6",
"wagmi": "^2.12.2",
"zod": "^3.23.8",
"zustand": "^4.5.4"
},
Expand Down
Binary file added public/img/login.webp
Binary file not shown.
114 changes: 111 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,117 @@
import React, { useState } from 'react';
import './App.css';
import '@rainbow-me/rainbowkit/styles.css';
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import {
getDefaultConfig,
RainbowKitProvider,
RainbowKitAuthenticationProvider,
createAuthenticationAdapter,
AuthenticationStatus,
} from '@rainbow-me/rainbowkit';
import { WagmiProvider } from 'wagmi';
import { sepolia } from 'viem/chains';
import { getAddress } from 'viem';
import { createSiweMessage } from 'viem/siwe';
import theme from './libs/theme';
import { router } from './router';
import { api } from './api';
import { AuthProvider, useAuth } from './context/authContext';

function App() {
return <RouterProvider router={router} />;
}
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: false,
staleTime: 1000 * 60 * 5,
},
},
});

const AuthenticationWrapper: React.FC = () => {
const { setAuthInfo, signOut } = useAuth();
const [authStatus, setAuthStatus] =
useState<AuthenticationStatus>('unauthenticated');

const authenticationAdapter = createAuthenticationAdapter({
getNonce: async () => {
const { data } = await api.get('auth/siwe/nonce');
return data.nonce;
},
createMessage: ({ nonce, address, chainId }) => {
return createSiweMessage({
address: getAddress(address),
chainId,
domain: window.location.host,
nonce,
uri: window.location.origin,
version: '1',
statement: 'Sign in with Ethereum to the app.',
});
},
getMessageBody: ({ message }) => message,
verify: async ({ message, signature }) => {
const { data } = await api.post('auth/siwe/verify', {
message,
signature,
chainId: 11155111,
});

if (!data) {
throw new Error('Verification response data is empty');
}

if (data?.jwt) {
setAuthStatus('authenticated');
setAuthInfo(data.jwt);
window.location.replace('/');
} else {
setAuthStatus('unauthenticated');
}

return data;
},
signOut: async () => {
await api.post('auth/logout');
setAuthStatus('unauthenticated');
signOut();
},
});

const config = getDefaultConfig({
appName: 'RainbowKit demo',
projectId: '1cf030f3b91e339bc4e6ecf71a694a88',
chains: [sepolia],
});

return (
<WagmiProvider config={config}>
<RainbowKitAuthenticationProvider
adapter={authenticationAdapter}
status={authStatus}
>
<RainbowKitProvider>
<RouterProvider router={router} />
</RainbowKitProvider>
</RainbowKitAuthenticationProvider>
</WagmiProvider>
);
};

const App: React.FC = () => {
return (
<AuthProvider>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
<CssBaseline />
<AuthenticationWrapper />
</ThemeProvider>
</QueryClientProvider>
</AuthProvider>
);
};

export default App;
37 changes: 37 additions & 0 deletions src/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Navigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import CircularProgress from '@mui/material/CircularProgress';
import Backdrop from '@mui/material/Backdrop';
import { useAuth } from './context/authContext';

const ProtectedRoute = ({ children }: { children: JSX.Element }) => {
const { isAuthenticated } = useAuth();
const [loading, setLoading] = useState(true);

useEffect(() => {
const checkAuthStatus = async () => {
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 1000);
};

checkAuthStatus();
}, [isAuthenticated]);

if (loading) {
return (
<Backdrop open={loading} style={{ zIndex: 1201 }}>
<CircularProgress color="inherit" />
</Backdrop>
);
}

if (!isAuthenticated) {
return <Navigate to="/auth/login" replace />;
}

return children;
};

export default ProtectedRoute;
34 changes: 32 additions & 2 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
import axios from 'axios';

export const client = axios.create({
baseURL: '',
const baseURL = import.meta.env.VITE_API_BASE_URL;

if (!baseURL) {
throw new Error(
'VITE_API_BASE_URL is not defined in your environment variables'
);
}

export const api = axios.create({
baseURL,
headers: {
'Content-Type': 'application/json',
},
});

api.interceptors.request.use(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(config: any) => {
const token = localStorage.getItem('OCI_TOKEN');
if (token) {
return {
...config,
headers: {
...config.headers,
Authorization: `Bearer ${token}`,
},
};
}
return config;
},
(error) => {
return Promise.reject(error);
}
);

export default api;
62 changes: 62 additions & 0 deletions src/context/authContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
createContext,
useState,
useContext,
ReactNode,
useEffect,
useMemo,
} from 'react';

interface AuthContextType {
isAuthenticated: boolean;
jwt: string | null;
setAuthInfo: (jwt: string) => void;
signOut: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [jwt, setJwt] = useState<string | null>(null);

useEffect(() => {
const token = localStorage.getItem('OCI_TOKEN');
if (token) {
setJwt(token);
setIsAuthenticated(true);
}
}, []);

const setAuthInfo = (token: string) => {
setJwt(token);
setIsAuthenticated(true);
localStorage.setItem('OCI_TOKEN', token);
};

const signOut = () => {
setJwt(null);
setIsAuthenticated(false);
localStorage.removeItem('OCI_TOKEN');
};

const value = useMemo(
() => ({
isAuthenticated,
jwt,
setAuthInfo,
signOut,
}),
[isAuthenticated, jwt]
);

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
29 changes: 5 additions & 24 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from "./libs/theme";

const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: false,
staleTime: 1000 * 60 * 5,
},
},
});
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</QueryClientProvider>
<App />
</React.StrictMode>
);
29 changes: 29 additions & 0 deletions src/pages/Auth/Login/Login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { ConnectButton } from '@rainbow-me/rainbowkit';
import { Box, Typography } from '@mui/material';

export function Login() {
return (
<div className="h-screen w-full flex">
<Box className="w-1/4 p-8 flex flex-col justify-center items-center shadow-2xl">
<Typography variant="h6" fontWeight="bold" gutterBottom>
Welcome to OnChain
</Typography>
<Typography variant="body1" gutterBottom>
Please connect your wallet to continue.
</Typography>
<div className="py-3">
<ConnectButton />
</div>
</Box>
<Box
className="w-3/4 h-full bg-cover bg-center"
style={{
backgroundImage: 'url(../../../../public/img/login.webp)',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
}}
/>
</div>
);
}
3 changes: 3 additions & 0 deletions src/pages/Auth/Login/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { Login } from "./Login";

export default Login;
Loading
Loading