Skip to content
Permalink
Browse files
Merge pull request #5 from caracold/msgAuth
authCheck for message routes
  • Loading branch information
caracold committed Apr 23, 2020
2 parents 2987cb4 + 039a1f7 commit 6fa4507a1e1908d8ac36db74ecde6d37aaf35064
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 10 deletions.
@@ -3,8 +3,10 @@ const User = require('../models/user');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

//On Get request, return all item objects in the database
exports.getAllItems = (req, res, next) => {
Item.find()
//Without the __v argument as it has no use to the app
.select('-__v')
.exec()
.then(docs => {
@@ -20,9 +22,10 @@ exports.getAllItems = (req, res, next) => {
askPrice: doc.askPrice,
location: doc.location,
picture: doc.pictures,
//with each item, also return a request link to the individual item for more information
request: {
type: 'GET',
url: 'https://caracold-304resit-api.herokuapp.com/itemlist' + doc._id
url: 'https://caracold-304resit-api.herokuapp.com/itemlist/' + doc._id
}
}
})
@@ -37,7 +40,9 @@ exports.getAllItems = (req, res, next) => {
});
}

//Handle post request to create a new item in the database
exports.newItem = (req, res, next) => {
//The poster's id is obtained from the token and stored in the databse along with the item
const decoded = jwt.decode(req.header.token);
const userId = decoded.username;
const item = new Item({
@@ -65,10 +70,7 @@ exports.newItem = (req, res, next) => {
condition: result.condition,
askPrice: result.askPrice,
location: result.location,
picture: result.picture,
request: {
type: 'GET',
url: 'https://caracold-304resit-api.herokuapp.com/itemlist' + result._id
picture: result.picture
}
}
});
@@ -81,6 +83,7 @@ exports.newItem = (req, res, next) => {
});
}

//Handles Get request for specific item by id
exports.getItem = (req, res, next) => {
const id = req.params.itemId;
Item.findById(id)
@@ -101,6 +104,7 @@ exports.getItem = (req, res, next) => {
})
}

//Handles delete request to remove specified item from the database
exports.deleteItem = (req, res, next) => {
const id = req.params.itemId;
Item.remove({ _id: id })
@@ -3,7 +3,9 @@ const User = require('../models/user');
const Item = require('../models/item');
const jwt = require('jsonwebtoken');

//Handles get request to show all messages in the database targetted at the user
exports.getInbox = (req, res, next) => {
//By obtaning the username from the token, finds the messages within the database that are specifically targetted at the user
const decoded = jwt.decode(req.header.token);
const userId = decoded.username;
Message.find({ destination: userId }).select('-__v').exec()
@@ -14,9 +16,10 @@ exports.getInbox = (req, res, next) => {
_id: doc._id,
sender: doc.sender,
title: doc.title,
//Also returns request link to get the full message from the API
request: {
type: 'GET',
url: 'https://caracold-304resit-api.herokuapp.com/inbox' + doc._id
url: 'https://caracold-304resit-api.herokuapp.com/inbox/' + doc._id
}
}
})
@@ -31,6 +34,7 @@ exports.getInbox = (req, res, next) => {
});
}

//Handles post request to send a message, using the token to set the sender to the current user
exports.sendMessage = (req, res, next) => {
const decoded = jwt.decode(req.header.token);
const userId = decoded.username;
@@ -66,6 +70,7 @@ exports.sendMessage = (req, res, next) => {
});
}

//Handles get requests where for messages sent by, rather than to, the user
exports.getSent = (req, res, next) => {
const decoded = jwt.decode(req.header.token);
const userId = decoded.username;
@@ -95,6 +100,7 @@ exports.getSent = (req, res, next) => {
});
}

//Fetches the full information of a specific message from the database
exports.getMessage = (req, res, next) => {
const id = req.params.msgId;
Message.findById(id)
@@ -3,28 +3,34 @@ const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');

//Handles post requests to add a new user to the database
exports.signup = (req, res, next) => {
//First check that username does not already exist
User.find({ username: req.body.username })
.exec()
.then(user => {
//then, check that there is a username
if (user.length >= 1) {
return res.status(422).json({
message: 'Username is already taken.'
})
} else {
//try to encrypt the password
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
})
} else {
//and if all succeeds, create a new user object
const user = new User({
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
password: hash,
rating: 0,
authlevel: req.body.authlevel
});
//to save in the database
user.save()
.then(result => {
console.log(result);
@@ -44,21 +50,27 @@ exports.signup = (req, res, next) => {
});
}

//Handles post request for signing in
exports.signin = (req, res, next) => {
//First check that the user exists
User.find({ username: req.body.username }).exec()
.then(user => {
//Check that there is a username
if (user.length < 1) {
return res.status(401).json({
message: 'Login failed.'
})
} else {
//Compare the password
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
//When something goes wrong, return an error with minimal information to ensure security
return res.status(401).json({
message: 'Login failed.'
})
}
if (result) {
//if the login is successful, attribute a Json Web Token to the user that lasts 2 hours
const token = jwt.sign({
username: user[0].username,
_id: user[0]._id,
@@ -85,6 +97,7 @@ exports.signin = (req, res, next) => {
});
}

//Handle delete requests to remove a user from the database
exports.deleteUser = (req, res, next) => {
User.remove({ _id: req.params.userId }).exec()
.then(result => {
@@ -5,6 +5,7 @@ const multer = require('multer');
const authCheck = require('../auth/check_auth');
const itemControl = require('../controllers/items');

//Setting the storage destination and file naming convention for image uploads
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
@@ -15,6 +16,7 @@ const storage = multer.diskStorage({
}
});

//Ensuring only image files are accepted to prevent unwanted uploads and errors
const fTypeFilter = function(req, file, cb) {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
@@ -23,6 +25,7 @@ const fTypeFilter = function(req, file, cb) {
}
};

//Middleware to handle file upload with the parameters set above
const upload = multer({
storage: storage,
limits: {
@@ -35,6 +38,7 @@ const Item = require('../models/item');

router.get('/', itemControl.getAllItems);

//authCheck prevents users not logged in from creating new items.
router.post('/', authCheck, upload.single('picture'), itemControl.newItem);

router.get('/:itemId', itemControl.getItem);
@@ -3,13 +3,14 @@ const router = express.Router();
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const msgControl = require('../controllers/messages');
const authCheck = require('../auth/check_auth')

router.get('/', msgControl.getInbox);
router.get('/', authCheck, msgControl.getInbox);

router.post('/', msgControl.sendMessage);
router.post('/', authCheck, msgControl.sendMessage);

router.get('/sent', msgControl.getSent);
router.get('/sent', authCheck, msgControl.getSent);

router.get('/:msgid', msgControl.getMessage);
router.get('/:msgid', authCheck, sgControl.getMessage);

module.exports = router;

0 comments on commit 6fa4507

Please sign in to comment.