oss-slu / Enhancing-Bioinformatics-Research-through-LLM

Apache License 2.0
0 stars 0 forks source link

created express server to handle signup requests/write to db #18

Closed PranaviKolouju closed 1 month ago

PranaviKolouju commented 1 month ago

Fixes #12

What was changed?

I created a MongoDB cluster with a new database that will be used to store new user credentials. I also initialized an express server that establishes a connection to the database to create a new user with the following information: username, email, password.

Why was it changed?

Our signup page collects the following information from a new user: username, email, and password. This code is necessary to create a new user in the database using these credentials. This code is also needed to verify that the new username and email are not associated with existing users. This code also hashes the password before storing it in the database which is necessary as a security measure.

How was it changed?

I added a Connection.js file under the Database folder. This file uses the user credentials from the .env file (not committed to repository) to establish a connection with the MongoDB database.

const uri = process.env.MONGO_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function connectDB() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");
  } catch (error) {
    console.error("Error connecting to MongoDB", error);
  }
}
connectDB();

This server contains an API endpoint ("/signup") that creates a new user in the database with the following credentials: username, email, and password. The password is hashed using the bcrypt library before being entered into the database.

const hashedPassword = await bcrypt.hash(password, saltRounds);

const result = await collection.insertOne({
  user_name, 
  email, 
  password: hashedPassword  
});

However, a new user will not be created if the username or the email already exists in the database. These errors are handled via error responses.

const existingEmail = await collection.findOne({ email: email });
if (existingEmail) {
  return res.status(400).json({ message: "Email is already in use" });
}

const existingUserName = await collection.findOne({ user_name: user_name });
if (existingUserName) {
  return res.status(400).json({ message: "Username is already in use" });
}

Screenshots that show the changes (if applicable):

image

image