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

Use Oauth to verify user owns their github account #7

Open
wants to merge 1 commit into
base: brightid-role
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ module.exports = {
images: {
domains: ['cdn.discordapp.com'],
},
env: {
GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
},
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@walletconnect/web3-provider": "^1.7.0",
"discord.js": "^13.5.1",
"ethers": "^5.5.3",
"form-data": "^4.0.0",
"next": "12.0.7",
"next-auth": "^4.0.6",
"react": "17.0.2",
Expand Down
3 changes: 1 addition & 2 deletions pages/api/auth/[...nextauth].js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
import DiscordProvider from 'next-auth/providers/discord';

export default NextAuth({
Expand All @@ -9,7 +8,7 @@ export default NextAuth({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
scope: ['identify guilds'],
}),
})
],

callbacks: {
Expand Down
43 changes: 43 additions & 0 deletions pages/api/github.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
const FormData = require('form-data');

export default async function handler(req, res) {
const { code } = await JSON.parse(req.body);
console.log('code: ', code);

const data = new FormData();

data.append('client_id', process.env.GITHUB_CLIENT_ID);
data.append('client_secret', process.env.GITHUB_CLIENT_SECRET);
data.append('code', code);
console.log('b');
data.append('redirect_uri', process.env.NEXTAUTH_URL + '/api/github');

console.log('data: ', data);

// Request to exchange code for an access token
fetch(`https://github.com/login/oauth/access_token`, {
method: 'POST',
body: data,
})
.then((response) => response.text())
.then((paramsString) => {
let params = new URLSearchParams(paramsString);
const access_token = params.get('access_token');
console.log('access_token: ', access_token);

// Request to return data of a user that has been authenticated
return fetch(`https://api.github.com/user`, {
headers: {
Authorization: `token ${access_token}`,
},
});
})
.then((response) => response.json())
.then((response) => {
return res.status(200).json(response);
})
.catch((error) => {
return res.status(400).json(error);
});
}
5 changes: 0 additions & 5 deletions pages/api/hello.js

This file was deleted.

56 changes: 46 additions & 10 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import { writeAddressbook } from '/helpers/github';

export default function Home() {
const [addBookEntry, setAddBookEntry] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [githubUsername, setGithubUsername] = useState('');

const { connect, address } = useWeb3Modal();
const { data: session, status } = useSession({ required: true });
console.log('session: ', session);
const { addressbook } = useAddressbook(session.user.id);

const onSubmit = async (ethAddress, githubUsername) => {
Expand All @@ -29,12 +30,39 @@ export default function Home() {
? '✅ BrightID is Connected'
: '❌ Go back to Discord and connect BrightID';

// useEffect(() => {
// async function fetchData() {

// }
// fetchData();
// }, [session]);
useEffect(() => {
const fetchGithub = async () => {
const url = window.location.href;
const hasCode = url.includes('?code=');

// If Github API returns the code parameter
if (hasCode) {
setIsLoading(true);
const newUrl = url.split('?code=');

const requestData = {
code: newUrl[1],
};

const proxy_url = process.env.NEXTAUTH_URL + '/api/github';

// Use code parameter and other parameters to make POST request to proxy_server
try {
const response = await fetch(proxy_url, {
method: 'POST',
body: JSON.stringify(requestData),
});
const { login } = await response.json();

setGithubUsername(login);
setIsLoading(false);
} catch (error) {
setIsLoading(false);
}
}
};
fetchGithub();
}, []);

useEffect(() => {
addressbook.find((addBookEntry) => {
Expand All @@ -57,7 +85,7 @@ export default function Home() {
<link rel="icon" href="/favicon.ico" />
</Head>

<main className={`${styles.main} bg-white`}>
<main className={`${styles.main} bg-white`} >
<div className="absolute top-10 flex row justify-around items-center w-60 ">
<Image
className=" rounded-full"
Expand Down Expand Up @@ -96,14 +124,22 @@ export default function Home() {
`New Address: ${formatAddress(address)}`
) : (
<button
className="w-60 text-white p-2 text-xl font-bold bg-cornflowerblue rounded"
className="h-12 px-3.5 text-white p-2 text-xl bg-cornflowerblue rounded shadow"
onClick={connect}
>
Link Ethereum to SHE
</button>
)}
<div className="w-60 p-2">
<GithubLoginButton text="Link Github to SHE" />
{githubUsername ? (
<GithubLoginButton className="m-0" text={githubUsername} />
) : (
<a
href={`https://github.com/login/oauth/authorize?scope=user&client_id=${process.env.GITHUB_CLIENT_ID}`}
>
<GithubLoginButton className="m-0" text="Link Github to SHE" />
</a>
)}
</div>
</div>
</div>
Expand Down