From f79465d3e0c32519b68d3c103ed645a764f01998 Mon Sep 17 00:00:00 2001 From: Nina1o1 Date: Wed, 6 Dec 2023 21:10:19 -0500 Subject: [PATCH 1/3] initial commit on passport jwt --- back-end/src/config/jwt-config.mjs | 31 ++++++++++++++++++++++++++++++ back-end/src/models/User.mjs | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 back-end/src/config/jwt-config.mjs diff --git a/back-end/src/config/jwt-config.mjs b/back-end/src/config/jwt-config.mjs new file mode 100644 index 0000000..9904129 --- /dev/null +++ b/back-end/src/config/jwt-config.mjs @@ -0,0 +1,31 @@ +import passportJWT from "passport-jwt"; +import User from "../models/User.mjs"; + +const ExtractJwt = passportJWT.ExtractJwt +const JwtStrategy = passportJWT.ExtractJwt + +// how the token is extracted and verified from the request +const jwtOptions = { + jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme("jwt"), //fromAuthHeaderAsBearerToken() + secretOrKey: process.env.JWT_SECRET, +} + +const jwtVerifyToken = async function (jwt_payload, done) { + console.log("JWT payload received", jwt_payload) // debugging + + // token expiration + + // match user in database + try { + const user = await User.findOne({ uuid: jwt_payload.uuid }) + if (!user) throw {jwtMessage: "user not found"} + return done(null, user) + + } catch (error) { + return done(null, false, {message: error.jwtMessage}) + } +} + +const jwtStrategy = new JwtStrategy(jwtOptions, jwtVerifyToken) + +export default jwtStrategy \ No newline at end of file diff --git a/back-end/src/models/User.mjs b/back-end/src/models/User.mjs index ccae9cd..ab85866 100644 --- a/back-end/src/models/User.mjs +++ b/back-end/src/models/User.mjs @@ -26,7 +26,7 @@ const userSchema = new mongoose.Schema({ __v: { type: Number // Number type for the version key } -}); +}) const User = model('User', userSchema,'users'); export default User; From 043722d97cb28075fef63f9704489350432ad802 Mon Sep 17 00:00:00 2001 From: Nina1o1 Date: Wed, 6 Dec 2023 21:22:07 -0500 Subject: [PATCH 2/3] add passport middleware --- back-end/src/app.mjs | 18 ++++++++---------- back-end/src/config/jwt-config.mjs | 6 ++++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/back-end/src/app.mjs b/back-end/src/app.mjs index 19e266f..56421e8 100644 --- a/back-end/src/app.mjs +++ b/back-end/src/app.mjs @@ -1,18 +1,16 @@ import express from 'express'; import url from 'url'; import path from 'path'; -// middlewares import multer from "multer"; -import bcrypt from 'bcryptjs'; import cors from 'cors'; -import "dotenv/config"; import dotenv from 'dotenv'; import morgan from 'morgan'; import session from 'express-session'; import mongoose from 'mongoose'; import { body, validationResult } from 'express-validator'; import jwt from 'jsonwebtoken'; - +import passport from 'passport' +import CustomJwtStrategy from './config/jwt-config.mjs'; // routes import loginRouter from './routes/loginRouter.mjs'; import registerRouter from './routes/registerRouter.mjs'; @@ -23,11 +21,9 @@ import getpieceRouter from './routes/getpieceRouter.mjs'; import resetpasswordRouter from './routes/resetpasswordRouter.mjs'; import resetemailRouter from './routes/resetemailRouter.mjs'; import searchArtsRouter from './routes/searchArtsRouter.mjs'; - import {addFavListRouter,favListRouter, getArts} from './routes/modifyFavListRouter.mjs' -import { configDotenv } from 'dotenv'; -const app = express(); +const app = express(); // use the morgan middleware to log all incoming http requests app.use(morgan("dev")); @@ -66,7 +62,11 @@ app.use(session({ })) console.log('Session secret:', process.env.SESSION_SECRET); -// other middlewares +// jwt strategy +passport.use(CustomJwtStrategy) + +// initialize passport +app.use(passport.initialize()) // routes that does not need authentication // app.post("/getpiece", getpieceRouter); @@ -101,8 +101,6 @@ const passwordValidationRules = [ // Optionally, include checks for special characters or uppercase letters ]; - - // routes that needs authentication // Account routes app.patch("/changeusername", usernameValidationRules, changeusernameRouter); //Finished diff --git a/back-end/src/config/jwt-config.mjs b/back-end/src/config/jwt-config.mjs index 9904129..930aa28 100644 --- a/back-end/src/config/jwt-config.mjs +++ b/back-end/src/config/jwt-config.mjs @@ -26,6 +26,8 @@ const jwtVerifyToken = async function (jwt_payload, done) { } } -const jwtStrategy = new JwtStrategy(jwtOptions, jwtVerifyToken) +const CustomJwtStrategy = () => { + return new JwtStrategy(jwtOptions, jwtVerifyToken) +} -export default jwtStrategy \ No newline at end of file +export default CustomJwtStrategy \ No newline at end of file From 0b2cc75f82f7e07e8c490fef8d7ff1cbc229bf78 Mon Sep 17 00:00:00 2001 From: Nina1o1 Date: Wed, 6 Dec 2023 21:32:34 -0500 Subject: [PATCH 3/3] remove uuid in local storage --- back-end/src/routes/loginRouter.mjs | 4 ++-- front-end/src/pages/Account/Account.jsx | 15 ++------------- front-end/src/pages/Authenticate/Login.jsx | 7 +------ 3 files changed, 5 insertions(+), 21 deletions(-) diff --git a/back-end/src/routes/loginRouter.mjs b/back-end/src/routes/loginRouter.mjs index 8a5d8f5..b948a4a 100644 --- a/back-end/src/routes/loginRouter.mjs +++ b/back-end/src/routes/loginRouter.mjs @@ -28,10 +28,10 @@ const loginRouter = async (req, res) => { return res.status(200).json({ message: "Successfully logged in!", accessToken, user: { - uuid: user.uuid, name: user.name, email: user.email - } }) + } + }) } catch (error) { return res.status(500).json({ message: "Internal server error." }); diff --git a/front-end/src/pages/Account/Account.jsx b/front-end/src/pages/Account/Account.jsx index bd822ad..a678c37 100644 --- a/front-end/src/pages/Account/Account.jsx +++ b/front-end/src/pages/Account/Account.jsx @@ -22,7 +22,6 @@ const AccountEdit = (props) => { const storedUserData = JSON.parse(localStorage.getItem('user') || '{}'); const [username, setUsername] = useState(storedUserData.name || 'John Doe'); const [email, setEmail] = useState(storedUserData.email || 'Asdfasdfasdf@nyu.edu'); - // console.log(storedUserData.email) // Set username and email on the screen useEffect(() => { @@ -63,12 +62,7 @@ const AccountEdit = (props) => { if(response?.data?.user){ setUsername(response.data.user.name); - const userData = { - uuid: response.data.user.uuid, - name: response.data.user.name, - email: response.data.user.email - }; - localStorage.setItem('user', JSON.stringify(userData)) + localStorage.setItem('user', JSON.stringify(response.data.user)) // localStorage.setItem('username', response.data.user.name); }else{ @@ -100,12 +94,7 @@ const AccountEdit = (props) => { if(response?.data?.user){ setEmail(response.data.user.email); - const userData = { - uuid: response.data.user.uuid, - name: response.data.user.name, - email: response.data.user.email - }; - localStorage.setItem('user', JSON.stringify(userData)) + localStorage.setItem('user', JSON.stringify(response.data.user)) }else{ console.log("Error!!!!!"); } diff --git a/front-end/src/pages/Authenticate/Login.jsx b/front-end/src/pages/Authenticate/Login.jsx index 965a61c..a459b73 100644 --- a/front-end/src/pages/Authenticate/Login.jsx +++ b/front-end/src/pages/Authenticate/Login.jsx @@ -40,12 +40,7 @@ const Login = () => { // Stores the token and user data in localStorage upon successful login localStorage.setItem('token', response.data.accessToken); - const userData = { - uuid: response.data.user.uuid, - name: response.data.user.name, - email: response.data.user.email - }; - localStorage.setItem('user', JSON.stringify(userData)); + localStorage.setItem('user', JSON.stringify(response.data.user)); setLoginMessage("Login successful!"); // Sets a success message navigate("/"); // Navigates to the home page or dashboard