Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Commit

Permalink
Merge pull request #149 from ColinLefter/authentication-hotfixes
Browse files Browse the repository at this point in the history
Critical Authentication Hot fixes (Urgent)
  • Loading branch information
Hocng7 authored Mar 26, 2024
2 parents f8ac2e9 + a669993 commit 0dea17f
Show file tree
Hide file tree
Showing 19 changed files with 145 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export function FriendsTab(props: TextInputProps) {

if (activeChat && user?.id) { // Ensure both activeChat and user.id are defined
return <Chat
sender={user.id}
sender={user.username as any}
receiver={activeChat} // The receiver is now the friend we clicked on
privateChat={true}
onMessageExchange={() => {}}
Expand Down
15 changes: 11 additions & 4 deletions Application/Frontend/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@ export default authMiddleware({
publicRoutes: [
'/',
'/api/webhooks/clerk-mongodb-sync',
'/api/registration',
'/api/update-user-data',
'/api/ably-auth',
'/api/delete-user',
'/api/FriendsTab',
'/log-in',
'/create-account'
'/api/get-message-history',
'/api/getServersListOfUser',
'/api/initializingServerList',
'/api/login',
'/api/registration',
'/api/servers',
'/api/testMongoDB',
'/api/update-message-history',
'/api/update-user-data',
'/api/userSettings'
],
// Prevent the specified routes from accessing authentication information:
// ignoredRoutes: [''],
Expand Down
103 changes: 103 additions & 0 deletions Application/Frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Application/Frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "1.0.0",
"private": true,
"scripts": {
"ngrok": "ngrok http 3001",
"ngrok": "ngrok http --domain=ant-inspired-bass.ngrok-free.app 3001",
"dev": "next dev",
"proxy": "ts-node -P tsconfig.node.json proxyServer.ts",
"accord": "concurrently \"npm run dev\" \"npm run proxy\" \"npm run ngrok\"",
Expand Down Expand Up @@ -39,6 +39,7 @@
"devDependencies": {
"@babel/core": "^7.23.2",
"@clerk/nextjs": "^4.29.9",
"@clerk/themes": "^1.7.10",
"@next/eslint-plugin-next": "^14.0.1",
"@storybook/addon-essentials": "^7.5.2",
"@storybook/addon-styling-webpack": "^0.0.5",
Expand Down Expand Up @@ -68,6 +69,7 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-testing-library": "^6.1.0",
"http-proxy-middleware": "^2.0.6",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"postcss": "^8.4.31",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from 'next';
import Ably from 'ably/promises';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
if (req.method === 'POST') {
const ably = new Ably.Rest.Promise({ key: process.env.ABLY_API_KEY_PUBLISH_SUBSCRIBE });

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getMongoDbUri } from '@/lib/dbConfig';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const { id } = JSON.parse(req.body); // Assuming the email is sent in the body
const { id } = req.body; // Directly destructuring `id` from `req.body` because it's already an object

if (!id) {
return res.status(400).json({ error: 'User ID is required for deletion' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,27 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
email,
phone,
createdAt
} = req.body; // Intaking the data that has been sent from the client-side
} = req.body;

let client: MongoClient | null = null; // We need to assign something to the client so TypeScript is aware that it can be null if the connection fails
let client: MongoClient | null = null;

try {
client = new MongoClient(getMongoDbUri());
await client.connect();
const db = client.db('Accord');

const accountsCollection = db.collection("Accounts");
// Querying the database by the userName we received

// First, check if an account with the same 'id' or 'userName' already exists
const existingAccountById = await accountsCollection.findOne({ id: id });
const existingAccountByUserName = await accountsCollection.findOne({ userName: userName });

if (existingAccountById || existingAccountByUserName) {
// If the account already exists by either id or userName, return a message indicating so
return res.status(409).json({ message: 'An account with the same ID or username already exists.' });
}

// If the account does not exist by either criterion, proceed to create a new account
await accountsCollection.insertOne({
id: id,
firstName: firstName,
Expand All @@ -39,12 +49,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
email: email,
phone: phone,
createdAt: createdAt,
friendsList: ["user1", "user2"] // for now every single new user is friends with user1 and user2. This would be replaced with an add friends button.
}); // IMPORTANT: The findOne method returns a promise, so we need to await the resolution of the promise first
return res.status(200).json({ message: 'Registration success' });
friendsList: ["user1", "user2"] // Example initial friends list
});

return res.status(200).json({ message: 'Registration successful' });
} catch (error) {
console.error(error);
console.error('Failed to register user:', error);
return res.status(500).json({ error: 'Internal server error' });
} finally {
if (client) {
Expand All @@ -56,4 +66,4 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export default async function POST(req: Request) {
if (userData) {
switch (eventType) {
case 'user.created':
// Create user in MongoDB
console.log(`Creating user: ${postData.firstName} ${postData.lastName}`);
// Making the API call
try {
const response = await fetch('http://localhost:3000/api/registration', {
method: 'POST',
Expand All @@ -100,7 +100,7 @@ export default async function POST(req: Request) {
}
break;
case 'user.updated':
// TODO: Update user in MongoDB
// Update user data in MongoDB
console.log(`Updating user: ${postData.firstName} ${postData.lastName}`);
try {
const response = await fetch('http://localhost:3000/api/update-user-data', {
Expand All @@ -121,17 +121,18 @@ export default async function POST(req: Request) {
}
break;
case 'user.deleted':
// TODO: Delete user from MongoDB
// Delete user in MongoDB
console.log(`Deleting user: ${postData.firstName} ${postData.lastName}`);
try {
const response = await fetch('http://localhost:3000/api/delete-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData.email),
// Stringify the whole object, not just the id
body: JSON.stringify({ id: postData.id }), // postData contains the id field
});

if (!response.ok) {
console.error('Failed to update user through API:', await response.text());
} else {
Expand Down
2 changes: 1 addition & 1 deletion Application/Frontend/pages/my-account.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export function MyAccount() {
export default function MyAccount() {
<h1>My account</h1>
}

0 comments on commit 0dea17f

Please sign in to comment.