Skip to content

Commit

Permalink
Merge pull request #186 from agiledev-students-fall2023/passport_jwt
Browse files Browse the repository at this point in the history
Passport jwt
  • Loading branch information
lunnnnnn authored Dec 7, 2023
2 parents a95d41a + 0b2cc75 commit 3413391
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 32 deletions.
18 changes: 8 additions & 10 deletions back-end/src/app.mjs
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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"));
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions back-end/src/config/jwt-config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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 CustomJwtStrategy = () => {
return new JwtStrategy(jwtOptions, jwtVerifyToken)
}

export default CustomJwtStrategy
2 changes: 1 addition & 1 deletion back-end/src/models/User.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
4 changes: 2 additions & 2 deletions back-end/src/routes/loginRouter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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." });
Expand Down
15 changes: 2 additions & 13 deletions front-end/src/pages/Account/Account.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 || '[email protected]');
// console.log(storedUserData.email)

// Set username and email on the screen
useEffect(() => {
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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!!!!!");
}
Expand Down
7 changes: 1 addition & 6 deletions front-end/src/pages/Authenticate/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 3413391

Please sign in to comment.