This commit is contained in:
Yûki VACHOT 2021-11-01 19:53:21 +01:00
parent 4138c22051
commit e17adfcfa5
11 changed files with 193 additions and 83 deletions

View file

@ -1,5 +1,18 @@
module.exports = { module.exports = {
User: 0, User: {
Advertiser: 5, name: "user",
Admin: 10 permission: 0
},
Advertiser: {
name: "advertiser",
permission: 5
},
Admin: {
name: "admin",
permission: 10
},
SuperAdmin: {
name: "superAdmin",
permission: 1000
}
}; };

View file

@ -81,13 +81,15 @@ function checkLogin(req, res, role=null){
const token = getToken(session); const token = getToken(session);
if(token.login === 'undefined' || token.login === -1){ if(token.login === 'undefined' || token.login === -1){
return sendError(res, 500, -1, "User not authenticated."); return sendError(res, 500, -1, "User not authenticated.");
} else{ } else {
if(role === null){ if(role === null){
return token; return token;
} else{ } else {
if(token.role !== 'undefined' && role.includes(token.role)){ if(token.role !== 'undefined' &&
((Array.isArray(role) && role.includes(token.role)) ||
( typeof role === 'object' && token.role.permission >= role.permission))){
return token; return token;
} else{ } else {
return sendError(res, 500, -1, "User doesn't have permission.", token); return sendError(res, 500, -1, "User doesn't have permission.", token);
} }
} }

View file

@ -11,7 +11,7 @@ exports.create = (req, res) => {
} }
}; };
// Retrieve all Playlists // Retrieve all Playlists + ads
exports.findAll = (req, res) => { exports.findAll = (req, res) => {
const token = checkLogin(req, res); const token = checkLogin(req, res);
if(token){ if(token){

View file

@ -1,6 +1,7 @@
const db = require("../models/mongodb.model"); const db = require("../models/mongodb.model");
const {sendError, sendMessage} = require ("../config/response.config"); const {sendError, sendMessage} = require ("../config/response.config");
const {checkLogin, setSessionCookie} = require("../config/sessionJWT.config"); const {checkLogin, setSessionCookie, getSession, getToken} = require("../config/sessionJWT.config");
const ObjectId = require('mongoose').Types.ObjectId;
const roles = require("../config/role.config"); const roles = require("../config/role.config");
const User = db.users; const User = db.users;
@ -8,7 +9,7 @@ const User = db.users;
exports.auth = (req, res) => { exports.auth = (req, res) => {
// Validate request // Validate request
if (!req.body.login || !req.body.hashPass) { if (!req.body.login || !req.body.hashPass) {
sendError(res, 400,-1,"Content can not be empty ! (login and hashPass needed)"); sendError(res, 400,-1,"Content can not be empty . (login and hashPass needed)");
} else{ } else{
// Check User in the database // Check User in the database
User User
@ -16,7 +17,7 @@ exports.auth = (req, res) => {
.then(data => { .then(data => {
if (data !== null){ if (data !== null){
setSessionCookie(req, res, {id: data._id, login: req.body.login, role: data.role}); setSessionCookie(req, res, {id: data._id, login: req.body.login, role: data.role});
return sendMessage(res, 1, true); return sendMessage(res, 1, {id: data._id, login: req.body.login, role: data.role});
} else { } else {
setSessionCookie(req, res, {id: -1, login: -1, role: -1 }); setSessionCookie(req, res, {id: -1, login: -1, role: -1 });
return sendError(res, 500, -1, "Invalid login or password."); return sendError(res, 500, -1, "Invalid login or password.");
@ -29,10 +30,9 @@ exports.auth = (req, res) => {
}; };
// Logout a User // Logout a User
exports.disconnect = (req, res) => { exports.logout = (req, res) => {
const token = checkLogin(req, res); const token = checkLogin(req, res);
if(token){ if(token){
console.log(token);
setSessionCookie(req, res, {id: -1, login: -1, role: -1}); setSessionCookie(req, res, {id: -1, login: -1, role: -1});
return sendMessage(res, 1, {message: "User disconnected"}, token); return sendMessage(res, 1, {message: "User disconnected"}, token);
} }
@ -42,7 +42,7 @@ exports.disconnect = (req, res) => {
exports.create = (req, res) => { exports.create = (req, res) => {
// Validate request // Validate request
if (!req.body.login || !req.body.hashPass || !req.body.mail) { if (!req.body.login || !req.body.hashPass || !req.body.mail) {
sendError(res, 400,-1,"Content can not be empty ! (login, hashPass and mail needed"); sendError(res, 400,-1,"Content can not be empty . (login, hashPass and mail needed");
} }
else{ else{
User.exists({login: req.body.login}, function (err, docs){ User.exists({login: req.body.login}, function (err, docs){
@ -50,13 +50,38 @@ exports.create = (req, res) => {
sendError(res, 500,-1,err.message || "Some error occurred while checking if the User already exists."); sendError(res, 500,-1,err.message || "Some error occurred while checking if the User already exists.");
} else{ } else{
if(docs === null) { if(docs === null) {
const user = new User({ let user;
const session = getSession(req.cookies.SESSIONID);
const token = getToken(session);
if(token.login === 'undefined' || token.login === -1){
if(req.body.role === 'undefined'){
sendError(res, 500, -1, "Must be connected to set role of a User.");
} else{
user = new User({
login: req.body.login,
hashPass: req.body.hashPass,
mail: req.body.mail
});
}
} else {
if(token.role !== 'undefined' &&
req.body.role !== 'undefined' &&
req.body.role.permission !== 'undefined' &&
token.role.permission >= req.body.role.permission){
user = new User({
login: req.body.login, login: req.body.login,
hashPass: req.body.hashPass, hashPass: req.body.hashPass,
mail: req.body.mail, mail: req.body.mail,
role: req.body.role role: req.body.role
}); });
} else {
user = new User({
login: req.body.login,
hashPass: req.body.hashPass,
mail: req.body.mail
});
}
}
// Save User in the database // Save User in the database
user user
.save(user) .save(user)
@ -68,7 +93,7 @@ exports.create = (req, res) => {
sendError(res, 500,-1,err.message || "Some error occurred while creating the User."); sendError(res, 500,-1,err.message || "Some error occurred while creating the User.");
}); });
} else{ } else{
sendError(res, 500, -1, err || "User already exists."); sendError(res, 500, -1, err || `User ${req.body.login} already exists.`);
} }
} }
}); });
@ -77,12 +102,10 @@ exports.create = (req, res) => {
// Retrieve all Users from the database if admin. // Retrieve all Users from the database if admin.
exports.findAll = (req, res) => { exports.findAll = (req, res) => {
const token = checkLogin(req, res, [roles.Admin]); const token = checkLogin(req, res, roles.Admin);
if(token){ if(token){
console.log(token);
const login = req.query.login; const login = req.query.login;
let condition = login ? { login: { $regex: new RegExp(login), $options: "i" } } : {}; let condition = login ? { login: { $regex: new RegExp(login), $options: "i" } } : {};
User.find(condition, {hashPass: false}) User.find(condition, {hashPass: false})
.then(data => { .then(data => {
sendMessage(res, 1, data, token) sendMessage(res, 1, data, token)
@ -93,63 +116,69 @@ exports.findAll = (req, res) => {
} }
}; };
// Find a single User with login if admin or login from cookie session // Find a single User by session id or by id if admin
exports.findOne = (req, res) => { exports.findOne = (req, res) => {
const token = checkLogin(req, res); const token = checkLogin(req, res);
if(token){ if(token){
let login; let id;
if(token.role === [roles.Admin]){ if([roles.Admin, roles.SuperAdmin].includes(token.role)){
login = req.params.login; if(typeof req.params.id === 'undefined'){
id = token.id;
} else{ } else{
login = token.login; id = req.params.id;
} }
console.log(token.role, login); } else{
User.find({login: login}, {hashPass: false}) id = token.id;
}
User.findById(new ObjectId(id), {hashPass: false})
.then(data => { .then(data => {
if (data){ if(data){
sendMessage(res, 1, data); sendMessage(res, 1, data, token);
} else { } else {
sendError(res,404,-1,"Not found User with login " + login ); sendError(res,404,-1,"User not found with id " + id, token);
} }
}) })
.catch(err => { .catch(err => {
sendError(res,500,-1,err.message || "Error retrieving User with login=" + login ); sendError(res,500,-1,err.message || "Error retrieving User with id=" + id, token);
}); });
} }
}; };
// Update a User by the id in the request // Update a User by the id in the request
exports.update = (req, res) => { exports.update = (req, res) => {
if (!req.body) { const token = checkLogin(req, res);
sendError(res,400,-1,"Data to update can not be empty!"); if(req.body && token) {
} else{ let id;
const id = req.params.id; if ([roles.Admin, roles.SuperAdmin].includes(token.role)) {
id = req.params.id;
User.findByIdAndUpdate(id, req.body, { useFindAndModify: false }) } else {
id = token.id;
}
User.findByIdAndUpdate(id, req.body, {useFindAndModify: false})
.then(data => { .then(data => {
if (data) { if (data) {
sendMessage(res, 1, { message: "User was updated successfully." }); sendMessage(res, 1, {message: "User was updated successfully."});
} else { } else {
sendError(res,404,-1,`Cannot update User with id=${id}. Maybe User was not found!`); sendError(res, 404, -1, `Cannot update User with id=${id}. Maybe User was not found.`);
} }
}) })
.catch(err => { .catch(err => {
sendError(res,500,-1,err.message || "Error updating User with id=" + id); sendError(res, 500, -1, err.message || "Error updating User with id=" + id);
}); });
} else {
sendError(res, 400, -1, "Data to update can not be empty.");
} }
}; };
// Delete a User with the specified id in the request // Delete a User with the specified id in the request
exports.delete = (req, res) => { exports.delete = (req, res) => {
const id = req.params.id; const id = req.params.id;
User.findByIdAndRemove(id) User.findByIdAndRemove(id)
.then(data => { .then(data => {
if (data) { if (data) {
sendMessage(res, 1, { message: "User was deleted successfully!" }); sendMessage(res, 1, { message: "User was deleted successfully." });
} else { } else {
sendError(res,404,-1,`Cannot delete User with id=${id}. Maybe User was not found!`); sendError(res,404,-1,`Cannot delete User with id=${id}. Maybe User was not found.`);
} }
}) })
.catch(err => { .catch(err => {
@ -159,13 +188,12 @@ exports.delete = (req, res) => {
// Delete all Users from the database. // Delete all Users from the database.
exports.deleteAll = (req, res) => { exports.deleteAll = (req, res) => {
const token = checkLogin(req, res, [roles.Admin]); const token = checkLogin(req, res, roles.SuperAdmin);
if(token) { if(token) {
console.log(token);
User.deleteMany({}) User.deleteMany({})
.then(data => { .then(data => {
sendMessage(res, 1, { sendMessage(res, 1, {
message: `${data.deletedCount} Users were deleted successfully!` message: `${data.deletedCount} Users were deleted successfully.`
}); });
}) })
.catch(err => { .catch(err => {
@ -173,3 +201,21 @@ exports.deleteAll = (req, res) => {
}); });
} }
}; };
// Get all Roles depending on the role of the User
exports.roles = (req, res) => {
const token = checkLogin(req, res);
if(token){
let rolesP = [];
for(const [roleName, role] of Object.entries(roles)){
if(role.permission < token.role.permission){
rolesP.push(role);
}
}
if(Object.entries(rolesP).length === 0){
sendError(res, 500, -1, "User do not have permission to see & create user with roles.", token);
} else{
sendMessage(res, 1, rolesP);
}
}
};

View file

@ -3,7 +3,15 @@ const {sendError, sendMessage} = require ("../config/response.config");
const {checkLogin} = require("../config/sessionJWT.config"); const {checkLogin} = require("../config/sessionJWT.config");
const Video = db.video; const Video = db.video;
// Search Video // Search Video + ads
exports.search = (req, res) => {
const token = checkLogin(req, res);
if(token){
return sendError(res, 501, -1, "Video.search not Implemented", token);
}
};
// History
exports.search = (req, res) => { exports.search = (req, res) => {
const token = checkLogin(req, res); const token = checkLogin(req, res);
if(token){ if(token){
@ -19,7 +27,7 @@ exports.create = (req, res) => {
} }
}; };
// Retrieve all Videos // Retrieve all Videos + ads
exports.findAll = (req, res) => { exports.findAll = (req, res) => {
const token = checkLogin(req, res); const token = checkLogin(req, res);
if(token){ if(token){

View file

@ -6,7 +6,7 @@ module.exports = mongoose => {
hashPass: String, // WARNING: We don't want to send back the hashPass hashPass: String, // WARNING: We don't want to send back the hashPass
mail: String, mail: String,
role: { role: {
type: Number, type: Object,
default: roles.User default: roles.User
}, },
playlists: [] playlists: []

View file

@ -3,22 +3,22 @@ module.exports = app => {
let router = require("express").Router(); let router = require("express").Router();
// Create a new Ad // Create a new Ad
router.post("/user/ad", ads.create); router.post("/ad/create", ads.create);
// Retrieve all Ads // Retrieve all Ads
router.get("/user/ad", ads.findAll); router.get("/ad/findAll", ads.findAll);
// Retrieve a single Ad with id // Retrieve a single Ad with id
router.get("/user/ad/:id", ads.findOne); router.get("/ad/findOne/:id", ads.findOne);
// Update an Ad with id // Update an Ad with id
router.put("/user/ad/:id", ads.update); router.put("/ad/update/:id", ads.update);
// Delete an Ad with id // Delete an Ad with id
router.delete("/user/ad/:id", ads.delete); router.delete("/ad/delete/:id", ads.delete);
// Delete all Ads // Delete all Ads
router.delete("/user/ad", ads.deleteAll); router.delete("/ad/deleteAll", ads.deleteAll);
app.use('/api', router); app.use('/api', router);
}; };

View file

@ -3,22 +3,22 @@ module.exports = app => {
let router = require("express").Router(); let router = require("express").Router();
// Create a new Playlist // Create a new Playlist
router.post("/user/playlist", playlists.create); router.post("/playlist/create", playlists.create);
// Retrieve all Playlists // Retrieve all Playlists
router.get("/user/playlists", playlists.findAll); router.get("/playlist/findAll", playlists.findAll);
// Retrieve a single Playlist with id // Retrieve a single Playlist with id
router.get("/user/playlist/:id", playlists.findOne); router.get("/playlist/findOne/:id", playlists.findOne);
// Update a Playlist with id // Update a Playlist with id
router.put("/user/playlist/:id", playlists.update); router.put("/playlist/update/:id", playlists.update);
// Delete a Playlist with id // Delete a Playlist with id
router.delete("/user/playlist/:id", playlists.delete); router.delete("/playlist/delete/:id", playlists.delete);
// Delete all Playlists // Delete all Playlists
router.delete("/user/playlists", playlists.deleteAll); router.delete("/playlist/deleteAll", playlists.deleteAll);
app.use('/api', router); app.use('/api', router);
}; };

View file

@ -3,28 +3,37 @@ module.exports = app => {
let router = require("express").Router(); let router = require("express").Router();
// Create a new User // Create a new User
router.post("/user", users.create); router.post("/user/create", users.create);
// Retrieve all Users // Retrieve all Users
router.get("/users", users.findAll); router.get("/user/findAll", users.findAll);
// Retrieve a single User with id // Retrieve a single User with id if admin
router.get("/user/:id", users.findOne); router.get("/user/findOne/:id", users.findOne);
// Update a User with id // Retrieve a single User with session id
router.put("/user/:id", users.update); router.get("/user/findOne", users.findOne);
// Update a User with id if admin
router.put("/user/update/:id", users.update);
// Update a User with session id
router.put("/user/update", users.update);
// Delete a User with id // Delete a User with id
router.delete("/user/:id", users.delete); router.delete("/user/delete/:id", users.delete);
// Delete all Users // Delete all Users
router.delete("/users", users.deleteAll); router.delete("/user/deleteAll", users.deleteAll);
// Authenticate a User // Authenticate a User
router.post("/user/auth", users.auth); router.post("/user/auth", users.auth);
// Logout a User // Logout a User
router.delete("/user/logout", users.disconnect); router.delete("/user/logout", users.logout);
// Get all Roles depending on the role of the User
router.get("/user/roles", users.roles);
app.use('/api', router); app.use('/api', router);
}; };

View file

@ -3,25 +3,25 @@ module.exports = app => {
let router = require("express").Router(); let router = require("express").Router();
// Search Video // Search Video
router.post("/videos", videos.search); router.post("/video/search", videos.search);
// Create a new Video // Create a new Video
router.post("/video", videos.create); router.post("/video/create", videos.create);
// Retrieve all Videos // Retrieve all Videos
router.get("/videos", videos.findAll); router.get("/video/findAll", videos.findAll);
// Retrieve a single Video with id // Retrieve a single Video with id
router.get("/video/:id", videos.findOne); router.get("/video/findOne/:id", videos.findOne);
// Update a Video with id // Update a Video with id
router.put("/video/:id", videos.update); router.put("/video/update/:id", videos.update);
// Delete a Video with id // Delete a Video with id
router.delete("/video/:id", videos.delete); router.delete("/video/delete/:id", videos.delete);
// Delete all Videos // Delete all Videos
router.delete("/videos", videos.deleteAll); router.delete("/video/deleteAll", videos.deleteAll);
app.use('/api', router); app.use('/api', router);
}; };

View file

@ -31,6 +31,38 @@ require("./app/routes/playlist.routes")(app);
require("./app/routes/video.routes")(app); require("./app/routes/video.routes")(app);
require("./app/routes/ad.routes")(app); require("./app/routes/ad.routes")(app);
const roles = require("./app/config/role.config");
const User = db.users;
const login = 'superAdmin';
const hashPass = 'hashPassSuperAdmin';
const mail = 'superAdmin@mail.admin';
User.exists({role: roles.SuperAdmin}, function (err, docs){
if(err){
console.log("Some error occurred while checking if superAdmin already exists.");
} else{
if(docs === null){
const user = new User({
login: login,
hashPass: hashPass,
mail: mail,
role: roles.SuperAdmin
});
user
.save(user)
.then(data => {
data.hashPass = undefined; // Hiding hashPass on return
console.log(data);
})
.catch(err => {
console.log(err.message || "Some error occurred while creating superAdmin.");
});
} else {
console.log("superAdmin already exist !");
}
}
});
app.listen(port, '0.0.0.0',() => { app.listen(port, '0.0.0.0',() => {
console.log (`listening on port ${port}`); console.log (`listening on port ${port}`);
}); });