SPRINT 3 ‐ Create Account with Backend - BlueJayBird11/UniJet GitHub Wiki
Frontend
In the frontend, a few things were changed.
First, a shared interface was made to represent the json format of the passenger (user):
export interface Passenger {
birthDate: string;
email: string;
passwordHash?: string;
phoneNumber: number;
firstName: string;
lastName: string;
userStatus: number;
carPool: boolean;
rating?: number;
schedule?: any;
}
handleSignup
The function handleSignup was changed by correcting the json format with the passenger interface, and calling a new function called "postPassenger"
const user: Passenger ={
birthDate: dob,
email: email,
passwordHash: password,
phoneNumber: +phone,
firstName: FirstName,
lastName: LastName,
userStatus: 0,
carPool: false
}
postPassenger(user);
postPassenger
This function sends a post request with the json body from above to add to the postgres table. The backend will tell the frontend if there any problems such as if the email is already in use.
const postPassenger = async(user: Passenger) => {
try {
const response = await fetch('http://localhost:8000/api/v1/passengers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(user), // Convert the passenger object to JSON
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const data = await response.json();
console.log('Success:', data);
setShowModal(true);
} catch (error) {
console.error('Error:', error);
}
};
Backend
The backend is only used for one request in the frontend, but it is divided into a couple of steps.
Email Duplicate Check
First, the backend uses a query to grab all the passengers using that email, which returns an empty list is there are none. If there is one already, the server sends a response to the frontend saying that the email is already in use.
const result = await pool.query(
"SELECT * FROM passengers WHERE email = $1",
[req.body.email]
);
console.log(result.rows.length);
if (result.rows.length === 1) {
res.status(409).json({
message: "Email already in use.",
});
throw new Error("Email in use");
}
Password Hash
The backend then uses the bcrypt library to hash the password with a salt of 10. This can be made more secure in the future.
const hash = await bcrypt.hash(req.body.passwordHash, 10);
Adding user to table
Then, the server sends a request to the database to add a new row to the passengers table with the new hash and the other given information.
const results = await pool.query(
"INSERT INTO passengers (birthDate, email, passwordHash, phoneNumber, firstName, lastName, userStatus, carPool, rating, schedule) \
VALUES ($1, $2, $3, $4, $5, $6, 0, $7, NULL, NULL) returning *",
[
req.body.birthDate,
req.body.email,
hash,
req.body.phoneNumber,
req.body.firstName,
req.body.lastName,
req.body.carPool,
]
);
res.status(201).json({
status: "success",
data: {
passengers: results.rows[0],
},
});