Skip to content

Commit

Permalink
updating cookie setting, reformat usercontrollers, add jwt which is n…
Browse files Browse the repository at this point in the history
…ot quite working
  • Loading branch information
kiranbanger committed Aug 18, 2022
1 parent cf5b54d commit 912b11c
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 58 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"express-session": "^1.17.3",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^4.8.1",
"mongoose": "^6.5.1",
"nodemon": "^2.0.19",
Expand Down
36 changes: 28 additions & 8 deletions server/controllers/cookieController.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,40 @@
//server/cookieController.js
const jwt = require('jsonwebtoken');
require("dotenv").config();

const cookieController = {};

/*
* setSSIDCookie - store the user id in a cookie
*/
cookieController.setSSIDCookie = (req, res, next) => {
// console.log('res.locals.user is: ', res.locals.user);
if (res.locals.user) {
console.log('cookieController.setSSIDCookie res.locals.user._id.id: ', res.locals.user._id.id )
res.cookie('ssid', res.locals.user._id.id, {httpOnly: true});
return next();
} else {
return next();
console.log('in set cookie, res.locals.userId is: ', res.locals.userId);
if (!res.locals.userId){
return next({
log: 'Error in cookieController.setSSIDCookie - no user info.',
message: {err: 'Error setting cookies, see server log for details.'}
})
}
// SERVER HANGS HERE - SOMETHING UP WITH JWT SIGNING BLOCK
jwt.sign({ userId: res.locals.userId }, process.env.SECRET), (err, token) => {// promises not supported
console.log(token)
//try {
if(err){
return next({
message: {err: 'Error in cookieController.setSSIDCookie.'},
log: `Problem creating token: ${err}`
})
}
res.cookie('ssid', token);
return next()
//}
// catch (error) {
// return next({
// message: {err: 'Error in cookieController.setSSIDCookie.'},
// log: `Problem setting cookies: ${err}`
// })
// }
}

};

module.exports = cookieController;
98 changes: 57 additions & 41 deletions server/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//server/userController.js
const {User} = require('../model.js');
const { User } = require('../model.js');
const fs = require('fs');
const userController = {};
const bcrypt = require('bcrypt');
require("dotenv").config();

/**
* getAllUsers - retrieve all users from the database and stores it into res.locals
Expand All @@ -27,22 +28,42 @@ userController.getAllUsers = (req, res, next) => {
* createUser - create and save a new User into the database.
*/
userController.createUser = (req, res, next) => {
// write code here
const { username, password } = req.body;
if(!username || !password) return next('Missing username or password in userController.createUser');

const hash = bcrypt.hashSync(password, 10);
if(!username || !password){
return next({
log: 'Error in userController.createUser - no username and/or password.',
message: {err: 'Error creating your account, invalid username and/or password.'}
});
}

User.create({ username, password: hash }, (err, user) => {
if(err) {
return next({error: err});
}else{
console.log('createUser user._doc: ', user._doc)
res.locals.user = user._doc;
return next()
}
bcrypt.hash(password, Number(process.env.SALTROUNDS))
.then( hash => {
const newUser = new User({
username: username,
password: hash
})
return newUser

})
.then( newUserData => {
//console.log(newUserData)
return newUserData.save()
// need to store user_id in locals
})
.then( data => {
//console.log(data)
//console.log('createUser object id: ', data._id.toString())
res.locals.userId = data._id.toString();
console.log(res.locals.userId)
return next()
})
.catch( err =>
next({
log: `Error in userController.createUser: ${err}`,
message: {err: 'Error creating your account, see server log for details.'}
})

)
};

/**
Expand All @@ -51,39 +72,34 @@ userController.createUser = (req, res, next) => {
* against the password stored in the database.
*/
userController.verifyUser = (req, res, next) => {
// write code here
const { username, password } = req.body;
// console.log('verify username: ',username);
// console.log('verify password: ',password);
//check against res.locals.users if username exists and password matches

if (!username || !password)
return next('Missing username or password in userController.verifyUser');
return next({
log: 'Error in userController.verifyCookie - invalid username and/or password.',
message: {err: 'Error with your account, invalid username and/or password.'}
});

User.findOne({ username: username }, (err, user) => {
if (err) {
return next('Error in userController.verifyUser (first err): ' + JSON.stringify(err));
} else if (!user) {
console.log('verifyUser user does not exist');
// res.redirect('/signup');
res.locals.path='/signup';
return next();

} else {
bcrypt.compare(password, user.password).then((result) => {
if (!result) {
// res.redirect('/login');
res.locals.path = '/login';
console.log('wrong password!');
return next()
} else {
res.locals.user = user;
res.locals.path = '/';
res.locals.loggedIn = true;
return next();
}
});
User.findOne({ username })
.then( response => {
console.log('user lookup response: ', response)
if(!response) {
console.log('user does not exist')
// username does not exist
// redirect to /signup - localhost:8080/signup won't work?
res.redirect('https://localhost:8080/signup') // does not end req-res cycle and continues to next middleware
return next()
}
res.locals.userId = response._id.toString();
// res.locals.path = '/';
// res.locals.loggedIn = true;
return next();
})
.catch ( err => next({
log: `Error in userController.verifyUser: ${err}`,
message: {err: 'Error with your account, invalid username and/or password.'}
}))

};

module.exports = userController;
19 changes: 10 additions & 9 deletions server/server.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
//server/server.js
const path = require('path');
const express = require('express');
const axios = require('axios');
const coreJsCompat = require('@babel/preset-env/data/core-js-compat');
//const axios = require('axios');
//const coreJsCompat = require('@babel/preset-env/data/core-js-compat');

// Connects to database
require('./model').connectToDB();

const controller = require('./controllers/controller');

const cors = require('cors');
const mongoose = require('mongoose');
//const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const session = require('express-session');
//const session = require('express-session');
const userController = require('./controllers/userController');
const cookieController = require('./controllers/cookieController');
const sessionController = require('./controllers/sessionController');
//const sessionController = require('./controllers/sessionController');

const PORT = 3000;

Expand Down Expand Up @@ -54,15 +54,16 @@ router.post('/search',

//SIGNUP routes
router.post('/signup', userController.createUser, cookieController.setSSIDCookie, (req, res, err) => {
// send response back to front-end and do redirect at frontend
res.status(200).send();
console.log('signup successful')
res.status(200).send(); // redirect is already handled on frontend, but cookie is not set
})

//LOGIN routes
router.post('/login', userController.verifyUser, cookieController.setSSIDCookie, (req, res, err) => {
// redirects happens in controllers
// redirect to '/
console.log('app.post login sucessful')
res.send(res.locals);
//res.send(res.locals);
res.redirect('http://localhost:8080')// does not work
})

//AUTHORIZED routes
Expand Down

0 comments on commit 912b11c

Please sign in to comment.