Update
This commit is contained in:
parent
4dfd8cd516
commit
5a64568824
22 changed files with 702 additions and 194 deletions
3
backend/app/config/mongodb.config.js
Normal file
3
backend/app/config/mongodb.config.js
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
module.exports = {
|
||||
url: "mongodb://127.0.0.1:27017/polynotfound"
|
||||
};
|
||||
9
backend/app/config/response.config.js
Normal file
9
backend/app/config/response.config.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
function sendMessage (res, successCode, data) {
|
||||
return res.status(200).json({ status: 'success', successCode: successCode, data: data });
|
||||
}
|
||||
|
||||
function sendError (res, statusCode, errorCode, reason) {
|
||||
return res.status(statusCode).json({ status: 'error', errorCode: errorCode, reason: reason });
|
||||
}
|
||||
|
||||
module.exports = { sendMessage, sendError };
|
||||
67
backend/app/config/sessionJWT.config.js
Normal file
67
backend/app/config/sessionJWT.config.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
const sessionJWTConfig = require ('jsonwebtoken');
|
||||
require('dotenv').config({ path: './app/.env' });
|
||||
const {sendError, sendMessage} = require ("./response.config");
|
||||
|
||||
if(process.env.JWTRS256_PRIVATE_KEY === undefined || process.env.JWTRS256_PUBLIC_KEY === undefined){
|
||||
console.log('Error Env Variables');
|
||||
process.exit();
|
||||
}
|
||||
|
||||
console.log('Env variables received');
|
||||
const JWTRS256_PRIVATE_KEY = Buffer.from(process.env.JWTRS256_PRIVATE_KEY, 'base64');
|
||||
const JWTRS256_PUBLIC_KEY = Buffer.from(process.env.JWTRS256_PUBLIC_KEY, 'base64');
|
||||
|
||||
function createSessionJWT (mail) {
|
||||
return sessionJWTConfig.sign(
|
||||
{
|
||||
mail: mail,
|
||||
midExp: Math.floor(Date.now() / 1000) + 1800
|
||||
},
|
||||
JWTRS256_PRIVATE_KEY,
|
||||
{
|
||||
algorithm: 'RS256',
|
||||
expiresIn: '1h'
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function createSessionCookie(req, res, payload) {
|
||||
let jwtToken;
|
||||
if ((typeof payload.mail !== 'undefined') &&
|
||||
(typeof payload.midExp !== 'undefined') &&
|
||||
(Math.floor(Date.now() / 1000) <= payload.midExp)) {
|
||||
jwtToken = req.headers.cookie;
|
||||
}
|
||||
else {
|
||||
jwtToken = createSessionJWT(payload.mail);
|
||||
}
|
||||
res.cookie('SESSIONID', jwtToken, {httpOnly:true, secure:false});
|
||||
}
|
||||
module.exports.createSessionCookie = createSessionCookie;
|
||||
|
||||
function decodeSessionCookie(sessionid, res) {
|
||||
if (typeof sessionid === 'undefined') {
|
||||
return { mail: -1 };
|
||||
}
|
||||
try {
|
||||
const token = sessionJWTConfig.verify(
|
||||
sessionid,
|
||||
JWTRS256_PUBLIC_KEY,
|
||||
{algorithms: ['RS256']});
|
||||
return sendMessage(res,1,{token: token});
|
||||
}
|
||||
catch (err) {
|
||||
return sendError(res,-1,{mail: -1});
|
||||
}
|
||||
}
|
||||
module.exports.decodeSessionCookie = decodeSessionCookie;
|
||||
|
||||
function getSession (sessionid, res) {
|
||||
return decodeSessionCookie(sessionid, res);
|
||||
}
|
||||
module.exports.getSession = getSession;
|
||||
|
||||
function setSessionCookie (req, res, session) {
|
||||
createSessionCookie(req, res, session);
|
||||
}
|
||||
module.exports.setSessionCookie = setSessionCookie;
|
||||
117
backend/app/controllers/tutorial.controller.js
Normal file
117
backend/app/controllers/tutorial.controller.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
const db = require("../models/mongodb.model");
|
||||
const {sendError, sendMessage} = require ("../config/response.config");
|
||||
const Tutorial = db.tutorials;
|
||||
|
||||
// Create and Save a new Tutorial
|
||||
exports.create = (req, res) => {
|
||||
// Validate request
|
||||
if (!req.body.title) {
|
||||
sendError(res, 400,-1,"Content can not be empty!" );
|
||||
}
|
||||
|
||||
// Create a Tutorial
|
||||
const tutorial = new Tutorial({
|
||||
title: req.body.title,
|
||||
description: req.body.description,
|
||||
published: req.body.published ? req.body.published : false
|
||||
});
|
||||
|
||||
// Save Tutorial in the database
|
||||
tutorial
|
||||
.save(tutorial)
|
||||
.then(data => {
|
||||
sendMessage(res, 1, data)
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res, 500,-1,err.message || "Some error occurred while creating the Tutorial.");
|
||||
});
|
||||
};
|
||||
|
||||
// Retrieve all Tutorials from the database.
|
||||
exports.findAll = (req, res) => {
|
||||
const title = req.query.title;
|
||||
let condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};
|
||||
|
||||
Tutorial.find(condition)
|
||||
.then(data => {
|
||||
sendMessage(res, 1, data)
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Some error occurred while retrieving tutorials.");
|
||||
});
|
||||
};
|
||||
|
||||
// Find a single Tutorial with an id
|
||||
exports.findOne = (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
Tutorial.findById(id)
|
||||
.then(data => {
|
||||
if (!data)
|
||||
sendError(res,404,-1,"Not found Tutorial with id " + id );
|
||||
else sendMessage(res, 1, data);
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Error retrieving Tutorial with id=" + id );
|
||||
});
|
||||
};
|
||||
|
||||
// Update a Tutorial by the id in the request
|
||||
exports.update = (req, res) => {
|
||||
if (!req.body) {
|
||||
sendError(res,400,-1,"Data to update can not be empty!");
|
||||
}
|
||||
|
||||
const id = req.params.id;
|
||||
|
||||
Tutorial.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
|
||||
.then(data => {
|
||||
if (!data) {
|
||||
sendError(res,404,-1,`Cannot update Tutorial with id=${id}. Maybe Tutorial was not found!`);
|
||||
} else sendMessage(res, 1, { message: "Tutorial was updated successfully." });
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Error updating Tutorial with id=" + id);
|
||||
});
|
||||
};
|
||||
|
||||
// Delete a Tutorial with the specified id in the request
|
||||
exports.delete = (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
Tutorial.findByIdAndRemove(id)
|
||||
.then(data => {
|
||||
if (!data) {
|
||||
sendError(res,404,-1,`Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`);
|
||||
} else {
|
||||
sendMessage(res, 1, { message: "Tutorial was deleted successfully!" });
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Could not delete Tutorial with id=" + id);
|
||||
});
|
||||
};
|
||||
|
||||
// Delete all Tutorials from the database.
|
||||
exports.deleteAll = (req, res) => {
|
||||
Tutorial.deleteMany({})
|
||||
.then(data => {
|
||||
sendMessage(res, 1, {
|
||||
message: `${data.deletedCount} Tutorials were deleted successfully!`
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Some error occurred while removing all tutorials.");
|
||||
});
|
||||
};
|
||||
|
||||
// Find all published Tutorials
|
||||
exports.findAllPublished = (req, res) => {
|
||||
Tutorial.find({ published: true })
|
||||
.then(data => {
|
||||
sendMessage(res, 1, data);
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Some error occurred while retrieving tutorials.");
|
||||
});
|
||||
};
|
||||
148
backend/app/controllers/user.controller.js
Normal file
148
backend/app/controllers/user.controller.js
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
const db = require("../models/mongodb.model");
|
||||
const {sendError, sendMessage} = require ("../config/response.config");
|
||||
const sessionJWT = require('../config/sessionJWT.config');
|
||||
const User = db.users;
|
||||
|
||||
|
||||
// Authenticate an User
|
||||
exports.auth = (req, res) => {
|
||||
// Validate request
|
||||
if (!req.body.mail || !req.body.hashPass) {
|
||||
sendError(res, 400,-1,"Content can not be empty ! (mail and hashPass needed)");
|
||||
} else{
|
||||
// Check User in the database
|
||||
User
|
||||
.findOne({mail: req.body.mail, hashPass: req.body.hashPass}, [{count: {$size: "$_id"}}])
|
||||
.then(data => {
|
||||
if (data !== null){
|
||||
sessionJWT.setSessionCookie(req, res, { mail: req.body.mail });
|
||||
return sendMessage(res, 1, true);
|
||||
} else {
|
||||
sessionJWT.setSessionCookie(req, res, { mail: -1 });
|
||||
return sendError(res, -1, "Invalid mail or password.");
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res, 500,-1,err.message || "Some error occurred while authenticating the User.");
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Create and Save a new User
|
||||
exports.create = (req, res) => {
|
||||
// Validate request
|
||||
if (!req.body.login || !req.body.hashPass || !req.body.mail || !req.body.role) {
|
||||
sendError(res, 400,-1,"Content can not be empty ! (login, hashPass, mail and role needed");
|
||||
}
|
||||
else{
|
||||
User.exists({login: req.body.login}, function (err, docs){
|
||||
if(err){
|
||||
sendError(res, 500,-1,err.message || "Some error occurred while checking if the User already exists.");
|
||||
} else{
|
||||
if(docs === null) {
|
||||
const user = new User({
|
||||
login: req.body.login,
|
||||
hashPass: req.body.hashPass,
|
||||
mail: req.body.mail,
|
||||
role: req.body.role
|
||||
});
|
||||
|
||||
// Save User in the database
|
||||
user
|
||||
.save(user)
|
||||
.then(data => {
|
||||
data.hashPass = undefined; // Hiding hashPass on return
|
||||
sendMessage(res, 1, data)
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res, 500,-1,err.message || "Some error occurred while creating the User.");
|
||||
});
|
||||
} else{
|
||||
sendError(res, 500, -1, err || "User already exists.");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Retrieve all Users from the database.
|
||||
exports.findAll = (req, res) => {
|
||||
const login = req.query.login;
|
||||
let condition = login ? { login: { $regex: new RegExp(login), $options: "i" } } : {};
|
||||
|
||||
User.find(condition, {hashPass: false})
|
||||
.then(data => {
|
||||
sendMessage(res, 1, data)
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Some error occurred while retrieving users.");
|
||||
});
|
||||
};
|
||||
|
||||
// Find a single User with an id
|
||||
exports.findOne = (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
User.findById(id, {hashPass: false})
|
||||
.then(data => {
|
||||
if (data){
|
||||
sendMessage(res, 1, data);
|
||||
} else {
|
||||
sendError(res,404,-1,"Not found User with id " + id );
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Error retrieving User with id=" + id );
|
||||
});
|
||||
};
|
||||
|
||||
// Update a User by the id in the request
|
||||
exports.update = (req, res) => {
|
||||
if (!req.body) {
|
||||
sendError(res,400,-1,"Data to update can not be empty!");
|
||||
} else{
|
||||
const id = req.params.id;
|
||||
|
||||
User.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
|
||||
.then(data => {
|
||||
if (data) {
|
||||
sendMessage(res, 1, { message: "User was updated successfully." });
|
||||
} else {
|
||||
sendError(res,404,-1,`Cannot update User with id=${id}. Maybe User was not found!`);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Error updating User with id=" + id);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Delete a User with the specified id in the request
|
||||
exports.delete = (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
User.findByIdAndRemove(id)
|
||||
.then(data => {
|
||||
if (data) {
|
||||
sendMessage(res, 1, { message: "User was deleted successfully!" });
|
||||
} else {
|
||||
sendError(res,404,-1,`Cannot delete User with id=${id}. Maybe User was not found!`);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Could not delete User with id=" + id);
|
||||
});
|
||||
};
|
||||
|
||||
// Delete all Users from the database.
|
||||
exports.deleteAll = (req, res) => {
|
||||
User.deleteMany({})
|
||||
.then(data => {
|
||||
sendMessage(res, 1,{
|
||||
message: `${data.deletedCount} Users were deleted successfully!`
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
sendError(res,500,-1,err.message || "Some error occurred while removing all Users.");
|
||||
});
|
||||
};
|
||||
14
backend/app/jwtRS256.key.pub
Normal file
14
backend/app/jwtRS256.key.pub
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyTaN1skc89wdcz8SLY9c
|
||||
lkcARENbO40DncmcUZwQEq+EYR9BzUhjIzKJ6JetU+qGt4SJQkPAczQbw8+LaF6P
|
||||
NT0QTF6E6BUgTZg1p98E/208AiFDnoqEjmlLdQN7ekttJXGDrVOTds9WMbn8lVpa
|
||||
4EpVc+8CPDmrSTIC2YVSZmmektmFTSUA6411+5FGlq5oUdyKkToWYdn/ViJbYst8
|
||||
N48E2Vuh1ghY5t7oPWGzPibMc/6A+uDAF7+VVD8x5UydMZ9id+RxC7lhtDDvZeRM
|
||||
BllHcnWfw0UMhVk8PC6/BenJ4I8HiOgyl4cypTvlevfbZjSoNJ4g/u/lDKpdqbBg
|
||||
T76OksaYqvwvTrcvPdgF1f8l/7M9ESYZTMpxvqK6YvYC/MG2355fmZ1SeuqKfDt8
|
||||
rQXfXzesGSNmFNkm8mORHYiXBqyuNAwnSqRtP8qfoB4yXZ2W1HjUf24TvkvMrqwT
|
||||
7PFg55c/f4LVdPjx52z30QzBJmcyVZgzXNOCG1KafwBibhriQmhdfiWogs824mwI
|
||||
9w0vG2pPqSHRAa6N1y9JHSP1rIfu1jzRNFWTUuqyKgLYBE47HqxxJ21BwBryTVUz
|
||||
8Ei+o05lJFkQX2/ISFYP2RunfUBccqmv0nEcGr+RSLTeqz5+WUTWs8tQxUItf2p6
|
||||
9Y30htlmCJlSnHn2JlaJWQUCAwEAAQ==
|
||||
-----END PUBLIC KEY-----
|
||||
8
backend/app/jwtRS256.sh
Normal file
8
backend/app/jwtRS256.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/env bash
|
||||
ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key -q -N ""
|
||||
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
|
||||
rm .env
|
||||
echo "JWTRS256_PRIVATE_KEY='`cat ./jwtRS256.key | base64 -w 0`'" >> .env
|
||||
echo "JWTRS256_PUBLIC_KEY='`cat ./jwtRS256.key.pub | base64 -w 0`'" >> .env
|
||||
source .env
|
||||
rm jwtRS256.key
|
||||
12
backend/app/models/mongodb.model.js
Normal file
12
backend/app/models/mongodb.model.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
const dbConfig = require("../config/mongodb.config");
|
||||
|
||||
const mongoose = require("mongoose");
|
||||
mongoose.Promise = global.Promise;
|
||||
|
||||
const db = {};
|
||||
db.mongoose = mongoose;
|
||||
db.url = dbConfig.url;
|
||||
db.tutorials = require("./tutorial.model")(mongoose);
|
||||
db.users = require("./user.model")(mongoose);
|
||||
|
||||
module.exports = db;
|
||||
17
backend/app/models/tutorial.model.js
Normal file
17
backend/app/models/tutorial.model.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
module.exports = mongoose => {
|
||||
let schema = mongoose.Schema({
|
||||
title: String,
|
||||
description: String,
|
||||
published: Boolean
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
schema.method("toJSON", function() {
|
||||
const { __v, _id, ...object } = this.toObject();
|
||||
object.id = _id;
|
||||
return object;
|
||||
});
|
||||
|
||||
return mongoose.model("tutorial", schema);
|
||||
};
|
||||
18
backend/app/models/user.model.js
Normal file
18
backend/app/models/user.model.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
module.exports = mongoose => {
|
||||
let schema = mongoose.Schema({
|
||||
login: String,
|
||||
hashPass: String, // WARNING: We don't want to send back the hashPass
|
||||
mail: String,
|
||||
role: Object
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
schema.method("toJSON", function() {
|
||||
const { __v, _id, ...object } = this.toObject();
|
||||
object.id = _id;
|
||||
return object;
|
||||
});
|
||||
|
||||
return User = mongoose.model("user", schema);
|
||||
};
|
||||
28
backend/app/routes/tutorial.routes.js
Normal file
28
backend/app/routes/tutorial.routes.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
module.exports = app => {
|
||||
const tutorials = require("../controllers/tutorial.controller.js");
|
||||
|
||||
let router = require("express").Router();
|
||||
|
||||
// Create a new Tutorial
|
||||
router.post("/", tutorials.create);
|
||||
|
||||
// Retrieve all Tutorials
|
||||
router.get("/", tutorials.findAll);
|
||||
|
||||
// Retrieve all published Tutorials
|
||||
router.get("/published", tutorials.findAllPublished);
|
||||
|
||||
// Retrieve a single Tutorial with id
|
||||
router.get("/:id", tutorials.findOne);
|
||||
|
||||
// Update a Tutorial with id
|
||||
router.put("/:id", tutorials.update);
|
||||
|
||||
// Delete a Tutorial with id
|
||||
router.delete("/:id", tutorials.delete);
|
||||
|
||||
// Create a new Tutorial
|
||||
router.delete("/", tutorials.deleteAll);
|
||||
|
||||
app.use('/api/tutorials', router);
|
||||
};
|
||||
27
backend/app/routes/user.routes.js
Normal file
27
backend/app/routes/user.routes.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
const users = require("../controllers/user.controller");
|
||||
module.exports = app => {
|
||||
let router = require("express").Router();
|
||||
|
||||
// Create a new User
|
||||
router.post("/", users.create);
|
||||
|
||||
// Retrieve all Users
|
||||
router.get("/", users.findAll);
|
||||
|
||||
// Retrieve a single User with id
|
||||
router.get("/:id", users.findOne);
|
||||
|
||||
// Update a User with id
|
||||
router.put("/:id", users.update);
|
||||
|
||||
// Delete a User with id
|
||||
router.delete("/:id", users.delete);
|
||||
|
||||
// Delete all Users
|
||||
router.delete("/", users.deleteAll);
|
||||
|
||||
// Authenticate a User
|
||||
router.post("/auth", users.auth);
|
||||
|
||||
app.use('/api/users', router);
|
||||
};
|
||||
Reference in a new issue