Skip to content

Commit

Permalink
Add useAuthAndContract hook
Browse files Browse the repository at this point in the history
Create a new file `useAuthAndContract.js` to define a custom hook `useAuthAndContract`. This hook imports necessary dependencies from `next-auth/react` and `@thirdweb-dev/react`, and returns session data, status, address, contract, login function, and logout function.
  • Loading branch information
XOwlPost committed Feb 18, 2024
1 parent 6374732 commit 41a674d
Show file tree
Hide file tree
Showing 9 changed files with 147 additions and 14 deletions.
14 changes: 14 additions & 0 deletions hooks/useAuthAndContract.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// hooks/useAuthAndContract.js
import { useSession, signIn, signOut } from "next-auth/react";
import { useContract, useAddress } from '@thirdweb-dev/react';

export function useAuthAndContract(contractAddress) {
const { data: session, status } = useSession();
const address = useAddress();
const contract = useContract(contractAddress);

const login = () => signIn();
const logout = () => signOut();

return { session, status, address, contract, login, logout };
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
"dependencies": {
"@thirdweb-dev/auth": "^4.1.32",
"@thirdweb-dev/react": "^4.4.8",
"@thirdweb-dev/sdk": "^4.0.34",
"@thirdweb-dev/sdk": "^4.0.35",
"@vercel/postgres": "^0.7.2",
"@vercel/speed-insights": "^1.0.9",
"cors": "^2.8.5",
"ethers": "5",
"ethers": "5.6.9",
"next": "^14.1.0",
"next-auth": "^4.24.5",
"prisma": "^5.9.1",
Expand Down
17 changes: 17 additions & 0 deletions pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// pages/_app.js
import { ThirdwebProvider } from '@thirdweb-dev/react';
import { SessionProvider } from "next-auth/react";

const desiredChainId = 1; // Mainnet. Change this to desired chain ID.

function MyApp({ Component, pageProps }) {
return (
<SessionProvider session={pageProps.session}>
<ThirdwebProvider desiredChainId={desiredChainId}>
<Component {...pageProps} />
</ThirdwebProvider>
</SessionProvider>
);
}

export default MyApp;
36 changes: 24 additions & 12 deletions pages/api/create-user.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
// pages/api/create-user.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
// Handle the POST request
const user = req.body; // Assuming the request body contains user data
// Process the user creation logic here...
res.status(200).json({ status: 'success', data: user });
} else {
// Handle any other HTTP method
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
import type { NextApiRequest, NextApiResponse } from 'next';
import { hashPassword } from './lib/auth';
import { queryDatabase } from './lib/db';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
// Handle non-POST requests
return res.status(405).end(`Method Not Allowed`);
}

const { email, password, name } = req.body;

try {
const { rows } = await queryDatabase('SELECT * FROM users WHERE email = $1', [email]);
if (rows.length > 0) {
return res.status(422).json({ message: 'User already exists.' });
}

const hashedPassword = await hashPassword(password);

const result = await queryDatabase('INSERT INTO users (email, password, name) VALUES ($1, $2, $3) RETURNING id', [email, hashedPassword, name]);
return res.status(201).json({ id: result.rows[0].id, email, name });
} catch (error) {
return res.status(500).json({ message: 'Internal server error' });
}
}
11 changes: 11 additions & 0 deletions pages/api/lib/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// pages/api/lib/auth.js
import bcrypt from 'bcryptjs';

export async function hashPassword(password) {
const salt = await bcrypt.genSalt(10);
return bcrypt.hash(password, salt);
}

export async function verifyPassword(password, hashedPassword) {
return bcrypt.compare(password, hashedPassword);
}
22 changes: 22 additions & 0 deletions pages/api/lib/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// pages/api/lib/db.js
import { Pool } from 'pg';

const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {rejectUnauthorized: false},
});

export async function connectToDatabase() {
const client = await pool.connect();
return { client };
}

export async function queryDatabase(queryText, params) {
const { client } = await connectToDatabase();
try {
const result = await client.query(queryText, params);
return result;
} finally {
client.release();
}
}
12 changes: 12 additions & 0 deletions pages/api/secure-action.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// pages/api/secure-action.js
import { getSession } from "next-auth/react";

export default async (req, res) => {
const session = await getSession({ req });

if (!session) {
return res.status(401).json({ error: 'Unauthorized' });
}

// Proceed with blockchain interactions using Thirdweb SDK
};
28 changes: 28 additions & 0 deletions pages/profile/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useContract } from '@thirdweb-dev/react';
import { useEffect, useState } from 'react';

const UserProfileBlockchain = ({ id }) => {
const [userTokens, setUserTokens] = useState([]);
const contract = useContract('<Your-Contract-Address>');

useEffect(() => {
const fetchUserTokens = async () => {
// Example: Fetching user's token holdings from a smart contract
const tokens = await contract.call('getUserTokens', id);
setUserTokens(tokens);
};

if (id && contract) {
fetchUserTokens();
}
}, [id, contract]);

return (
<div>
<h1>User Blockchain Data</h1>
{/* Display blockchain data */}
</div>
);
};

export default UserProfileBlockchain;
17 changes: 17 additions & 0 deletions pages/protected-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// pages/protected-page.js
import { useSession } from "next-auth/react";
import { useEffect } from "react";
import { useRouter } from "next/router";

export default function ProtectedPage() {
const { data: session } = useSession();
const router = useRouter();

useEffect(() => {
if (!session) {
router.push('/api/auth/signin');
}
}, [session, router]);

return <div>Protected Content</div>;
}

0 comments on commit 41a674d

Please sign in to comment.