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

Added discord user auth #8

Merged
merged 7 commits into from
Mar 2, 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
13 changes: 11 additions & 2 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ DISCORD_CHANNEL_NAME=devnode
MYSQL_URL=mysql://root:testpassword@localhost/devnode
NEXTAUTH_URL=http://localhost:3000/
NEXT_PUBLIC_DISCORD_BOT_URL=http://localhost:4000/
DISCORD_SERVER_URL=
DISCORD_SERVER_URL=

#Staging
DISCORD_BOT_NAME=devnode-bot-staging
Expand All @@ -23,5 +23,14 @@ DISCORD_BOT_NAME=devnode-bot
#CERAMIC_NODE=https://ceramic-daemon-production.up.railway.app
#NEXTAUTH_URL=https://devnode-production.up.railway.app/

# discord user oauth creds
NEXT_PUBLIC_APP_HOME=http://localhost:3000
NEXT_PUBLIC_DISCORD_OAUTH_CLIENT_ID=
NEXT_PUBLIC_DISCORD_OAUTH_CLIENT_SECRET=
NEXT_PUBLIC_DISCORD_OAUTH_REDIRECT_URL=$NEXT_PUBLIC_APP_HOME

# wallet connect project id
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID=

NODE_VERSION=16.18.0
NIXPACKS_NODE_VERSION=16
NIXPACKS_NODE_VERSION=16
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ apps/indexer/tsconfig.tsbuildinfo
prisma/dev.db
.env

packages/composedb/.ceramic
packages/composedb/.ceramic
.idea/
3 changes: 3 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"@trpc/next": "10.7.0",
"@trpc/react-query": "10.7.0",
"@trpc/server": "10.7.0",
"@web3modal/ethereum": "^2.1.2",
"@web3modal/react": "^2.1.2",
"axios": "^1.3.4",
"did-session": "^1.0.0",
"ethers": "^5.7.2",
"graphql-request": "^5.1.0",
Expand Down
33 changes: 33 additions & 0 deletions apps/web/src/components/Button/ConnectWalletButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {useWeb3Modal} from '@web3modal/react';
import {useState} from 'react';
import {useAccount, useDisconnect} from 'wagmi';

export const ConnectWalletButton = () => {
const {open} = useWeb3Modal()
const {disconnect} = useDisconnect()
const {isConnected, address} = useAccount()
const [loading, setLoading] = useState(false)

const onOpen = async () => {
setLoading(true)
await open()
setLoading(false)
}

const onClick = async () => {
isConnected ? disconnect() : await onOpen()
}

const getAddress = () => {
return address ? address.slice(0, 8).concat("...") : "";
}

return (
<button
className="flex h-[50px] items-center justify-center rounded-[10px] border-[1px] border-[#DAD8E2] bg-white px-2 text-[#97929B] hover:border-[#08010D] hover:text-[#08010D] focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2"
onClick={onClick}
disabled={loading}>
{ isConnected ? getAddress() : "Connect Wallet"}
</button>
)
}
1 change: 1 addition & 0 deletions apps/web/src/components/Button/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ConnectWalletButton';
66 changes: 30 additions & 36 deletions apps/web/src/components/NavBar/NavBar.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import { Popover, Transition } from "@headlessui/react";
import { useConnect, useAccount, useDisconnect } from "wagmi";
import { useAccount } from "wagmi";
import Image from "next/image";
import { Fragment, useState } from "react";
import {Fragment, useEffect, useState} from "react";
import { EthereumWebAuth, getAccountId } from "@didtools/pkh-ethereum";
import { DIDSession } from "did-session";
import useLocalStorage from "../../hooks/useLocalStorage";
import { Resolver } from "did-resolver";
import { getResolver } from "pkh-did-resolver";
import { trpc } from "../../utils/trpc";
import { Modal } from "../Modal";
import Link from "next/link";

const pkhResolver = getResolver();
const resolver = new Resolver(pkhResolver);
import {getDiscordAuthUrl} from "../../config";
import {useRouter} from "next/router";
import {toast} from "react-toastify";
import {ConnectWalletButton} from "../Button";

function classNames(...classes: string[]) {
return classes.filter(Boolean).join(" ");
Expand All @@ -21,8 +20,8 @@ function classNames(...classes: string[]) {
const navigation = [{ name: "Ask a question", href: "#", current: true }];

const NavBar = (props) => {
const { disconnectAsync } = useDisconnect();
const { connectors, connectAsync } = useConnect();
const router = useRouter();
const code = router.query.code as string;
const { address, isConnected } = useAccount();

const [did, setDid] = useLocalStorage("did", "");
Expand All @@ -36,13 +35,13 @@ const NavBar = (props) => {
const discordUserName = authorDiscord.data?.discordUsername;

discordUserName && props.handleDiscordUser(true);
const connectWallet = async () => {
await Promise.all(
connectors.map(async (connector) => {
if (!isConnected) await connectAsync({ connector });
})
);
};

useEffect(() => {
const profile = localStorage.getItem("discord");
if (code && !profile) {
handleDiscordAuthCallback(code).catch((e) => { console.error(e) })
}
}, [code]);

const handleDIDSession = async () => {
if (!isConnected) return;
Expand Down Expand Up @@ -74,6 +73,19 @@ const NavBar = (props) => {
setOpen((state) => !state);
};

const handleDiscordConnect = () => {
const redirect = getDiscordAuthUrl()
window.location.replace(redirect)
}

const handleDiscordAuthCallback = async (code: string) => {
const response = await fetch(`/api/user/discord-auth/profile?code=${code}`);
const profile = await response.json();
localStorage.setItem("discord", JSON.stringify(profile));
toast.success("Successfully logged in with discord");
props.handleDiscordUser(true);
}

return (
<>
{/* When the mobile menu is open, add `overflow-hidden` to the `body` element to prevent double scrollbars */}
Expand Down Expand Up @@ -146,25 +158,7 @@ const NavBar = (props) => {
</Popover.Button> */}
</div>
<div className="hidden gap-[16px] lg:flex lg:w-[40%] lg:items-center lg:justify-start">
{isConnected ? (
<button
onClick={() => {
disconnectAsync();
}}
className="flex h-[50px] items-center justify-center rounded-[10px] border-[1px] border-[#DAD8E2] bg-white px-2 text-[#97929B] hover:border-[#08010D] hover:text-[#08010D] focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2"
>
{address.slice(0, 8) + "..."}
</button>
) : (
<button
onClick={() => {
connectWallet();
}}
className="flex h-[50px] items-center justify-center rounded-[10px] border-[1px] border-[#DAD8E2] bg-white px-2 text-[#97929B] hover:border-[#08010D] hover:text-[#08010D] focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2"
>
Connect wallet
</button>
)}
<ConnectWalletButton />

{isConnected && did.length > 0 ? (
<Popover className="relative">
Expand Down Expand Up @@ -233,7 +227,7 @@ const NavBar = (props) => {
</Popover>
) : (
<button
onClick={handleClick}
onClick={handleDiscordConnect}
className="flex h-[50px] items-center justify-center rounded-[10px] border-[1px] border-[#DAD8E2] bg-white px-2 text-[#97929B] hover:border-[#08010D] hover:text-[#08010D] focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2"
>
Connect with Discord bot
Expand Down
22 changes: 22 additions & 0 deletions apps/web/src/config/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export const config = {
appHome: process.env.NEXT_PUBLIC_APP_HOME || "",
discordApiEndpoint: "https://discord.com/api",
discordOAuth: {
clientId: process.env.NEXT_PUBLIC_DISCORD_OAUTH_CLIENT_ID || "",
clientSecret: process.env.NEXT_PUBLIC_DISCORD_OAUTH_CLIENT_SECRET || "",
redirectUrl: process.env.NEXT_PUBLIC_DISCORD_OAUTH_REDIRECT_URL || "",
},
walletConnect: {
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID || "",
}
}

export const getDiscordAuthUrl = (): string => {
const data = new URLSearchParams({
client_id: config.discordOAuth.clientId,
redirect_uri: config.discordOAuth.redirectUrl,
scope: "identify",
response_type: "code",
});
return `${config.discordApiEndpoint}/oauth2/authorize?${data}`;
}
1 change: 1 addition & 0 deletions apps/web/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './config'
87 changes: 39 additions & 48 deletions apps/web/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,58 +1,49 @@
import { type AppType } from "next/app";

import { trpc } from "../utils/trpc";

import {type AppType} from "next/app";
import {trpc} from "../utils/trpc";
import "../styles/globals.css";

import { publicProvider } from "wagmi/providers/public";

import { InjectedConnector } from "wagmi/connectors/injected";

import { Session } from "next-auth";
import { configureChains, createClient, WagmiConfig } from "wagmi";
import { mainnet, optimism } from "wagmi/chains";

import { ToastContainer } from 'react-toastify';

import {configureChains, createClient, WagmiConfig} from "wagmi";
import {arbitrum, avalanche, bsc, fantom, gnosis, mainnet, optimism, polygon} from "wagmi/chains";
import {ToastContainer} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {EthereumClient, modalConnectors, walletConnectProvider} from "@web3modal/ethereum";
import {Web3Modal} from '@web3modal/react'
import {config} from '../config';

const { chains, provider, webSocketProvider } = configureChains(
[mainnet],
[publicProvider()]
);

const projectId = config.walletConnect.projectId;
const chains = [mainnet, polygon, avalanche, arbitrum, bsc, optimism, gnosis, fantom]
const {provider} = configureChains(chains, [walletConnectProvider({projectId})])
const client = createClient({
autoConnect: true,
connectors: [
new InjectedConnector({
chains,
options: {
name: "Injected",
shimDisconnect: true,
},
}),
],
provider,
webSocketProvider,
});
connectors: modalConnectors({version: '1', appName: 'web3Modal', chains, projectId}),
provider
})
const ethereumClient = new EthereumClient(client, chains)

const MyApp: AppType = ({ Component, pageProps }) => {
const MyApp: AppType = ({Component, pageProps}) => {
return (
<WagmiConfig client={client}>
<ToastContainer
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
/>
<Component {...pageProps} />
</WagmiConfig>
<>
<WagmiConfig client={client}>
<ToastContainer
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
/>
<Component {...pageProps} />
</WagmiConfig>
<Web3Modal
themeMode="light"
themeColor="blackWhite"
themeBackground="themeColor"
projectId={projectId}
ethereumClient={ethereumClient}/>
</>
);
};

Expand Down
57 changes: 57 additions & 0 deletions apps/web/src/pages/api/user/discord-auth/profile.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {NextApiRequest, NextApiResponse} from "next";
import {config} from "../../../../config";
import axios from 'axios';

const getAccessToken = async (code: string) => {
const url = `${config.discordApiEndpoint}/oauth2/token`;
const body = new URLSearchParams({
client_id: config.discordOAuth.clientId,
client_secret: config.discordOAuth.clientSecret,
redirect_uri: config.discordOAuth.redirectUrl,
scope: "identify",
grant_type: "authorization_code",
code: code,
});
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
try {
return await axios.post(url, body.toString(), {headers});
} catch (e) {
return e.response
}
}

const getDiscordUserProfile = async (tokenType: string, token: string) => {
const url = `${config.discordApiEndpoint}/users/@me`;
const headers = {
authorization: `${tokenType} ${token}`,
};
try {
return await axios.get(url, {headers: headers});
} catch (e) {
return e.response;
}
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const {code} = req.query;
if (!code) {
return res.send(400);
}

const tokenResp = await getAccessToken(code as string);
if (tokenResp.status !== 200) {
return res.status(400).json(tokenResp.data);
}

const profile = await getDiscordUserProfile(
tokenResp.data.token_type,
tokenResp.data.access_token
);
if (profile.status !== 200) {
return res.status(400).json(profile.data);
}

return res.status(200).json(profile.data);
}
Loading