Skip to content

Commit

Permalink
Merge pull request #41 from COS301-SE-2024/feature/db-synch
Browse files Browse the repository at this point in the history
Adding users to postgres db
  • Loading branch information
JBlixems authored Jun 22, 2024
2 parents 69111b2 + 41a0768 commit 3bb01d3
Showing 6 changed files with 75 additions and 32 deletions.
14 changes: 13 additions & 1 deletion CoVAR-app/src/login/loginForm.tsx
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ import { useAuth } from '../contexts/authContext';
import { useNavigate } from 'react-router-dom';
import { doc, setDoc, getDoc } from "firebase/firestore";
import { db } from '../firebase/firebaseConfig';
import axios from 'axios';

interface LoginProps {
toggleForm: () => void;
@@ -80,7 +81,18 @@ const Login: React.FC<LoginProps> = ({ toggleForm }) => {
const result = await doSignInWithGoogle();
await addUserToFirestore(result.user as User); // Ensure to await Firestore addition
console.log(result.user);
navigate('/'); // Navigate to dashboard after successful Google login
//call to postgresql to check if user exists else make one and then navigate
const { uid, email } = result.user;
const response = await axios.post('/api/users/create', {
uid,
email
});

if (response.status === 201) {
navigate('/');
} else {
throw new Error('Failed to create user in PostgreSQL');
}
return result;
} catch (error) {
console.error(error);
35 changes: 28 additions & 7 deletions CoVAR-app/src/login/signupForm.tsx
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ import { doCreateUserWithEmailAndPassword, doSignInWithGoogle } from '../firebas
import GoogleIcon from "../icons/GoogleIcon";
import { doc, setDoc, getDoc } from "firebase/firestore";
import { db } from '../firebase/firebaseConfig';
import axios from 'axios';

interface User {
uid: string;
@@ -49,15 +50,25 @@ const Signup: React.FC<SignupProps> = ({ toggleForm }) => {
try {
const result = await doSignInWithGoogle();
if (result.user) {
const { uid, email} = result.user;
await addUserToFirestore(result.user as User); // Ensure to await Firestore addition
navigate('/'); // Navigate to the home page
// Send user data to backend
const response = await axios.post('/api/users/create', {
uid,
email
});

if (response.status === 201) {
navigate('/');
} else {
throw new Error('Failed to create user in PostgreSQL');
}
} catch (error) {
console.error(error);
// Handle errors here
}
}
} catch (error) {
console.error(error);
// Handle errors here
}
};

const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
@@ -74,7 +85,17 @@ const Signup: React.FC<SignupProps> = ({ toggleForm }) => {
const userCredential = await doCreateUserWithEmailAndPassword(email, password);
const user = userCredential.user;
await addUserToFirestore(user as User); // Ensure to await Firestore addition
navigate('/'); // Navigate to the home page
// Send user data to backend
const response = await axios.post('/api/users/create', {
uid: user.uid,
email: user.email
});

if (response.status === 201) {
navigate('/'); // Navigate to the home page after successful signup
} else {
throw new Error('Failed to create user in PostgreSQL');
}
} catch (error) {
console.error("Error signing up: ", error);
}
4 changes: 1 addition & 3 deletions CoVAR-app/src/tests/dashBoard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { render } from '@testing-library/react';
import Dashboard from '../dashboard/dashboard';

class MockResizeObserver {
@@ -16,6 +16,4 @@ describe('Dashboard Component', () => {
<Dashboard />
</div>);
});


});
20 changes: 2 additions & 18 deletions CoVAR-app/src/tests/sidebar.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { BrowserRouter as Router } from 'react-router-dom';
import '@testing-library/jest-dom/extend-expect';
import Sidebar from '../sidebar/sidebar';

// Mock Firebase services

jest.mock('../sidebar/components/userRole', () => ({
__esModule: true, // this property makes it work
default: jest.fn().mockReturnValue('admin'), // Mock the user role
default: jest.fn().mockReturnValue('admin'),
}));

jest.mock('firebase/app', () => ({
@@ -29,17 +27,7 @@ jest.mock('firebase/firestore', () => ({
getFirestore: jest.fn(),
}));

// // Mock the useNavigate hook from react-router-dom
// jest.mock('react-router-dom', () => ({
// ...jest.requireActual('react-router-dom'),
// useNavigate: jest.fn(),
// }));

// const mockNavigate = jest.requireMock('react-router-dom').useNavigate;

describe('Sidebar Component', () => {


test('renders the sidebar with all menu items', () => {
render(
<Router>
@@ -53,8 +41,4 @@ describe('Sidebar Component', () => {
expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByText('Logout')).toBeInTheDocument();
});




});
4 changes: 1 addition & 3 deletions CoVAR-app/src/tests/userList.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import { render } from '@testing-library/react';
import UserList from '../adminTools/components/userList';

jest.mock('../adminTools/components/userList', () => {
@@ -12,9 +12,7 @@ jest.mock('../adminTools/components/userList', () => {
};
});


describe('UserList Component', () => {
//test if the component renders
test('renders UserList component', () => {
render(<UserList />);
});
30 changes: 30 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -42,6 +42,36 @@ app.get('/users/all', async (req, res) => {
}
});

//postgres firebase synch
app.post('/users/create', async (req, res) => {
const { uid, email } = req.body;
const role = 'client'; // Default role

try {
// Check if user with email already exists
const checkUserQuery = `
SELECT * FROM users WHERE username = $1
`;
const existingUser = await pgClient.query(checkUserQuery, [email]);

if (existingUser.rows.length > 0) {
// User already exists
return res.status(409).send('User already exists');
}

// User does not exist, proceed with insertion
const insertUserQuery = `
INSERT INTO users (username, role)
VALUES ($1, $2)
`;
await pgClient.query(insertUserQuery, [email, role]);

res.status(201).send('User created successfully');
} catch (err) {
console.error('Error creating user:', err);
res.status(500).send('Server Error');
}
});

//Get all organizations
app.get('/organizations/all', async (req, res) => {

0 comments on commit 3bb01d3

Please sign in to comment.