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

Set_Up_Auth_And_Firebase #20

Merged
merged 6 commits into from
Nov 15, 2023
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
4 changes: 4 additions & 0 deletions frontend/nextjs/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
NEXTAUTH_URL=
NEXTAUTH_SECRET=
NEXT_PUBLIC_FIREBASE_API_KEY=
FIREBASE_SERVICE_ACCOUNT_KEY=
3 changes: 2 additions & 1 deletion frontend/nextjs/emt.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { getDefaultWallets } = require("@rainbow-me/rainbowkit");
import {getDefaultWallets} from "@rainbow-me/rainbowkit";
import { LucideImport } from "lucide-react";
import { configureChains, createConfig } from 'wagmi';
import {
hardhat, mainnet, polygonMumbai
Expand Down
9 changes: 8 additions & 1 deletion frontend/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,29 @@
"lint": "next lint"
},
"dependencies": {
"@auth/firebase-adapter": "^1.0.4",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-tabs": "^1.0.4",
"@rainbow-me/rainbowkit": "^1.1.4",
"@rainbow-me/rainbowkit-siwe-next-auth": "^0.3.2",
"axios": "^1.6.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"ethers": "^6.8.1",
"ethers": "^5.7.2",
"ethers6": "npm:ethers@^6.8.1",
"firebase": "^10.6.0",
"firebase-admin": "^11.11.0",
"lucide-react": "^0.291.0",
"next": "14.0.1",
"next-themes": "^0.2.1",
"prettier": "^3.0.3",
"react": "^18",
"react-dom": "^18",
"react-icons": "^4.11.0",
"siwe": "^2.1.4",
"tailwind-merge": "^2.0.0",
"tailwindcss-animate": "^1.0.7",
"viem": "^1.18.1",
Expand Down
58 changes: 58 additions & 0 deletions frontend/nextjs/src/app/api/auth/[...nextauth]/auth-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { getCsrfToken } from "next-auth/react";
import { SiweMessage } from "siwe";

export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Ethereum",
credentials: {
message: {
label: "Message",
type: "text",
placeholder: "0x0",
},
signature: {
label: "Signature",
type: "text",
placeholder: "0x0",
},
},
async authorize(credentials, req) {
try {
const siwe = new SiweMessage(
JSON.parse(credentials?.message || "{}")
);
const nextAuthUrl = new URL(process.env.NEXTAUTH_URL as string);

const result = await siwe.verify({
signature: credentials?.signature || "",
domain: nextAuthUrl.host,
nonce: await getCsrfToken({ req: { headers: req.headers } }),
});

if (result.success) {
return {
id: siwe.address,
};
}
return null;
} catch (e) {
return null;
}
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token }: { session: any; token: any }) {
session.address = token.sub;
session.user.name = token.sub;
return session;
},
},
};
6 changes: 6 additions & 0 deletions frontend/nextjs/src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import NextAuth from "next-auth";
import { authOptions } from "./auth-options";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
9 changes: 7 additions & 2 deletions frontend/nextjs/src/app/dapp/components/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import React from 'react';
import '@rainbow-me/rainbowkit/styles.css';
import {
RainbowKitProvider,
darkTheme
darkTheme,
} from '@rainbow-me/rainbowkit';

import { RainbowKitSiweNextAuthProvider } from '@rainbow-me/rainbowkit-siwe-next-auth';
import { emtChains, emtWagmiConfig } from "../../../../emt.config"
import { WagmiConfig } from 'wagmi';
import { ContractProvider } from '@/lib/hooks/contracts';
import { UserProvider } from '@/lib/hooks/user';

// Web3 Wallet Connector's Provider
export default function DappProviders({
Expand All @@ -18,15 +19,19 @@ export default function DappProviders({
}) {
return (
<WagmiConfig config={emtWagmiConfig}>
<RainbowKitSiweNextAuthProvider>
<RainbowKitProvider chains={emtChains} theme={darkTheme({
accentColorForeground: 'white',

accentColor: '#5957e9',
})} >
<ContractProvider>
<UserProvider>
{children}
</UserProvider>
</ContractProvider>
</RainbowKitProvider>
</RainbowKitSiweNextAuthProvider>
</WagmiConfig>
)
}
9 changes: 6 additions & 3 deletions frontend/nextjs/src/app/dapp/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,21 @@ import { Search } from '@/components/ui/forms/search';
import { Button } from '@/components/ui/button';
import { HiOutlinePencilAlt } from "react-icons/hi"
import DappProviders from './components/providers';
import { ScrollArea } from "@/components/ui/scroll-area"

import SessionProvider from "@/lib/hooks/sessionProvider";
import { getServerSession } from "next-auth";
export const metadata: Metadata = {
title: 'MEMM! Homepage',
}

export default function DappLayout({
export default async function DappLayout({
children
}: {
children: React.ReactNode
}) {
const session = await getServerSession();
return (
<>
<SessionProvider refetchInterval={0} session={session}>
<DappProviders>
<header>
<div className=" flex-col md:flex">
Expand Down Expand Up @@ -62,6 +64,7 @@ export default function DappLayout({
</div>
</div>
</DappProviders>
</SessionProvider>
</>
)
}
17 changes: 3 additions & 14 deletions frontend/nextjs/src/app/dapp/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Image from "next/image";
import { HiCheckBadge, HiOutlineFire } from "react-icons/hi2"
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
import { useUser } from "@/lib/hooks/user";

const dummyPosts = [
{
Expand Down Expand Up @@ -125,20 +126,8 @@ const topCreatorList = [

export default function RootLayout() {
const { EMTMarketPlace, ExpertToken, MentorToken } = useContracts();
async function handleEMTMarketPlace() {
const val = await EMTMarketPlace.downVoteWeight();
alert(val);
}

async function handleExpertToken() {
const val = await ExpertToken.MINTER_ROLE();
alert(val);
}

async function handleMentorToken() {
const val = await MentorToken.decimals();
alert(val);
}
const {user, updateUser, isLoading} = useUser();
console.log('u', user)

// return (
// <div className="flex flex-col">
Expand Down
13 changes: 7 additions & 6 deletions frontend/nextjs/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@ import { Inter } from 'next/font/google'
import './globals.css'
import { ThemeProvider } from '@/components/ui/theme-provider'

const inter = Inter({ subsets: ['latin'] })
const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: 'MEMM!',
description: 'Mentorship from the best',
}

export default function RootLayout({
export default async function RootLayout({
children,
}: {
children: React.ReactNode
children: React.ReactNode;
}) {
return (



return (
<html lang="en">
<body className={`${inter.className}`}>
<ThemeProvider
Expand All @@ -29,6 +31,5 @@ export default function RootLayout({
</ThemeProvider>
</body>
</html>

)
);
}
24 changes: 24 additions & 0 deletions frontend/nextjs/src/lib/firebase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from 'firebase/auth';

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: "emt-marketplace-6bc77.firebaseapp.com",
projectId: "emt-marketplace-6bc77",
storageBucket: "emt-marketplace-6bc77.appspot.com",
messagingSenderId: "927116640337",
appId: "1:927116640337:web:231f3fd6dbd1679d11f870",
measurementId: "G-RX5EYJK6HH"
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
export const auth = getAuth(app)
2 changes: 1 addition & 1 deletion frontend/nextjs/src/lib/hooks/contracts.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { ethers } from "ethers";
import { ethers } from "ethers6";
import { chain } from "../../../emt.config";
import {EMTMarketplace} from "../../../../../blockchain/typechain-types/contracts/EMTMarketplace";
import {ExpertToken} from "../../../../../blockchain/typechain-types/contracts/ExpertToken";
Expand Down
3 changes: 3 additions & 0 deletions frontend/nextjs/src/lib/hooks/sessionProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"use client";
import { SessionProvider } from "next-auth/react";
export default SessionProvider;
111 changes: 111 additions & 0 deletions frontend/nextjs/src/lib/hooks/user.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import axios from "axios";
import { auth, firestore } from "@/lib/firebase";
import { signInWithCustomToken, signOut, onAuthStateChanged, } from "firebase/auth";
import { doc, getDoc, setDoc, updateDoc } from "firebase/firestore";

interface User {
address: string;
displayName?: string,
email?: string;
isAuthenticated?: boolean;
photoUrl?: string,
}

interface UserContext {
user: User | null;
updateUser: (data: {username?: string, photoUrl?: string, displayName?: string, email?: string}) => void;
isLoading: boolean;
}

declare global {
interface Window {
ethereum: any;
}
}

const UserContext = createContext<UserContext | null>(null);

export function useUser(): UserContext {
const userContext = useContext(UserContext);

return userContext!;


}

export function UserProvider({ children }: { children: React.ReactNode }) {

const [user, setUser] = useState<User | null>(null);
const { data: session, status } : {data: any, status: string} = useSession();
const [isLoading, setIsLoading] = useState(false);

async function updateUser(data: {username?: string, photoUrl?: string, displayName?: string, email?: string}) {
const userDocRef = doc(firestore, 'users', session?.address); // Replace 'users' with your collection name
await updateDoc(userDocRef, data);
}

useEffect(() => {


async function signIn(){

try {
setIsLoading(true);
const baseUrl = `${window.location.protocol}//${window.location.host}`;
const res = await axios.post(baseUrl + '/api/getToken', {
address: session?.address })
const token = res.data.token;
const userData = await signInWithCustomToken(auth, token);
//get user data from fireStore
const userDocRef = doc(firestore, 'users', session.address); // Replace 'users' with your collection name
const userDocSnap = await getDoc(userDocRef);

if (userDocSnap.exists()) {
//@ts-ignore
setUser({ ...userDocSnap.data() });
} else {
const newUser = { address: session?.address};
await setDoc(userDocRef, newUser);
//@ts-ignore
setUser(newUser);
}
} catch (err:any) {
throw new Error(err);
}
finally{
setIsLoading(false);
}

}
async function _signOut(){
setIsLoading(true)
signOut(auth).then(() => {
console.log('User signed out');
setUser(null);
}).catch((error) => {
console.error('Error signing out: ', error);
});
setIsLoading(false)
}

if (status === 'unauthenticated' && user) {
_signOut();
}
if (session?.address && !user) {
signIn();
}


}, [session?.address])





return (
<UserContext.Provider value={{user, updateUser, isLoading}}>{children}</UserContext.Provider>
);
}
Loading
Loading