Sup_File/routes/api.js
2018-05-18 22:07:38 +02:00

283 lines
7.9 KiB
JavaScript

var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/database');
require('../config/passport')(passport);
var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();
var User = require("../models/user");
var FileMongo = require("../models/FileMongo");
var FolderMongo = require("../models/FolderMongo");
var Book = require("../models/book");
var fs = require('fs');
var multer = require('multer');
var upload = multer({ dest: './public/' });
var passportFacebook = require('../auth/facebook');
var passportGoogle = require('../auth/google');
var passportGitHub = require('../auth/github');
/* creation Token */
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
/* config multer dossier cible et nom du file */
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.send('Express RESTful API');
});
router.post('/signup', function(req, res) {
if (!req.body.username || !req.body.password) {
res.json({success: false, msg: 'Please pass username and password.'});
} else {
var newUser = new User({
username: req.body.username,
password: req.body.password
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
/* SAVE FILE */
router.post('/uploadFileMongo', function(req, res, next) {
FileMongo.create(req.body, function (err, post) {
if (err){
return next(err);
}
res.json(post);
});
});
/* SAVE URL FILE */
router.post('/saveURLFileMongo', function(req, res, next) {
console.log("New File data req.body", JSON.stringify(req.body));
FileMongo.findOneAndUpdate({_id : req.body._id, owner: req.body.owner}, {url: req.body.url},{new: true}).then((data) =>{
if(data === null){
throw new Error('File Not Found');
}
res.json({ message: 'File updated!' });
}).catch( (error) => {
//Deal with all your errors here with your preferred error handle middleware / method
res.status(500).json({ message: 'Some Error!' });
console.log(error);
});
});
/* SAVE FOLDER */
router.post('/createFolder', function(req, res, next) {
FolderMongo.create(req.body, function (err, post) {
if (err){
return next(err);
}
res.json(post);
});
});
/* DELETE FILE */
router.post('/deleteFileMongo', function(req, res, next) {
FileMongo.remove(req.body, function (err, post) {
if (err){
return next(err);
}
//Delete file multer dans Public
fs.unlink('./public/' + req.body._id);
res.json(post);
});
});
/* DELETE FOLDER */
router.post('/deleteFolderMongo', function(req, res, next) {
FolderMongo.remove({_id : req.body._id, name: req.body.name, owner: req.body.owner}, function (err, post) {
if (err){
return next(err);
}
res.json(post);
});
});
/* Rename FOLDER */
router.post('/renameFolderMongo', function(req, res, next) {
FolderMongo.findOneAndUpdate({_id : req.body._id, owner: req.body.owner}, {name: req.body.name},{new: true}).then((data) =>{
if(data === null){
throw new Error('Folder Not Found');
}
res.json({ message: 'Folder updated!' });
}).catch( (error) => {
//Deal with all your errors here with your preferred error handle middleware / method
res.status(500).json({ message: 'Some Error!' });
console.log(error);
});
});
/* Rename FILE */
router.post('/renameFileMongo', function(req, res, next) {
console.log("New File data req.body", JSON.stringify(req.body));
FileMongo.findOneAndUpdate({_id : req.body._id, owner: req.body.owner}, {name: req.body.name},{new: true}).then((data) =>{
if(data === null){
throw new Error('File Not Found');
}
res.json({ message: 'File updated!' });
}).catch( (error) => {
//Deal with all your errors here with your preferred error handle middleware / method
res.status(500).json({ message: 'Some Error!' });
console.log(error);
});
});
/* Get Current folder */
router.post('/getMainFolder', function(req, res) {
FolderMongo.findOne({
path: req.body.path,
owner: req.body.owner
}, function(err, folder) {
res.json(folder);
});
});
/* Get tout les folders du mainFolder */
router.post('/getFolderList', function(req, res) {
FolderMongo.find({
parent: req.body.mainPath,
owner: req.body.owner
}, function(err, folder) {
res.json(folder);
});
});
/* Get tout les files du mainFolder */
router.post('/getFileList', function(req, res) {
FileMongo.find({
path: req.body.mainPath,
owner: req.body.owner
}, function(err, files) {
res.json(files);
});
});
/* Login */
router.post('/signin', function(req, res) {
User.findOne({
username: req.body.username
}, function(err, user) {
if (err) throw err;
if (!user) {
res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
console.log('req.user.username logggggg ::: ' + JSON.stringify(user));
// if user is found and password is right create a token
var token = jwt.sign(user.toJSON(), config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
/* Multer upload */
router.post('/upload' , multer({storage: storage, limits: {fileSize: 30000000000}}).array("public[]", 12) ,function(req,res,next){
console.log('bebeb : ' + JSON.stringify(req));
res.send(req.files);
});
/* Get utilisateur courant */
router.get('/getCurrentUser', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
res.json(req.user);
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
});
////////////
/* GET users listing. */
router.get('/', ensureAuthenticated, function(req, res, next) {
res.render('user', { user: req.user });
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
/* FACEBOOK ROUTER */
router.get('/facebook', passportFacebook.authenticate('facebook'));
router.get('/facebook/callback', passportFacebook.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
/* GOOGLE ROUTER */
router.get('/google', passportGoogle.authenticate('google', { scope: 'https://www.google.com/m8/feeds' }));
router.get('/google/callback', passportGoogle.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
res.redirect('/');
});
/* GITHUB ROUTER */
router.get('/github', passportGitHub.authenticate('github', { scope: [ 'user:email' ] }));
router.get('/github/callback', passportGitHub.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
module.exports = router;