import express from 'express'; import { DB_NAME, getDatabaseClient } from '../db-utils'; import bcrypt from 'bcrypt'; import { generateJWT, SALT_ROUNDS } from './auth'; const authRoutes = express.Router(); authRoutes.get('/users/', async (request, response) => { console.log(request); response.send("List of users will be displayed"); }); authRoutes.post('/register-applicant/', async (request, response) => { const name = request.body.name; const email = request.body.email; const password = request.body.password; const userType = 'APPLICANT'; const isVerified = false; const userCollection = getDatabaseClient().db(DB_NAME).collection('users'); // Check if form is filled if (!name || !email || !password) { response.status(400); response.send("Please field the required fields"); return; } try { const userWithSameMail = await userCollection.find({ email, }).count(); if (userWithSameMail > 0) { response.status(400); response.send('EmailID already exists'); return; } } catch(e) { console.log(e); return; } try { bcrypt.hash(password, SALT_ROUNDS, (error, hashedPassword) => { if (error) { throw error; } userCollection.insertOne({ name, email, password: hashedPassword, isVerified, userType, }); }); response.send("Registeration Complete, Please verify your profile to proceed further"); } catch (e) { console.log(e); } return; }); authRoutes.post('/api-auth/', async (request, response) => { const email = request.body.email; const password = request.body.password; const userType = request.body.userType; if (!email || !password || !userType) { response.status(400); response.send("Please field the required fields"); return; } const userCollection = getDatabaseClient().db(DB_NAME).collection('users'); let users = await userCollection.find({ email, userType, }).toArray(); const matchedUser = users[0]; if (!matchedUser) { response.status(400); response.send('Wrong credentials'); return; } else if (!matchedUser.isVerified) { response.status(400); response.send('Please complete user verification'); return; } let passwordComparisonResult: boolean; try { passwordComparisonResult = await bcrypt.compare(password, matchedUser.password); if (passwordComparisonResult) { response.send({ id: matchedUser._id, token: generateJWT(matchedUser._id), }); } else { response.status(400); response.send('Wrong credentials'); } } catch(e) { response.sendStatus(500); response.json(e); } return; // let passwordComparisonResult: boolean; // try { // passwordComparisonResult = await bcrypt.compare(password, user.password); // } }); export default authRoutes;