diff --git a/backend/package.json b/backend/package.json index 2cd802a..f7ab3bb 100644 --- a/backend/package.json +++ b/backend/package.json @@ -4,6 +4,7 @@ "description": "", "main": "index.js", "scripts": { + "start": "nodemon server.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], diff --git a/backend/src/controllers/authController.js b/backend/src/controllers/authController.js index 87df675..5bf1ab8 100644 --- a/backend/src/controllers/authController.js +++ b/backend/src/controllers/authController.js @@ -7,49 +7,59 @@ const { OTPGenerator } = require('../utils/otpgenerator'); require('dotenv').config(); -exports.signup = async (req, res) => { +const signup = async (req, res, isWeb) => { try { // Extract user information const otp = OTPGenerator() - + const { email, password, name } = req.body; const saltRounds = 10; // Adjust const hashedPassword = await bcrypt.hash(password, saltRounds); + const user = await User.findOne({ email }); + if (!user){ + + // Create a new user const user = new User({ email, hashedPassword, name, otp }); await user.save(); - - console.log("Start"); - await emailModule.sendOTP(email, otp) - - - // Send the response + // Send the response const token = jwt.sign({ name: user.name, isVerified: user.isVerified, email: user.email }, process.env.SECURITY_KEY, { expiresIn: '7day' }); + if (isWeb) { + const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds + const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds + res.cookie('token', token, { + expires: expirationDate, + }); + res.json({ message: 'Signup successful' }); + }else{ + return res.header("x-auth-token", token).status(201).json({ token, success: true }); + + } - const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds - const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds - res.cookie('token', token, { - expires: expirationDate, - - }); - res.json({ message: 'Signup successful' }); + }else{ + return res.status(404).json({error : "User exists", success : false}) + } } catch (error) { res.status(500).json({ error: 'Signup failed' }); } }; +exports.signUpWeb = async (req, res) => { + return signup(req, res, true) +} +exports.signUpApp = async (req, res) => { + return signup(req, res, false) +} - - -exports.login = async (req, res) => { +const login = async (req, res, isWeb) => { try { const { email, password } = req.body; @@ -57,106 +67,49 @@ exports.login = async (req, res) => { const user = await User.findOne({ email }); if (!user) { - return res.status(404).json({ error: 'User not found' }); + return res.status(404).json({ error: 'User not found', success: false }); } // Compare the provided password with the hashed password in the database const passwordMatch = await bcrypt.compare(password, user.hashedPassword); if (!passwordMatch) { - return res.status(401).json({ error: 'Incorrect password' }); - } - - // If the username and password are correct, generate a JWT token - const token = jwt.sign({ name: user.name, isVerified: user.isVerified, email: user.email }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - - - const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds - const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds - res.cookie('token', token, { - expires: expirationDate, - - }); - // Send the token in the response - res.json({ message: 'Login successful' }); - } catch (error) { - console.error(error); - res.status(500).json({ error: 'Login failed' }); - } -}; - -exports.loginApp = async (req, res) => { - try { - const { email, password } = req.body; - - // Check if the username exists in the database - const user = await User.findOne({ email }); - - if (!user) { - return res.status(404).json({ error: 'User not found' }); - } - - const passwordMatch = await bcrypt.compare(password, user.hashedPassword); - - if (passwordMatch) { - - const token = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - return res.header("x-auth-token", token).status(201).json({token}); - + return res.status(401).json({ error: 'Incorrect password', success: false }); } else { - console.log("Invalid credentials.", user.email); - return res.status(401).json({ error: 'Incorrect password' }); - } - } catch (error) { - console.error("Error during login:", error); - res.status(500).json({error: "An error occurred during login."}); - } -}; - -exports.signUpApp = async (req, res) => { - try { - // Extract user information - const { email, password, name } = req.body; - const user = await User.findOne({ email }) - if (user) { - console.log("User already has an account") - }else{ - const saltRounds = 10; // Adjust - const hashedPassword = await bcrypt.hash(password, saltRounds); - // Create a new user - const user = new User({ email, hashedPassword, name }); - await user.save(); - - const token = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - return res.header("x-auth-token", token).status(201).json({token}); + // If the username and password are correct, generate a JWT token + const token = jwt.sign({ name: user.name, isVerified: user.isVerified, email: user.email }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); + if (isWeb) { + const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds + const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds + res.cookie('token', token, { + expires: expirationDate, + + }); + // Send the token in the response + res.json({ message: 'Login successful' }); + } else { + return res.header("x-auth-token", token).status(201).json({ token, success: true }); + } } - - - - - - - - } catch (error) { - console.log('hi') console.error(error); - res.status(500).json({ error: 'Signup failed' }); + res.status(500).json({ error: 'Login failed' }); } }; - -exports.googleLogin = async (req , res) => { - return googleLoginBase(req,res, true) +exports.loginWeb = async (req, res) => { + return login(req, res, true) } +exports.loginApp = async (req, res) => { + return login(req, res, false) +} - - +exports.googleLogin = async (req, res) => { + return googleLoginBase(req, res, true) +} const googleLoginBase = async (req, res, isWeb) => { try { - - const { token } = req.body console.log({ token }) //verfication of user by fetching user information from google @@ -184,19 +137,20 @@ const googleLoginBase = async (req, res, isWeb) => { await newUser.save() // Send the response + newUser.isVerified = true const newToken = jwt.sign({ name: newUser.name, isVerified: newUser.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - if(isWeb){ - res.cookie("token", newToken,{ maxAge: 900000, httpOnly: true }); + if (isWeb) { + res.cookie("token", newToken, { maxAge: 900000, httpOnly: true }); res.json({ message: 'Login successful' }); - }else{ - res.json({message : 'Login Successful', token}) + } else { + res.json({ message: 'Login Successful', token }) } - - - } + + } + user.isVerified = true const newToken = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); @@ -211,66 +165,63 @@ const googleLoginBase = async (req, res, isWeb) => { } -exports.facebooklogin = async ( req,res) => { - - const { token , userID } = req.body - console.log({ token , userID }) - //verfication of user by fetching user information from google - const facebookResponse = await fetch(`https://graph.facebook.com/${userID}?fields=id,name,email&access_token=${token}`, { - method: "GET", headers: { - Authorization: `Bearer ${token}`, - Accept: 'application/json' - } - }).then(res => res.json()) +exports.facebooklogin = async (req, res) => { + + const { token, userID } = req.body + console.log({ token, userID }) + //verfication of user by fetching user information from google + const facebookResponse = await fetch(`https://graph.facebook.com/${userID}?fields=id,name,email&access_token=${token}`, { + method: "GET", headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json' + } + }).then(res => res.json()) - console.log(facebookResponse) - // const { email, name } = googleResponse - // //see if there is an user with that email already - // const user = await User.findOne({ email }) - // console.log({ email, name }) + console.log(facebookResponse) + // const { email, name } = googleResponse + // //see if there is an user with that email already + // const user = await User.findOne({ email }) + // console.log({ email, name }) - // if (!user) { - // //Generate random password - // const password = GenerateRandomPassword - // const saltRounds = 10; // Adjust - // const hashedPassword = await bcrypt.hash(password, saltRounds); + // if (!user) { + // //Generate random password + // const password = GenerateRandomPassword + // const saltRounds = 10; // Adjust + // const hashedPassword = await bcrypt.hash(password, saltRounds); - // //create a new user - // const newUser = new User({ email, hashedPassword, name }) - // await newUser.save() + // //create a new user + // const newUser = new User({ email, hashedPassword, name }) + // await newUser.save() - // // Send the response - // const newToken = jwt.sign({ name: newUser.name, isVerified: newUser.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - // res.cookie("token", newToken); - // res.json({ message: 'Login successful' }); + // // Send the response + // const newToken = jwt.sign({ name: newUser.name, isVerified: newUser.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); + // res.cookie("token", newToken); + // res.json({ message: 'Login successful' }); - // } + // } - // const newToken = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); + // const newToken = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' }); - // res.cookie("token", newToken); + // res.cookie("token", newToken); + + // // Send the token in the response + // res.json({ message: 'Login successful' }); - // // Send the token in the response - // res.json({ message: 'Login successful' }); - } -exports.googleLoginApp = async (req,res) => { - const { token } = req.body +exports.googleLoginApp = async (req, res) => { + return googleLoginBase(req, res, false) } -exports.verify = async (req, res) => { +const verify = async (req, res, isWeb) => { try { const { token, otp } = req.body - - - console.log(token) - + console.log({token , otp}) jwt.verify(token, process.env.SECURITY_KEY, (err, decoded) => { if (err) { // Token is invalid or has expired @@ -280,14 +231,8 @@ exports.verify = async (req, res) => { final = decoded } }); - const email = final.email - - - - const user = await User.findOne({ email }) - if (!user) { return res.status(404).json({ message: "User not found" }) } @@ -300,16 +245,16 @@ exports.verify = async (req, res) => { const token = jwt.sign({ name: user.name, isVerified: user.isVerified, email: user.email }, process.env.SECURITY_KEY, { expiresIn: '7day' }); - - const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds - const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds - res.cookie('token', token, { - expires: expirationDate, - - }); - - - return res.status(200).json({ message: "User verified successfully" }) + if (isWeb) { + const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds + const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds + res.cookie('token', token, { + expires: expirationDate + }) + return res.status(200).json({ message: "User verified successfully" }) + } else { + return res.header("x-auth-token", token).status(201).json({ token, success: true }); + } } else { return res.status(400).json({ message: "Invalid OTP" }) } @@ -319,17 +264,21 @@ exports.verify = async (req, res) => { } } - - -exports.logout = async (req,res) =>{ - try{ +exports.verificationWeb = async (req, res) => { + return verify(req, res, true) +} +exports.verificationApp = async (req, res) => { + return verify(req, res, false) +} +exports.logout = async (req, res) => { + try { res.clearCookie('token') - res.json({msg:"Done"}) + res.json({ msg: "Done" }) } - catch(err){ + catch (err) { res.error(err) } - + } diff --git a/backend/src/routes/authRoutes.js b/backend/src/routes/authRoutes.js index 30f0c70..bbdee2d 100644 --- a/backend/src/routes/authRoutes.js +++ b/backend/src/routes/authRoutes.js @@ -1,14 +1,19 @@ const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); -router.post('/signup', authController.signup); -router.post('/login', authController.login); -router.post('/googleLogin',authController.googleLogin) +router.post('/signup', authController.signUpWeb); +router.post('/signUpApp',authController.signUpApp); + +router.post('/login', authController.loginWeb); router.post('/loginApp', authController.loginApp); -router.post('/signUpApp',authController.signUpApp) + +router.post('/googleLogin',authController.googleLoginApp); + router.post('/facebooklogin',authController.facebooklogin); + router.post('/logout', authController.logout); -router.post('/verifyotp', authController.verify); +router.post('/verifyotp', authController.verificationWeb); +router.post('/verifyOtpApp',authController.verificationApp) module.exports = router; diff --git a/webapp/src/components/GoogleLoginButton.js b/webapp/src/components/GoogleLoginButton.js index 2c98381..d1e1bcd 100644 --- a/webapp/src/components/GoogleLoginButton.js +++ b/webapp/src/components/GoogleLoginButton.js @@ -2,16 +2,19 @@ import React, { useState, useEffect } from 'react'; import { GoogleLogin, useGoogleLogin } from '@react-oauth/google'; import axios from 'axios'; import Button from 'react-bootstrap/Button'; +import { useNavigate } from 'react-router-dom'; function GoogleLoginButton() { + const navigate = useNavigate() const responseMessage = (response) => { axios.defaults.withCredentials = true axios.post('http://localhost:5000/api/auth/googleLogin', { token: response.access_token }) .then(response => { // Handle the successful response here console.log(response.data); - alert('login successful') + // alert('login successful') + navigate('/dashboard',{replace : true}) }) .catch(error => { // Handle any errors that occur during the request diff --git a/webapp/src/views/Login.js b/webapp/src/views/Login.js index 3d60671..fad5088 100644 --- a/webapp/src/views/Login.js +++ b/webapp/src/views/Login.js @@ -8,6 +8,7 @@ import { useAuthContext } from "../context/AuthContext"; import axios from 'axios'; import { getSessionCookie } from "../utils/cookie"; import jwt_decode from 'jwt-decode' +import GoogleLoginButton from "../components/GoogleLoginButton"; export default function Login() { const navigate = useNavigate() @@ -95,7 +96,9 @@ export default function Login() {

OR

*/}

OR

- + */}