2 Commits

Author SHA1 Message Date
Rampeur be44e4fdf0 Ajout des fichiers .env 2025-08-08 18:08:01 +02:00
Rampeur ffdc93834a Ajout initial des fichiers du projet 2025-08-08 10:47:29 +02:00
71 changed files with 15435 additions and 4852 deletions
+10 -8
View File
@@ -1,15 +1,17 @@
APP_ENV="development"
NODE_ENV="development"
DEBUG=false
SERVER_PORT="3201"
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME="3600"
MONGODB_URI="mongodb://localhost:27017/adastradb"
SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr"
SENDGRID_TO_MAIL="rampeur@gmail.com"
MYSQL_DBNAME="c4adastracomdb2"
MYSQL_DBUSER="c4adastracomu2"
MYSQL_DBPASS="kbrnrt5jPK12"
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
MYSQL_DBPORT="3306"
MYSQL_DBTYPE="mysql"
AUTHORIZATION_PREFIX="Api-Key"
COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="adastradb"
COUCHDB_DESIGN="adastra_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+10 -8
View File
@@ -1,15 +1,17 @@
APP_ENV="development"
NODE_ENV="development"
DEBUG=false
SERVER_PORT="3201"
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600
MONGODB_URI="mongodb://localhost:27017/adastradb"
SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr"
SENDGRID_TO_MAIL="rampeur@gmail.com"
MYSQL_DBNAME="c4adastracomdb2"
MYSQL_DBUSER="c4adastracomu2"
MYSQL_DBPASS="kbrnrt5jPK12"
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
MYSQL_DBPORT="3306"
MYSQL_DBTYPE="mysql"
AUTHORIZATION_PREFIX="Api-Key"
COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="adastradb"
COUCHDB_DESIGN="adastra_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+10 -8
View File
@@ -1,15 +1,17 @@
APP_ENV="local"
NODE_ENV="development"
DEBUG=false
SERVER_PORT="3201"
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600
MONGODB_URI="mongodb://localhost:27017/adastradb"
SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr"
SENDGRID_TO_MAIL="rampeur@gmail.com"
MYSQL_DBNAME="c4adastracomdb2"
MYSQL_DBUSER="c4adastracomu2"
MYSQL_DBPASS="kbrnrt5jPK12"
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
MYSQL_DBPORT="3306"
MYSQL_DBTYPE="mysql"
AUTHORIZATION_PREFIX="Api-Key"
COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="adastradb"
COUCHDB_DESIGN="adastra_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+10 -8
View File
@@ -1,15 +1,17 @@
APP_ENV="production"
NODE_ENV="production"
DEBUG=false
SERVER_PORT="3201"
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600
MONGODB_URI="mongodb://localhost:27017/adastradb"
SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr"
SENDGRID_TO_MAIL="rampeur@gmail.com"
MYSQL_DBNAME="c4adastracomdb2"
MYSQL_DBUSER="c4adastracomu2"
MYSQL_DBPASS="kbrnrt5jPK12"
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
MYSQL_DBPORT="3306"
MYSQL_DBTYPE="mysql"
AUTHORIZATION_PREFIX="Api-Key"
COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="adastradb"
COUCHDB_DESIGN="adastra_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+2
View File
@@ -62,3 +62,5 @@ sonar.properties
**/*.copy.ts
**/*.copy.scss
**/*.copy.html
middlewares
+115
View File
@@ -0,0 +1,115 @@
var appEnv = process.env.APP_ENV;
if (appEnv == undefined) {
appEnv = 'development';
}
require('dotenv').config({ path: `.env.${appEnv}` });
const { promisify } = require('util'),
bodyParser = require('body-parser'),
chalk = require('chalk'),
utils = require('./routes/utils'),
exceptionHandler = require('./middlewares/exceptions.handler.js');
var express = require('express'),
session = require('express-session'),
cors = require('cors'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose'),
morgan = require('morgan');
var isProduction = appEnv === 'production';
// Create global app object
var app = express();
app.use(cors());
// Normal express config defaults
//app.use(morgan('combined'));
morgan.token('statusColor', (req, res) => {
let status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
? res.statusCode
: undefined
return status >= 500 ? chalk.red(status)
: status >= 429 ? chalk.magenta(status)
: status >= 400 ? chalk.yellow(status)
: status >= 300 ? chalk.cyan(status)
: status >= 200 ? chalk.green(status)
: chalk.underline(status);
});
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('method-override')());
app.use(express.static(__dirname + '/public'));
app.use(session({ secret: 'acapisecret', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }));
if (!isProduction) {
app.use(errorhandler());
}
if(isProduction){
mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGODB_URI).then(() => {
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully'));
}).catch(() => {
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database'));
});
mongoose.set('debug', process.env.DEBUG);
console.log(`${utils.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
}
require('./models/mongo');
require('./config/passport');
app.use(require('./routes'));
app.use(exceptionHandler.notFoundErrorHandler);
app.use(exceptionHandler.logErrorHandler);
app.use(exceptionHandler.clientErrorHandler);
app.use(exceptionHandler.fianlErrorHandler);
/*
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`error handler : ${err.message} ${err.err}`));
if (res.headersSent) {
return next(err)
}
res.status(err.status || 500);
if (!isProduction) {
// development error handler will print stacktrace
res.json({errors: {
message: err.message,
error: err.err,
stack: err.stack
}});
} else {
// production error handler no stacktraces leaked to user
res.json({errors: {
message: err.message,
error: {},
stack: {}
}});
}
});
*/
const startServer = async () => {
const port = process.env.SERVER_PORT || 3200;
await promisify(app.listen).bind(app)(port);
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
}
// finally, let's start our server...
startServer();
+26
View File
@@ -0,0 +1,26 @@
module.exports = {
"development": {
"username": 'c4adastracomu1',
"password": 'kbrnrt5jPK12',
"database": 'c4adastracomdb1',
"host": '176.31.255.24',
"port": 3306,
"dialect": 'mysql'
},
"test": {
"username": 'c4adastracomu1',
"password": 'kbrnrt5jPK12',
"database": 'c4adastracomdb1',
"host": '176.31.255.24',
"port": 3306,
"dialect": 'mysql'
},
"production": {
"username": 'c4adastracomu1',
"password": 'kbrnrt5jPK12',
"database": 'c4adastracomdb1',
"host": '176.31.255.24',
"port": 3306,
"dialect": 'mysql'
}
}
+6
View File
@@ -0,0 +1,6 @@
const config = {
secret: process.env.SECRET || 'acapisecret',
session_lifetime: process.env.SESSION_LIFETIME || 21600 // 21600 secondes = 6 heures
};
module.exports = config;
+61
View File
@@ -0,0 +1,61 @@
var secret = require('../config').secret,
bcrypt = require('bcrypt');
const passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var HeaderAPIKeyStrategy = require('passport-headerapikey').HeaderAPIKeyStrategy;
var mongoose = require('mongoose');
var Application = mongoose.model('Application');
var User = mongoose.model('User');
passport.use('headerapikey', new HeaderAPIKeyStrategy(
{ header: 'Authorization', prefix: `${process.env.AUTHORIZATION_PREFIX} ` },
false,
function (apikey, done) {
const salt = secret;
Promise.resolve(bcrypt.hash(apikey, salt)).then(function (encryptedKey) {
Application.findOne({ encryptedKey: encryptedKey })
.populate('author')
.then(function (application) {
if (!application) {
return done({message: "Application can't be found.", status: 404}, false, false);
}
console.log('encryptedKey: ', encryptedKey);
return done(null, application);
});
}).catch(done);
/*
const salt = secret;
Promise.resolve(bcrypt.hash(apikey, salt)).then(function (encryptedKey) {
Application.findOne({ encryptedKey: encryptedKey })
.populate('author')
.then(function (application) {
if (!application) {
return done({message: "Application can't be found.", status: 404}, false, false);
}
console.log('encryptedKey: ', encryptedKey);
return done(null, application);
return {app: application, prom: Promise.resolve(bcrypt.compare(apikey, application.apikey))};
}).then(function (res) {
res.prom.then(function (valid) {
if (!valid) {
return done(null, false, {app: res.app, valid: valid});
}
return done(null, res.app, valid);
});
});
}).catch(done);
*/
}
));
passport.use('local', new LocalStrategy({
usernameField: 'user[email]',
passwordField: 'user[password]'
}, function (email, password, done) {
User.findOne({ email: email }).then(function (user) {
if (!user || !user.validPassword(password)) {
return done(null, false, { errors: { 'email ou mot de passe': 'invalide' } });
}
return done(null, user);
}).catch(done);
}));
-265
View File
@@ -1,265 +0,0 @@
const { where } = require("sequelize");
const asyncHandler = require("../middlewares/asyncHandler");
const Article = require("../models/Article");
const Tag = require("../models/Tag");
const User = require("../models/User");
const ErrorResponse = require("../util/errorResponse");
const slugify = require("slugify");
const {
appendFollowers,
appendFavorites,
appendTagList,
} = require("../util/helpers");
const includeOptions = [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] },
},
{ model: User, as: "author", attributes: { exclude: ["email", "password"] } },
];
module.exports.getArticles = asyncHandler(async (req, res, next) => {
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
const { loggedUser } = req;
const searchOptions = {
include: [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] }, // ? this will remove the rows from the join table
// where: tag ? { name: tag } : {},
...(tag && { where: { name: tag } }),
},
{
model: User,
as: "author",
attributes: { exclude: ["password", "email"] },
// where: author ? { username: author } : {},
...(author && { where: { username: author } }),
},
],
limit: parseInt(limit),
offset: parseInt(offset),
order: [["createdAt", "DESC"]],
distinct: true,
};
let articles = { rows: [], count: 0 };
if (favorited) {
const user = await User.findOne({ where: { username: favorited } });
articles.rows = await user.getFavorites(searchOptions);
articles.count = await user.countFavorites();
} else {
articles = await Article.findAndCountAll(searchOptions);
}
for (let article of articles.rows) {
const articleTags = await article.getTagLists();
// const articleTags = article.tagLists;
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
delete article.dataValues.Favorites;
}
res
.status(200)
.json({ articles: articles.rows, articlesCount: articles.count });
});
module.exports.createArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
fieldValidation(req.body.article.title, next);
fieldValidation(req.body.article.description, next);
fieldValidation(req.body.article.body, next);
const { title, description, body, tagList } = req.body.article;
const slug = slugify(title, { lower: true });
const slugInDB = await Article.findOne({ where: { slug: slug } });
if (slugInDB) next(new ErrorResponse("Title already exists", 400));
const article = await Article.create({
title: title,
description: description,
body: body,
});
for (const tag of tagList) {
const tagInDB = await Tag.findByPk(tag.trim());
if (tagInDB) {
await article.addTagList(tagInDB);
} else if (tag.length > 2) {
const newTag = await Tag.create({ name: tag.trim() });
await article.addTagList(newTag);
}
}
delete loggedUser.dataValues.token;
article.dataValues.tagList = tagList;
article.setAuthor(loggedUser);
article.dataValues.author = loggedUser;
await appendFollowers(loggedUser, loggedUser);
await appendFavorites(loggedUser, article);
res.status(201).json({ article });
});
module.exports.deleteArticle = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) next(new ErrorResponse("Article not found", 404));
if (article.authorId !== loggedUser.id)
return next(new ErrorResponse("Unauthorized", 401));
await article.destroy();
res.status(200).json({ article });
});
module.exports.updateArticle = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) next(new ErrorResponse("Article not found", 404));
if (article.authorId !== loggedUser.id)
return next(new ErrorResponse("Unauthorized", 401));
const { title, description, body } = req.body.article;
const slugInDB = await Article.findOne({
where: { slug: slugify(title ? title : article.title, { lower: true }) },
});
if (slugInDB && slugInDB.slug !== slug)
return next(new ErrorResponse("Title already exists", 400));
await article.update({
title: title ? title : article.title,
description: description ? description : article.description,
body: body ? body : article.body,
});
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
module.exports.articlesFeed = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { limit = 3, offset = 0 } = req.query;
const authors = await loggedUser.getFollowing();
const articles = await Article.findAndCountAll({
include: includeOptions,
limit: parseInt(limit),
offset: offset * limit,
order: [["createdAt", "DESC"]],
where: { authorId: authors.map((author) => author.id) },
distinct: true,
});
for (const article of articles.rows) {
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
}
res.json({ articles: articles.rows, articlesCount: articles.count });
});
module.exports.getArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) return next(new ErrorResponse("Article not found", 404));
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
module.exports.addFavoriteArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) return next(new ErrorResponse("Article not found", 404));
await loggedUser.addFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
module.exports.deleteFavoriteArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) return next(new ErrorResponse("Article not found", 404));
await loggedUser.removeFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
const fieldValidation = (field, next) => {
if (!field) {
return next(new ErrorResponse(`Missing fields`, 400));
}
};
-120
View File
@@ -1,120 +0,0 @@
const Comment = require("../models/Comment");
const Article = require("../models/Article");
const User = require("../models/User");
const asyncHandler = require("../middlewares/asyncHandler");
const { appendFollowers } = require("../util/helpers");
const ErrorResponse = require("../util/errorResponse");
module.exports.getComments = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
});
if (!article) return next(new ErrorResponse("Article not found", 404));
const comments = await article.getComments({
include: [
{
model: User,
as: "author",
attributes: ["username", "bio", "image"],
},
],
});
for (let comment of comments) {
await appendFollowers(loggedUser, comment);
}
res.status(200).json({ comments });
});
module.exports.getComment = asyncHandler(async (req, res, next) => {
const { slug, id } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
});
if (!article) return next(new ErrorResponse("Article not found", 404));
const comment = await Comment.findOne({
where: { id: id },
include: [
{
model: User,
as: "author",
attributes: ["username", "bio", "image"],
},
],
});
if (!comment) return next(new ErrorResponse("Comment not found", 404));
await appendFollowers(loggedUser, comment);
res.status(200).json({ comment });
});
module.exports.createComment = asyncHandler(async (req, res, next) => {
const { body } = req.body.comment;
const { slug } = req.params;
const { loggedUser } = req;
fieldValidation(body, next);
const article = await Article.findOne({
where: { slug: slug },
include: [
{ model: User, as: "author", attributes: ["username", "bio", "image"] },
],
});
if (!article) return next(new ErrorResponse("Article not found", 404));
const comment = await Comment.create({
body: body,
articleId: article.id,
authorId: loggedUser.id,
});
delete loggedUser.dataValues.token;
await appendFollowers(loggedUser, loggedUser);
comment.dataValues.author = loggedUser;
res.status(201).json({ comment });
});
module.exports.deleteComment = asyncHandler(async (req, res, next) => {
const { slug, id } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
});
if (!article) return next(new ErrorResponse("Article not found", 404));
const comment = await Comment.findOne({
where: { id: id },
});
if (!comment) return next(new ErrorResponse("Comment not found", 404));
if (comment.authorId !== loggedUser.id)
return next(new ErrorResponse("Unauthorized", 401));
await comment.destroy();
res.status(200).json({ comment });
});
const fieldValidation = (field, next) => {
if (!field) {
return next(new ErrorResponse(`Missing fields`, 400));
}
};
-80
View File
@@ -1,80 +0,0 @@
const User = require("../models/User");
const asyncHandler = require("../middlewares/asyncHandler");
const ErrorResponse = require("../util/errorResponse");
module.exports.getProfile = asyncHandler(async (req, res, next) => {
const username = req.params.username;
const { loggedUser } = req;
const user = await User.findOne({ where: { username: username } });
if (!user) {
return next(new ErrorResponse(`User not found`, 404));
}
let isFollowing = false;
if (loggedUser) {
const followers = await user.getFollowers();
isFollowing = followers.some((user) => user.id === loggedUser.id);
}
const profile = {
username,
firstname: user.firstname,
lastname: user.lastname,
bio: user.bio,
image: user.image,
following: isFollowing,
};
res.status(200).json({ profile });
});
module.exports.followUser = asyncHandler(async (req, res, next) => {
const username = req.params.username;
const { loggedUser } = req;
const userToFollow = await User.findOne({ where: { username: username } });
if (!userToFollow) {
return next(new ErrorResponse(`User not found`, 404));
}
const currentUser = await User.findByPk(loggedUser.id);
await userToFollow.addFollower(currentUser);
const profile = {
username: username,
firstname: userToFollow.dataValues.firstname,
lastname: userToFollow.dataValues.lastname,
bio: userToFollow.dataValues.bio,
image: userToFollow.dataValues.image,
following: true,
};
res.status(200).json({ profile });
});
module.exports.unfollowUser = asyncHandler(async (req, res, next) => {
const username = req.params.username;
const { loggedUser } = req;
const userToUnfollow = await User.findOne({ where: { username: username } });
if (!userToUnfollow) {
return next(new ErrorResponse(`User not found`, 404));
}
const currentUser = await User.findByPk(loggedUser.id);
await userToUnfollow.removeFollower(currentUser);
const profile = {
username: username,
firstname: userToUnfollow.dataValues.firstname,
lastname: userToUnfollow.dataValues.lastname,
bio: userToUnfollow.dataValues.bio,
image: userToUnfollow.dataValues.image,
following: false,
};
res.status(200).json({ profile });
});
-12
View File
@@ -1,12 +0,0 @@
const Tag = require("../models/Tag");
const { appendTagList } = require("../util/helpers");
module.exports.getTags = async (req, res, next) => {
let tags = await Tag.findAll({
attributes: ["name"],
});
tags = tags.map((tag) => tag.name);
res.status(200).json({ tags });
};
-97
View File
@@ -1,97 +0,0 @@
const asyncHandler = require("../middlewares/asyncHandler");
const User = require("../models/User");
const ErrorResponse = require("../util/errorResponse");
const { sign } = require("../util/jwt");
module.exports.createUser = asyncHandler(async (req, res, next) => {
const { email, password, username, firstname, lastname } = req.body.user;
fieldValidation(email, next);
fieldValidation(password, next);
fieldValidation(username, next);
fieldValidation(firstname, next);
fieldValidation(lastname, next);
const user = await User.create({
email: email,
password: password,
username: username,
firstname: firstname,
lastname: lastname,
});
if (user.dataValues.password) {
delete user.dataValues.password;
}
user.dataValues.token = await sign(user);
user.dataValues.bio = null;
user.dataValues.image = null;
res.status(201).json({ user });
});
module.exports.loginUser = asyncHandler(async (req, res, next) => {
const { email, password } = req.body.user;
fieldValidation(email, next);
fieldValidation(password, next);
const user = await User.findOne({
where: {
email: email,
},
});
if (!user) {
return next(new ErrorResponse(`User not found`, 404));
}
const isMatch = user.matchPassword(password);
if (!isMatch) {
return next(new ErrorResponse("Wrong password", 401));
}
delete user.dataValues.password;
user.dataValues.token = await sign(user);
user.dataValues.bio = null;
user.dataValues.image = null;
res.status(200).json({ user });
});
module.exports.getCurrentUser = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const user = await User.findByPk(loggedUser.id);
if (!user) {
return next(new ErrorResponse(`User not found`, 404));
}
user.dataValues.token = req.headers.authorization.split(" ")[1];
res.status(200).json({ user });
});
module.exports.updateUser = asyncHandler(async (req, res, next) => {
await User.update(req.body.user, {
where: {
id: req.user.id,
},
});
const user = await User.findByPk(req.user.id);
user.dataValues.token = req.headers.authorization.split(" ")[1];
res.status(200).json({ user });
});
const fieldValidation = (field, next) => {
if (!field) {
return next(new ErrorResponse(`Missing fields`, 400));
}
};
-7
View File
@@ -1,7 +0,0 @@
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((err) => {
next(err);
});
};
module.exports = asyncHandler;
-30
View File
@@ -1,30 +0,0 @@
const { verify } = require("../util/jwt");
const User = require("../models/User");
const ErrorResponse = require("../util/errorResponse");
exports.protect = async (req, res, next) => {
try {
const { headers } = req;
if (!headers.authorization) return next();
const token = headers.authorization.split(" ")[1];
if (!token) throw new SyntaxError("Token missing or malformed");
const userVerified = await verify(token);
if (!userVerified) throw new Error("Invalid Token");
req.loggedUser = await User.findOne({
attributes: { exclude: ["email", "password"] },
where: { email: userVerified.email },
});
if (!req.loggedUser) next(new NotFoundError("User"));
headers.email = userVerified.email;
req.loggedUser.dataValues.token = token;
next();
} catch (error) {
next(error);
}
};
-22
View File
@@ -1,22 +0,0 @@
const ErrorResponse = require("../util/errorResponse");
//REQUESTED PAGE IS NOT FOUND
module.exports.notFound = (req, res, next) => {
const error = new ErrorResponse(`Not Found - ${req.originalUrl}`);
res.status(404);
next(error);
};
module.exports.errorHandler = (err, req, res, next) => {
// Log to console for dev
console.log(err.message.red);
console.log(err.stack.red);
const statusCode = err.statusCode ? err.statusCode : 500;
res.status(statusCode).json({
errors: {
body: [err.message],
},
});
};
-34
View File
@@ -1,34 +0,0 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../util/database");
const slugify = require("slugify");
const Article = sequelize.define("Article", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
slug: { type: DataTypes.STRING, allowNull: false },
title: { type: DataTypes.STRING, allowNull: false },
description: { type: DataTypes.TEXT },
body: { type: DataTypes.TEXT, allowNull: false }
}, {
sequelize,
timestamps: true,
modelName: 'Article',
tableName: 'article',
createdAt: true,
updatedAt: true
});
Article.beforeValidate((article) => {
article.slug = slugify(article.title, { lower: true });
});
Article.prototype.toJSONFor = function () {
return {
id: this.id,
slug: this.slug,
title: this.title,
description: this.description,
body: this.body
};
};
module.exports = Article;
-23
View File
@@ -1,23 +0,0 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../util/database");
const Comment = sequelize.define("Comment", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
body: { type: DataTypes.TEXT, allowNull: false }
}, {
sequelize,
timestamps: true,
modelName: 'Comment',
tableName: 'comment',
createdAt: true,
updatedAt: true
});
Comment.prototype.toJSONFor = function () {
return {
id: this.id,
body: this.body
};
};
module.exports = Comment;
-21
View File
@@ -1,21 +0,0 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../util/database");
const Tag = sequelize.define("Tag", {
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
}, {
sequelize,
timestamps: true,
modelName: 'Tag',
tableName: 'tag',
createdAt: true,
updatedAt: true
});
Tag.prototype.toJSONFor = function () {
return {
name: this.name
};
};
module.exports = Tag;
-52
View File
@@ -1,52 +0,0 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const bcrypt = require("bcryptjs");
const User = sequelize.define("User", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false, unique: true },
username: { type: DataTypes.STRING, allowNull: false, unique: true },
firstname: { type: DataTypes.STRING },
lastname: { type: DataTypes.STRING },
bio: { type: DataTypes.TEXT, allowNull: true },
image: { type: DataTypes.TEXT, allowNull: true },
role: { type: DataTypes.STRING },
password: { type: DataTypes.STRING, allowNull: false }
}, {
sequelize,
timestamps: true,
modelName: 'User',
tableName: 'user',
createdAt: true,
updatedAt: true
});
Model.prototype.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const DEFAULT_SALT_ROUNDS = 10;
User.addHook("beforeCreate", async (user) => {
const encryptedPassword = await bcrypt.hash(
user.password,
DEFAULT_SALT_ROUNDS
);
user.password = encryptedPassword;
});
User.prototype.toJSONFor = function () {
return {
id: this.id,
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
bio: this.bio,
image: this.image,
role: this.role
};
};
module.exports = User;
+15 -4
View File
@@ -1,4 +1,15 @@
exports.User = require('./User');
exports.Article = require('./Article');
exports.Comment = require('./Comment');
exports.Tag = require('./Tag');
exports.User = require('./mongo/User');
exports.Application = require('./mongo/Application');
exports.Aeronef = require('./mongo/Aeronef');
exports.Canopy = require('./mongo/Canopy');
exports.Dropzone = require('./mongo/Dropzone');
exports.JumpFile = require('./mongo/JumpFile');
exports.Jump = require('./mongo/Jump');
exports.Qcm = require('./mongo/Qcm');
exports.QcmCategory = require('./mongo/QcmCategory');
exports.QcmQuestion = require('./mongo/QcmQuestion');
exports.QcmChoice = require('./mongo/QcmChoice');
exports.X2DataLog = require('./mongo/X2DataLog');
exports.Article = require('./mongo/Article');
exports.Comment = require('./mongo/Comment');
exports.Tag = require('./mongo/Tag');
+33
View File
@@ -0,0 +1,33 @@
var mongoose = require('mongoose');
var slug = require('slug');
var AeronefSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
aeronef: String,
imat: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
AeronefSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
AeronefSchema.methods.slugify = function () {
this.slug = slug(`${this.aeronef} ${this.imat}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
AeronefSchema.methods.toJSONFor = function(user){
return {
slug: this.slug,
aeronef: this.aeronef,
imat: this.imat,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Aeronef', AeronefSchema);
+51
View File
@@ -0,0 +1,51 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var ApplicationSchema = new mongoose.Schema({
apikey: String,
maskedkey: String,
slug: { type: String, lowercase: true, unique: true },
title: String,
description: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, { timestamps: true, toJSON: { virtuals: true } });
ApplicationSchema.plugin(uniqueValidator, { message: 'is already taken' });
ApplicationSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
ApplicationSchema.methods.slugify = function () {
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
ApplicationSchema.methods.toJSONFor = function (user) {
return {
maskedkey: this.maskedkey,
slug: this.slug,
title: this.title,
description: this.description,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
ApplicationSchema.methods.toAuthJSON = function () {
return {
maskedkey: this.maskedkey,
slug: this.slug,
title: this.title,
description: this.description,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toJSONFor()
};
};
mongoose.model('Application', ApplicationSchema);
+60
View File
@@ -0,0 +1,60 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var User = mongoose.model('User');
//var Membre = mongoose.model('Membre');
var ArticleSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
title: String,
description: String,
body: String,
membre: String,
// membre: Membre.schema,
// membre: { type: mongoose.Schema.Types.ObjectId, ref: 'Membre' },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
favoritesCount: { type: Number, default: 0 },
tagList: [{ type: String }]
}, { timestamps: true, toJSON: { virtuals: true } });
ArticleSchema.plugin(uniqueValidator, { message: 'is already taken' });
ArticleSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
ArticleSchema.methods.slugify = function () {
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
ArticleSchema.methods.updateFavoriteCount = function () {
var article = this;
return User.count({ favorites: { $in: [article._id] } }).then(function (count) {
article.favoritesCount = count;
return article.save();
});
};
ArticleSchema.methods.toJSONFor = function (user) {
return {
slug: this.slug,
title: this.title,
description: this.description,
body: this.body,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
tagList: this.tagList,
membre: this.membre,
favorited: user ? user.isFavorite(this._id) : false,
favoritesCount: this.favoritesCount,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Article', ArticleSchema);
+33
View File
@@ -0,0 +1,33 @@
var mongoose = require('mongoose');
var slug = require('slug');
var CanopySchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
voile: String,
taille: Number,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
CanopySchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
CanopySchema.methods.slugify = function () {
this.slug = slug(`${this.voile} ${this.taille}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
CanopySchema.methods.toJSONFor = function(user){
return {
slug: this.slug,
voile: this.voile,
taille: this.taille,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Canopy', CanopySchema);
+19
View File
@@ -0,0 +1,19 @@
var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
body: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
article: { type: mongoose.Schema.Types.ObjectId, ref: 'Article' }
}, { timestamps: true, toJSON: { virtuals: true } });
// Requires population of author
CommentSchema.methods.toJSONFor = function (user) {
return {
id: this._id,
body: this.body,
createdAt: this.createdAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Comment', CommentSchema);
+33
View File
@@ -0,0 +1,33 @@
var mongoose = require('mongoose');
var slug = require('slug');
var DropzoneSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
lieu: String,
oaci: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
DropzoneSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
DropzoneSchema.methods.slugify = function () {
this.slug = slug(`${this.lieu} ${this.oaci}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
DropzoneSchema.methods.toJSONFor = function(user){
return {
slug: this.slug,
lieu: this.lieu,
oaci: this.oaci,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Dropzone', DropzoneSchema);
+86
View File
@@ -0,0 +1,86 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var JumpSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
date: { type: Date, default: Date.now },
numero: { type: Number, unique: true },
lieu: String,
oaci: String,
aeronef: String,
imat: String,
hauteur: Number,
deploiement: Number,
voile: String,
taille: Number,
categorie: String,
module: String,
participants: Number,
sautants: [String],
programme: String,
accessoires: String,
zone: String,
dossier: String,
video: String,
files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'JumpFile' }],
x2data: { type: mongoose.Schema.Types.ObjectId, ref: 'X2DataLog' },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
JumpSchema.plugin(uniqueValidator, { message: 'is already taken' });
JumpSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
JumpSchema.methods.slugify = function () {
this.slug = slug(`${this.numero} ${this.lieu}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
JumpSchema.methods.addFile = function (id) {
if (this.files.indexOf(id) === -1) {
this.files.push(id);
}
return this.save();
};
JumpSchema.methods.removeFile = function (id) {
this.files.remove(id);
return this.save();
};
JumpSchema.methods.toJSONFor = function(user) {
return {
slug: this.slug,
date: this.date,
numero: this.numero,
lieu: this.lieu,
oaci: this.oaci,
aeronef: this.aeronef,
imat: this.imat,
hauteur: this.hauteur,
deploiement: this.deploiement,
voile: this.voile,
taille: this.taille,
categorie: this.categorie,
module: this.module,
participants: this.participants,
sautants: this.sautants,
programme: this.programme,
accessoires: this.accessoires,
zone: this.zone,
dossier: this.dossier,
video: this.video,
files: this.files.map(file => file ? file.toJSONForJump() : null),
x2data: this.x2data ? this.x2data.toJSONFor() : null,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Jump', JumpSchema);
+51
View File
@@ -0,0 +1,51 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var JumpFileSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
name: String,
path: String,
type: {
type: String,
enum : ['csv', 'image', 'kml', 'video'],
default: 'video'
},
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
JumpFileSchema.plugin(uniqueValidator, { message: 'is already taken' });
JumpFileSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
JumpFileSchema.methods.slugify = function () {
this.slug = slug(`${this.type}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
JumpFileSchema.methods.toJSONFor = function(user){
return {
slug: this.slug,
name: this.name,
path: this.path,
type: this.type,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
JumpFileSchema.methods.toJSONForJump = function(){
return {
slug: this.slug,
name: this.name,
path: this.path,
type: this.type
};
};
mongoose.model('JumpFile', JumpFileSchema);
+46
View File
@@ -0,0 +1,46 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QcmSchema = new mongoose.Schema({
name: { type: String, lowercase: true, unique: true },
slug: { type: String, lowercase: true, unique: true },
categories: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmCategory' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QcmSchema.plugin(uniqueValidator, { message: 'is already taken' });
QcmSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
QcmSchema.methods.slugify = function () {
this.slug = slug(`${this.name}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
QcmSchema.methods.addCategory = function (id) {
if (this.categories.indexOf(id) === -1) {
this.categories.push(id);
}
return this.save();
};
QcmSchema.methods.removeCategory = function (id) {
this.categories.remove(id);
return this.save();
};
QcmSchema.methods.toJSONFor = function() {
return {
name: this.name,
slug: this.slug,
categories: this.categories.map(category => category.toJSONFor())
};
};
mongoose.model('Qcm', QcmSchema);
+48
View File
@@ -0,0 +1,48 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QcmCategorySchema = new mongoose.Schema({
num: Number,
name: { type: String, unique: true },
slug: { type: String, lowercase: true, unique: true },
questions: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmQuestion' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QcmCategorySchema.plugin(uniqueValidator, { message: 'is already taken' });
QcmCategorySchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
QcmCategorySchema.methods.slugify = function () {
this.slug = slug(`${this.name}-${this.num}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
QcmCategorySchema.methods.addQuestion = function (id) {
if (this.questions.indexOf(id) === -1) {
this.questions.push(id);
}
return this.save();
};
QcmCategorySchema.methods.removeQuestion = function (id) {
this.questions.remove(id);
return this.save();
};
QcmCategorySchema.methods.toJSONFor = function() {
return {
num: this.num,
name: this.name,
slug: this.slug,
questions: this.questions.map(question => question.toJSONFor())
};
};
mongoose.model('QcmCategory', QcmCategorySchema);
+17
View File
@@ -0,0 +1,17 @@
var mongoose = require('mongoose');
var QcmChoiceSchema = new mongoose.Schema({
index: String,
libelle: String,
correct: Boolean
}, {timestamps: true, toJSON: {virtuals: true}});
QcmChoiceSchema.methods.toJSONFor = function() {
return {
index: this.index,
libelle: this.libelle,
correct: this.correct
};
};
mongoose.model('QcmChoice', QcmChoiceSchema);
+31
View File
@@ -0,0 +1,31 @@
var mongoose = require('mongoose');
var QcmQuestionSchema = new mongoose.Schema({
num: Number,
libelle: String,
choices: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmChoice' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QcmQuestionSchema.methods.addChoice = function (id) {
if (this.choices.indexOf(id) === -1) {
this.choices.push(id);
}
return this.save();
};
QcmQuestionSchema.methods.removeChoice = function (id) {
this.choices.remove(id);
return this.save();
};
QcmQuestionSchema.methods.toJSONFor = function() {
return {
num: this.num,
libelle: this.libelle,
choices: this.choices.map(choice => choice.toJSONFor())
};
};
mongoose.model('QcmQuestion', QcmQuestionSchema);
+18
View File
@@ -0,0 +1,18 @@
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const TagSchema = new mongoose.Schema({
tagName: {
type: String,
required: true,
unique: true
},
articles: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Article'
}]
})
TagSchema.plugin(uniqueValidator);
module.exports = mongoose.model('Tag', TagSchema);
+136
View File
@@ -0,0 +1,136 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var crypto = require('crypto');
var jwt = require('jsonwebtoken'),
secret = require('../../config').secret,
session_lifetime = require('../../config').session_lifetime;
var UserSchema = new mongoose.Schema({
email: { type: String, lowercase: true, unique: true, required: [true, "email can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true },
username: { type: String, lowercase: true, unique: true, required: [true, "username can't be blank"], match: [/^[a-zA-Z0-9_]+$/, 'is invalid'], index: true },
role: String,
firstname: { type: String, required: [true, "firstname can't be blank"] },
lastname: { type: String, required: [true, "lastname can't be blank"] },
phone: String,
licence: Number,
poids: Number,
image: String,
bg_image: String,
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }],
following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
hash: String,
salt: String
}, { timestamps: true, toJSON: { virtuals: true } });
UserSchema.plugin(uniqueValidator, { message: 'is already taken.' });
UserSchema.methods.validPassword = function (password) {
let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};
UserSchema.methods.setPassword = function (password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
};
UserSchema.methods.generateJWT = function () {
var today = new Date();
var exp = new Date(today.getTime() + (session_lifetime * 1000));
console.log('Now date :', today.toISOString());
console.log('Expiracy date :', exp.toISOString());
console.log('Session lifetime :', session_lifetime);
return jwt.sign({
id: this._id,
username: this.username,
exp: parseInt(exp.getTime() / 1000)
}, secret, { algorithm: 'HS256' });
};
UserSchema.methods.toAuthJSON = function () {
return {
id: this._id,
email: this.email,
role: this.role,
token: this.generateJWT(),
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
licence: this.licence,
poids: this.poids,
username: this.username,
image: this.image || '/assets/images/users/user.jpg',
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg'
};
};
UserSchema.methods.toJSONFor = function () {
return {
email: this.email,
role: this.role,
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
licence: this.licence,
poids: this.poids,
username: this.username,
image: this.image || '/assets/images/users/user.jpg',
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg'
};
};
UserSchema.methods.toProfileJSONFor = function (user) {
return {
email: this.email,
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
licence: this.licence,
poids: this.poids,
username: this.username,
image: this.image || '/assets/images/users/user.jpg',
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg',
following: user ? user.isFollowing(this._id) : false
};
};
UserSchema.methods.favorite = function (id) {
if (this.favorites.indexOf(id) === -1) {
this.favorites.push(id);
}
return this.save();
};
UserSchema.methods.unfavorite = function (id) {
this.favorites.remove(id);
return this.save();
};
UserSchema.methods.isFavorite = function (id) {
return this.favorites.some(function (favoriteId) {
return favoriteId.toString() === id.toString();
});
};
UserSchema.methods.follow = function (id) {
if (this.following.indexOf(id) === -1) {
this.following.push(id);
}
return this.save();
};
UserSchema.methods.unfollow = function (id) {
this.following.remove(id);
return this.save();
};
UserSchema.methods.isFollowing = function (id) {
return this.following.some(function (followId) {
return followId.toString() === id.toString();
});
};
mongoose.model('User', UserSchema);
+107
View File
@@ -0,0 +1,107 @@
var mongoose = require('mongoose');
var X2DataLogSchema = new mongoose.Schema({
id: String,
name: String,
type: String,
description: String,
landingZone: String,
speed: {
freeFall: {
vertical: {
max: Number,
avg: Number
},
horizontal: {
max: Number,
avg: Number
}
},
underCanopy: {
vertical: {
max: Number,
avg: Number
},
horizontal: {
max: Number,
avg: Number
}
}
},
glideRatio: {
freeFall: {
max: Number,
avg: Number
},
underCanopy: {
max: Number,
avg: Number
}
},
duration: {
freeFall: Number,
underCanopy: Number
},
distance: {
exitFromLandingZone: Number,
totalFlying: Number,
totalHorizontal: Number
},
altitude: {
exit: Number,
deployment: Number
},
cutaway: String,
malfunctions: [
{
name: String,
type: String
}
],
date: String,
createdOn: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
X2DataLogSchema.methods.toJSONFor = function() {
return {
id: this.id,
name: this.name,
type: this.type,
description: this.description,
landingZone: this.landingZone,
speed: this.speed,
glideRatio: this.glideRatio,
duration: this.duration,
distance: this.distance,
altitude: this.altitude,
cutaway: this.cutaway,
malfunctions: this.malfunctions,
date: this.date,
createdOn: this.createdOn
};
};
X2DataLogSchema.methods.toJSONForUser = function(user) {
return {
id: this.id,
name: this.name,
type: this.type,
description: this.description,
landingZone: this.landingZone,
speed: this.speed,
glideRatio: this.glideRatio,
duration: this.duration,
distance: this.distance,
altitude: this.altitude,
cutaway: this.cutaway,
malfunctions: this.malfunctions,
date: this.date,
createdOn: this.createdOn,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('X2DataLog', X2DataLogSchema);
+16
View File
@@ -0,0 +1,16 @@
exports.User = require('./User');
exports.Application = require('./Application');
exports.Aeronef = require('./Aeronef');
exports.Canopy = require('./Canopy');
exports.Dropzone = require('./Dropzone');
exports.JumpFile = require('./JumpFile');
exports.Jump = require('./Jump');
exports.Qcm = require('./Qcm');
exports.QcmCategory = require('./QcmCategory');
exports.QcmQuestion = require('./QcmQuestion');
exports.QcmChoice = require('./QcmChoice');
exports.X2DataLog = require('./X2DataLog');
exports.Article = require('./Article');
exports.Comment = require('./Comment');
exports.Tag = require('./Tag');
-48
View File
@@ -1,48 +0,0 @@
const slugify = require("slugify");
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Article extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Article.init({
articleId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
slug: { type: DataTypes.STRING, allowNull: false },
title: { type: DataTypes.STRING, allowNull: false },
description: { type: DataTypes.TEXT },
body: { type: DataTypes.TEXT, allowNull: false }
}, {
sequelize,
timestamps: false,
modelName: 'Article',
tableName: 'article',
createdAt: true,
updatedAt: true
});
Article.beforeValidate((article) => {
article.slug = slugify(article.title, { lower: true });
});
Article.prototype.toJSONFor = function () {
return {
articleId: this.articleId,
slug: this.slug,
title: this.title,
description: this.description,
body: this.body
};
};
return Article;
};
-35
View File
@@ -1,35 +0,0 @@
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Comment extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Comment.init({
commentId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
body: { type: DataTypes.TEXT, allowNull: false }
}, {
sequelize,
timestamps: false,
modelName: 'Comment',
tableName: 'comment',
createdAt: true,
updatedAt: true
});
Comment.prototype.toJSONFor = function () {
return {
commentId: this.commentId,
body: this.body
};
};
return Comment;
};
-33
View File
@@ -1,33 +0,0 @@
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Tag extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Tag.init({
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
}, {
sequelize,
timestamps: false,
modelName: 'Tag',
tableName: 'tag',
createdAt: true,
updatedAt: true
});
Tag.prototype.toJSONFor = function () {
return {
name: this.name
};
};
return Tag;
};
-65
View File
@@ -1,65 +0,0 @@
'use strict';
const bcrypt = require("bcryptjs");
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
User.init({
userId: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false},
email: {type: DataTypes.STRING, allowNull: false, unique: true},
username: {type: DataTypes.STRING, allowNull: false, unique: true},
firstname: {type: DataTypes.STRING},
lastname: {type: DataTypes.STRING},
bio: {type: DataTypes.TEXT, allowNull: true},
image: {type: DataTypes.TEXT, allowNull: true},
role: {type: DataTypes.STRING},
password: {type: DataTypes.STRING, allowNull: false}
}, {
sequelize,
timestamps: false,
modelName: 'User',
tableName: 'user',
createdAt: true,
updatedAt: true
});
User.prototype.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const DEFAULT_SALT_ROUNDS = 10;
User.addHook("beforeCreate", async (user) => {
const encryptedPassword = await bcrypt.hash(
user.password,
DEFAULT_SALT_ROUNDS
);
user.password = encryptedPassword;
});
User.prototype.toJSONFor = function () {
return {
userId: this.userId,
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
bio: this.bio,
image: this.image,
role: this.role
};
};
return User;
};
-50
View File
@@ -1,50 +0,0 @@
const fs = require('fs'),
path = require('path'),
basename = path.basename(__filename),
chalk = require('chalk'),
utils = require('../../routes/utils');
const { Sequelize } = require('sequelize');
const db = {};
const Op = Sequelize.Op;
const sequelize = new Sequelize(
process.env.MYSQL_DBNAME,
process.env.MYSQL_DBUSER,
process.env.MYSQL_DBPASS,
{
host: process.env.MYSQL_DBHOST,
port: process.env.MYSQL_DBPORT,
dialect: process.env.MYSQL_DBTYPE,
$like: Op.like,
$not: Op.not
}
);
sequelize.authenticate().then(() => {
if (process.env.DEBUG) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MySQL connection has been established successfully'));
}
}).catch((error) => {
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MySQL database'));
console.error(error);
});
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
+2 -2
View File
@@ -3,8 +3,8 @@
"APP_ENV": "local",
"NODE_ENV" : "development",
"DEBUG": false,
"SERVER_PORT": "3201",
"JWT_SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle",
"SERVER_PORT": "3200",
"SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle",
"SESSION_LIFETIME": "3600",
"MONGODB_URI": "mongodb://localhost:27017/adastradb",
"SENDGRID_API_KEY": "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",
+5934 -3485
View File
File diff suppressed because it is too large Load Diff
+55 -38
View File
@@ -1,40 +1,57 @@
{
"name": "adastra-api",
"version": "1.0.0",
"description": "Ad Astra API",
"private": true,
"license": "UNLICENSED",
"author": "Solide Apps <jgautier.webdev@gmail.com>",
"contributors": [
"Julien Gautier <jgautier.webdev@gmail.com>"
],
"main": "server.js",
"scripts": {
"start": "APP_ENV=production node ./server.js",
"dev": "APP_ENV=development node ./server.js",
"local": "APP_ENV=local nodemon ./server.js",
"test": "newman run ./tests/api-tests.postman.json -e ./tests/env-api-tests.postman.json"
},
"engines": {
"node": "^16.20.2 || ^18.19.1 || ^20.11.1"
},
"dependencies": {
"@sendgrid/mail": "^8.1.5",
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"morgan": "^1.10.0",
"mysql2": "^3.14.3",
"nodemon": "^3.1.10",
"sequelize": "^6.26.0",
"slugify": "^1.6.5"
},
"devDependencies": {
"@eslint/js": "^9.0.0",
"eslint": "^9.0.0",
"prettier": "^2.8.0",
"sequelize-cli": "^6.6.3"
}
"name": "adastra-api",
"version": "1.0.0",
"description": "Ad Astra API",
"main": "app.js",
"author": "Solide Apps <jgautier.webdev@gmail.com>",
"contributors": [
"Julien Gautier <jgautier.webdev@gmail.com>"
],
"scripts": {
"start": "APP_ENV=production node ./app.js",
"dev": "APP_ENV=development node ./app.js",
"local": "APP_ENV=local nodemon ./app.js",
"test": "newman run ./tests/api-tests.postman.json -e ./tests/env-api-tests.postman.json",
"stop": "lsof -ti :3200 | xargs kill",
"mongo:start": "docker run --name hu-mongo -p 27017:27017 mongo & sleep 5",
"mongo:stop": "docker stop hu-mongo && docker rm hu-mongo"
},
"engines": {
"node": "^16.20.2 || ^18.19.1 || ^20.11.1"
},
"license": "UNLICENSED",
"private": true,
"dependencies": {
"@sendgrid/mail": "^7.7.0",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"ejs": "^3.1.9",
"errorhandler": "^1.5.1",
"express": "^4.18.2",
"express-jwt": "^8.4.1",
"express-session": "^1.18.0",
"jsonwebtoken": "^9.0.2",
"method-override": "3.0.0",
"methods": "1.1.2",
"mongoose": "^6.12.6",
"mongoose-unique-validator": "^3.1.0",
"morgan": "^1.10.0",
"node-fetch": "^3.3.2",
"passport": "^0.6.0",
"passport-headerapikey": "^1.2.2",
"passport-local": "^1.0.0",
"request": "^2.88.2",
"slug": "^8.2.3",
"underscore": "^1.13.6",
"uuid": "^9.0.1"
},
"devDependencies": {
"@eslint/js": "^9.0.0",
"eslint": "^9.0.0",
"globals": "^15.0.0",
"newman": "^5.3.2",
"nodemon": "^2.0.22"
}
}
View File
+3563
View File
File diff suppressed because it is too large Load Diff
+143
View File
@@ -0,0 +1,143 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth'),
queries = require('../queries');
router.get('/allByImat', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = queries.getAeronefsByImatQuery(user._id.toString());
Promise.all([
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
//Aeronef.count(query)
]).then(function (results) {
let aeronefs = results[0];
//let aeronefsCount = results[1];
return res.json({
aeronefs: aeronefs.map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, count: data.count };
}),
aeronefsCount: aeronefs.length
});
/*
return res.json({
aeronefs: aeronefs.map(function (aeronef) {
return aeronef.toJSONFor(user);
}),
aeronefsCount: aeronefsCount
});
*/
}).catch(next);
}).catch(next);
});
router.get('/allByImatByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 50;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getAeronefsByImatByYearQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let aeronefs = result.map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, year: data._id.year, count: data.count };
});
return res.json({
aeronefs: aeronefs,
aeronefsCount: aeronefs.length
});
}).catch(next);
}).catch(next);
/*
let limit = 50;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'aeronef': 1,
'imat': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
let user = results[0];
let aeronefs = results[1];
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({
aeronefs: aeronefs,
aeronefsCount: aeronefs.length
});
}).catch(next);
*/
});
module.exports = router;
+173
View File
@@ -0,0 +1,173 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Application = mongoose.model('Application'),
User = mongoose.model('User');
const auth = require('../auth'),
mailer = require('@sendgrid/mail');
mailer.setApiKey(process.env.SENDGRID_API_KEY);
// Preload application objects on routes with ':application'
router.param('application', function (req, res, next, slug) {
Application.findOne({ slug: slug })
.populate('author')
.then(function (application) {
if (!application) {
return res.sendStatus(404);
}
req.application = application;
return next();
}).catch(next);
});
/**
* return all applications
*/
router.get('/', auth.required, function (req, res, next) {
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.apikey !== 'undefined') {
query.apikey = req.query.apikey;
}
if (typeof req.query.maskedkey !== 'undefined') {
query.maskedkey = req.query.maskedkey;
}
Promise.all([
req.query.author ? User.findOne({ username: req.query.author }) : null
]).then(function (author) {
if (author[0]) {
query.author = author[0]._id;
}
return Promise.all([
Application.find(query)
.skip(Number(offset))
.limit(Number(limit))
.sort({ createdAt: 'desc' })
.populate('author')
.exec(),
Application.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
let applications = results[0];
let applicationsCount = results[1];
let user = results[2];
return res.json({
applications: applications.map(function (application) {
return application.toJSONFor(user);
}),
applicationsCount: applicationsCount
});
});
}).catch(next);
});
/**
* save an application
*/
router.post('/', auth.required, function (req, res, next) {
Promise.all([
User.findById(req.payload.id),
auth.generateAPIKey()
]).then(function (results) {
let user = results[0];
let keys = results[1];
if (!user) {
return res.sendStatus(401).json({message: "Unauthorized - You are not allowed to access this resource."});
}
let application = new Application(req.body.application);
application.author = user;
application.apikey = keys.encrypted;
application.maskedkey = keys.masked;
return application.save().then(function () {
let msg = {
to: user.email,
from: process.env.SENDGRID_FROM_MAIL,
subject: `Api-Key ${application.title}`,
text: `Votre Api-Key: ${keys.key}\nAttention, cette Api-Key doit être conservée et ne sera plus affichée.\n\n${application.title}\n${application.description}`,
html: `<h2>${application.title}</h2>
<p>
Votre Api-Key: ${keys.key}<br />
<strong>Attention, cette Api-Key doit être conservée et ne sera plus affichée.</strong>
</p>
<hr />
<p>${application.description}</p>`
};
mailer.send(msg).then(() => {
return res.json({ application: application.toJSONFor(user) });
})
.catch(err => {
res.sendStatus(500).json({message: "A SendGrid error occured while sending an email", err: err});
});
});
}).catch(next);
});
/**
* return an application
*/
router.get('/:application', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
req.application.populate('author')
]).then(function (results) {
let user = results[0];
return res.json({ application: req.application.toJSONFor(user) });
}).catch(next);
});
/**
* update an application
*/
router.put('/:application', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (req.application.author._id.toString() === req.payload.id.toString()) {
if (typeof req.body.application.title !== 'undefined') {
req.application.title = req.body.application.title;
}
if (typeof req.body.application.description !== 'undefined') {
req.application.description = req.body.application.description;
}
if (typeof req.body.application.apikey !== 'undefined') {
req.application.apikey = req.body.application.apikey;
}
if (typeof req.body.application.maskedkey !== 'undefined') {
req.application.maskedkey = req.body.application.maskedkey;
}
req.application.save().then(function (application) {
return res.json({ application: application.toJSONFor(user) });
}).catch(next);
} else {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
});
});
/**
* delete an application
*/
router.delete('/:application', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role == 'Admin' || req.application.author._id.toString() === req.payload.id.toString()) {
return req.application.remove().then(function () {
return res.json({ deleted: true });
});
} else {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
}).catch(next);
});
module.exports = router;
Regular → Executable
+280 -27
View File
@@ -1,30 +1,283 @@
const express = require("express");
const router = express.Router();
const {
getArticle,
getArticles,
createArticle,
articlesFeed,
addFavoriteArticle,
deleteFavoriteArticle,
deleteArticle,
updateArticle,
} = require("../../controllers/articles");
const { protect } = require("../../middlewares/auth");
var router = require('express').Router();
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
var Comment = mongoose.model('Comment');
var User = mongoose.model('User');
var auth = require('../auth');
router
.route("/articles")
.get(protect, getArticles)
.post(protect, createArticle);
router.route("/articles/feed").get(protect, articlesFeed);
router
.route("/articles/:slug")
.get(protect, getArticle)
.put(protect, updateArticle)
.delete(protect, deleteArticle);
router
.route("/articles/:slug/favorite")
.post(protect, addFavoriteArticle)
.delete(protect, deleteFavoriteArticle);
// Preload article objects on routes with ':article'
router.param('article', function (req, res, next, slug) {
Article.findOne({ slug: slug })
.populate('author')
.then(function (article) {
if (!article) {
return res.sendStatus(404);
}
req.article = article;
return next();
}).catch(next);
});
router.param('comment', function (req, res, next, id) {
Comment.findById(id).then(function (comment) {
if (!comment) {
return res.sendStatus(404);
}
req.comment = comment;
return next();
}).catch(next);
});
router.get('/', auth.optional, function (req, res, next) {
var query = {};
var limit = 20;
var offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.membre !== 'undefined') {
query.membre = req.query.membre;
}
if (typeof req.query.tag !== 'undefined') {
query.tagList = { "$in": [req.query.tag] };
}
Promise.all([
req.query.author ? User.findOne({ username: req.query.author }) : null,
req.query.favorited ? User.findOne({ username: req.query.favorited }) : null
]).then(function (results) {
var author = results[0];
var favoriter = results[1];
if (author) {
query.author = author._id;
}
if (favoriter) {
query._id = { $in: favoriter.favorites };
} else if (req.query.favorited) {
query._id = { $in: [] };
}
return Promise.all([
Article.find(query)
.limit(Number(limit))
.skip(Number(offset))
.sort({ createdAt: 'desc' })
.populate('author')
.exec(),
Article.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]).then(function (results) {
var articles = results[0];
var articlesCount = results[1];
var user = results[2];
return res.json({
articles: articles.map(function (article) {
return article.toJSONFor(user);
}),
articlesCount: articlesCount
});
});
}).catch(next);
});
router.get('/feed', auth.required, function (req, res, next) {
var limit = 20;
var offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
Promise.all([
Article.find({ author: { $in: user.following } })
.limit(Number(limit))
.skip(Number(offset))
.populate('author')
.exec(),
Article.count({ author: { $in: user.following } })
]).then(function (results) {
var articles = results[0];
var articlesCount = results[1];
return res.json({
articles: articles.map(function (article) {
return article.toJSONFor(user);
}),
articlesCount: articlesCount
});
}).catch(next);
});
});
router.post('/', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
var article = new Article(req.body.article);
article.author = user;
return article.save().then(function () {
return res.json({ article: article.toJSONFor(user) });
});
}).catch(next);
});
// return a article
router.get('/:article', auth.optional, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
req.article.populate('author')
]).then(function (results) {
var user = results[0];
return res.json({ article: req.article.toJSONFor(user) });
}).catch(next);
});
// update article // 6440016ef84d788c1b352018
router.put('/:article', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (req.article.author._id.toString() === req.payload.id.toString()) {
if (typeof req.body.article.title !== 'undefined') {
req.article.title = req.body.article.title;
}
if (typeof req.body.article.description !== 'undefined') {
req.article.description = req.body.article.description;
}
if (typeof req.body.article.body !== 'undefined') {
req.article.body = req.body.article.body;
}
if (typeof req.body.article.tagList !== 'undefined') {
req.article.tagList = req.body.article.tagList
}
if (typeof req.body.article.membre !== 'undefined') {
req.article.membre = req.body.article.membre;
}
req.article.save().then(function (article) {
return res.json({ article: article.toJSONFor(user) });
}).catch(next);
} else {
return res.sendStatus(403);
}
});
});
// delete article
router.delete('/:article', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
if (req.article.author._id.toString() === req.payload.id.toString()) {
return req.article.remove().then(function () {
return res.sendStatus(204);
});
} else {
return res.sendStatus(403);
}
}).catch(next);
});
// Favorite an article
router.post('/:article/favorite', auth.required, function (req, res, next) {
var articleId = req.article._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
return user.favorite(articleId).then(function () {
return req.article.updateFavoriteCount().then(function (article) {
return res.json({ article: article.toJSONFor(user) });
});
});
}).catch(next);
});
// Unfavorite an article
router.delete('/:article/favorite', auth.required, function (req, res, next) {
var articleId = req.article._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
return user.unfavorite(articleId).then(function () {
return req.article.updateFavoriteCount().then(function (article) {
return res.json({ article: article.toJSONFor(user) });
});
});
}).catch(next);
});
// return an article's comments
router.get('/:article/comments', auth.optional, function (req, res, next) {
Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function (user) {
return req.article.populate({
path: 'comments',
populate: {
path: 'author'
},
options: {
sort: {
createdAt: 'desc'
}
}
}).then(function (article) {
return res.json({
comments: req.article.comments.map(function (comment) {
return comment.toJSONFor(user);
})
});
});
}).catch(next);
});
// create a new comment
router.post('/:article/comments', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
var comment = new Comment(req.body.comment);
comment.article = req.article;
comment.author = user;
return comment.save().then(function () {
req.article.comments.push(comment);
return req.article.save().then(function (article) {
res.json({ comment: comment.toJSONFor(user) });
});
});
}).catch(next);
});
router.delete('/:article/comments/:comment', auth.required, function (req, res, next) {
if (req.comment.author.toString() === req.payload.id.toString()) {
req.article.comments.remove(req.comment._id);
req.article.save()
.then(Comment.find({ _id: req.comment._id }).remove().exec())
.then(function () {
res.sendStatus(204);
});
} else {
res.sendStatus(403);
}
});
module.exports = router;
+166
View File
@@ -0,0 +1,166 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth'),
queries = require('../queries');
router.get('/', auth.required, function (req, res, next) {
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.slug !== 'undefined') {
query.slug = req.query.slug;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role == 'Admin') {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Jump.find(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result;
return res.json({
canopies: canopies,
canopiesCount: canopies.length
});
}).catch(next);
}).catch(next);
});
router.get('/allBySize', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = queries.getCanopiesBySizeQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
});
}).catch(next);
}).catch(next);
});
router.get('/allBySizeByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getCanopiesBySizeByYearQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, year: data._id.year, count: data.count };
});
//console.log(dropzones);
return res.json({
canopies: canopies,
canopiesCount: canopies.length
});
}).catch(next);
}).catch(next);
});
router.get('/allBySizeByModel', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = queries.getCanopiesBySizeByModelQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, voile: data._id.voile, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
});
}).catch(next);
}).catch(next);
});
router.get('/allBySizeByModelByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getCanopiesBySizeByModelByYearQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, voile: data._id.voile, year: data._id.year, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
});
}).catch(next);
}).catch(next);
});
module.exports = router;
+57 -17
View File
@@ -1,23 +1,63 @@
const express = require("express");
const router = express.Router();
var router = require('express').Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment');
var User = mongoose.model('User');
var auth = require('../auth');
const {
getComment,
getComments,
createComment,
deleteComment,
} = require("../../controllers/comments");
// return an article's comments
router.get('/:article/comments', auth.optional, function (req, res, next) {
Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function (user) {
return req.article.populate({
path: 'comments',
populate: {
path: 'author'
},
options: {
sort: {
createdAt: 'desc'
}
}
}).then(function (article) {
return res.json({
comments: req.article.comments.map(function (comment) {
return comment.toJSONFor(user);
})
});
});
}).catch(next);
});
const { protect } = require("../../middlewares/auth");
// create a new comment
router.post('/:article/comments', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
var comment = new Comment(req.body.comment);
comment.article = req.article;
comment.author = user;
router
.route("/articles/:slug/comments")
.get(protect, getComments)
.post(protect, createComment);
return comment.save().then(function () {
req.article.comments.push(comment);
router
.route("/articles/:slug/comments/:id")
.get(protect, getComment)
.delete(protect, deleteComment);
return req.article.save().then(function (article) {
res.json({ comment: comment.toJSONFor(user) });
});
});
}).catch(next);
});
router.delete('/:article/comments/:comment', auth.required, function (req, res, next) {
if (req.comment.author.toString() === req.payload.id.toString()) {
req.article.comments.remove(req.comment._id);
req.article.save()
.then(Comment.find({ _id: req.comment._id }).remove().exec())
.then(function () {
res.sendStatus(204);
});
} else {
res.sendStatus(403);
}
});
module.exports = router;
+69
View File
@@ -0,0 +1,69 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth'),
queries = require('../queries');
router.get('/allByOaci', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getDropZonesByOaciQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let dropzones = result.map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, count: data.count };
});
return res.json({
dropzones: dropzones,
dropzonesCount: dropzones.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByOaciByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getDropZonesByOaciByYearQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let dropzones = result.map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, year: data._id.year, count: data.count };
});
return res.json({
dropzones: dropzones,
dropzonesCount: dropzones.length
});
}).catch(next);
}).catch(next);
});
module.exports = router;
+8 -2
View File
@@ -1,11 +1,17 @@
var router = require('express').Router();
router.use('/', require('./profiles'));
router.use('/', require('./users'));
router.use('/articles', require('./articles'));
router.use('/comments', require('./comments'));
router.use('/tags', require('./tags'));
router.use('/profiles', require('./profiles'));
router.use('/users', require('./users'));
router.use('/applications', require('./applications'));
router.use('/aeronefs', require('./aeronefs'));
router.use('/canopies', require('./canopies'));
router.use('/dropzones', require('./dropzones'));
router.use('/jumps', require('./jumps'));
router.use('/pages', require('./pages'));
router.use('/qcm', require('./qcm'));
router.use(function (err, req, res, next) {
if (err.name === 'ValidationError') {
+621
View File
@@ -0,0 +1,621 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
JumpFile = mongoose.model('JumpFile'),
User = mongoose.model('User'),
X2DataLog = mongoose.model('X2DataLog');
const auth = require('../auth'),
chalk = require('chalk'),
queries = require('../queries'),
utils = require('../utils');
// Preload jump objects on routes with ':jump'
router.param('jump', function (req, res, next, slug) {
Jump.findOne({ slug: slug })
.populate('author')
.populate('files')
.populate('x2data')
.then(function (jump) {
if (!jump) {
return res.sendStatus(404);
}
req.jump = jump;
return next();
}).catch(next);
});
/**
* return all jumps
*/
router.get('/', auth.required, function (req, res, next) {
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.title !== 'undefined') {
const rgx = new RegExp(`.*${req.query.title}.*`);
query = {
$or: [
{ title: { $regex: rgx, $options: "i" } },
{ slug: { $regex: rgx, $options: "i" } },
],
}
}
if (typeof req.query.numeroRangeStart !== 'undefined' && typeof req.query.numeroRangeEnd !== 'undefined') {
query.numero = {
$gte: req.query.numeroRangeStart,
$lte: req.query.numeroRangeEnd
};
}
if (typeof req.query.tailleRangeStart !== 'undefined' && typeof req.query.tailleRangeEnd !== 'undefined') {
query.taille = {
$gte: req.query.tailleRangeStart,
$lte: req.query.tailleRangeEnd
};
}
if (typeof req.query.participantsRangeStart !== 'undefined' && typeof req.query.participantsRangeEnd !== 'undefined') {
query.participants = {
$gte: req.query.participantsRangeStart,
$lte: req.query.participantsRangeEnd
};
}
if (typeof req.query.hauteurRangeStart !== 'undefined' && typeof req.query.hauteurRangeEnd !== 'undefined') {
query.hauteur = {
$gte: req.query.hauteurRangeStart,
$lte: req.query.hauteurRangeEnd
};
}
if (typeof req.query.yearRangeStart !== 'undefined' && typeof req.query.yearRangeEnd !== 'undefined') {
query.date = {
$gte: new Date(`${req.query.yearRangeStart}-01-01 00:00:00`),
$lte: new Date(`${req.query.yearRangeEnd}-12-31 23:59:59`)
};
}
if (typeof req.query.dateRangeStart !== 'undefined' && typeof req.query.dateRangeEnd !== 'undefined') {
query.date = {
$gte: new Date(`${req.query.dateRangeStart} 00:00:00`),
$lte: new Date(`${req.query.dateRangeEnd} 23:59:59`)
};
}
Promise.all([
req.query.author ? User.findOne({ username: req.query.author }) : null,
req.query.favorited ? User.findOne({ username: req.query.favorited }) : null
]).then(function (users) {
let author = users[0];
if (author) {
query.author = author._id;
}
Promise.all([
Jump.find(query)
.skip(Number(offset))
.limit(Number(limit))
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
let jumps = results[0];
let jumpsCount = results[1];
let user = results[2];
/*
Promise.all(
jumps.map(jump => {
if (jump.files[0] !== undefined && jump.files[0].type !== 'kml') {
console.log( chalk.green(`Fichier ${jump.files[0].type}`))
//console.log( chalk.green(`Suppression du fichier ${jump.files[2]._id}`))
//return jump.removeFile(jump.files[2]._id);
}
return;
})
).then(function () {
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
}),
jumpsCount: jumpsCount
});
});
*/
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
}),
jumpsCount: jumpsCount
});
});
}).catch(next);
});
router.get('/allByCategorie', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByCategoryQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { categorie: data._id.categorie, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByDateQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { year: data._id.year, month: data._id.month, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByDay', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = {};
let limit = 50;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.dateRangeStart !== 'undefined' && typeof req.query.dateRangeEnd !== 'undefined') {
query = queries.getJumpsByDayQuery(
user._id.toString(),
req.query.dateRangeStart,
req.query.dateRangeEnd
);
} else {
query = queries.getJumpsByDayQuery(user._id.toString());
}
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let days = result.map(function (data) {
return { jumps: data.jumps, count: data.count };
});
return res.json({
days: days,
daysCount: days.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByModule', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByModuleQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { categorie: data._id.categorie, module: data._id.module, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
/**
* return a jump from SkydiverId API
*/
router.get('/allFromSkydiverIdApi', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
utils.fetchSkydiverIdApi('jumps', req.query).then(result => {
if (result.errors === undefined) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception des sauts SkydiverId`));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception des sauts SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
return res.json({
jumps: result,
jumpsCount: result.items.length
});
}).catch(next);
}).catch(next);
});
router.get('/feed', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = { author: { $in: user.following } };
Promise.all([
Jump.find(query)
.skip(Number(offset))
.limit(Number(limit))
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.count(query)
]).then(function (results) {
let jumps = results[0];
let jumpsCount = results[1];
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
}),
jumpsCount: jumpsCount
});
}).catch(next);
});
});
/**
* return last jump
*/
router.get('/last', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
/*Jump.findOne({ slug: slug })
.populate('author')
.then(function (jump) {
if (!jump) {
return res.sendStatus(404);
}
req.jump = jump;
return next();
}).catch(next);*/
Jump.find({})
.limit(1)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec()
.then(function (jumps) {
if (!jumps) {
return res.sendStatus(404);
}
req.lastjump = jumps[0];
if (req.lastjump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
return res.json({ jump: req.lastjump.toJSONFor(user) });
}).catch(next);
}).catch(next);
});
/**
* return a jump
*/
router.get('/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Promise.all([
Jump.findOne({numero: (req.jump.numero - 1)}).exec(),
Jump.findOne({numero: (req.jump.numero + 1)}).exec(),
]).then(function (results) {
return res.json({
jump: req.jump.toJSONFor(user),
prevJump: results[0],
nextJump: results[1]
});
}).catch(next);
}).catch(next);
});
/**
* save a jump
*/
router.post('/', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let jump = new Jump(req.body.jump);
jump.author = user;
//jump.numero = numero;
return jump.save().then(function () {
return res.json({ jump: jump.toJSONFor(user) });
});
}).catch(next);
});
/**
* save a jump file
*/
router.post('/data/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
/*
console.log(req.jump.files);
return res.json({ jump: req.jump.toJSONFor(user) });
*/
Object.assign(req.body.file, {_id: new mongoose.Types.ObjectId()});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user;
files.push(file);
return file.save().then(function () {
Object.assign(req.body.data, {_id: new mongoose.Types.ObjectId()});
let x2data = new X2DataLog(req.body.data);
x2data.author = user;
return x2data.save().then(function () {
req.jump.files = files;
req.jump.x2data = x2data;
Jump.updateOne({_id: req.jump._id}, {files: files, x2data: x2data._id}).then(function () {
return res.json({ jump: req.jump.toJSONFor(user) });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save a jump file
*/
router.post('/file/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Object.assign(req.body.file, {_id: new mongoose.Types.ObjectId()});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user;
files.push(file);
return file.save().then(function () {
Jump.updateOne({_id: req.jump._id}, {files: files}).then(function () {
return res.json({ file: file.toJSONForJump() });
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save a jump file
*/
router.post('/kml/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Object.assign(req.body.file, {
_id: new mongoose.Types.ObjectId(),
name: `${req.jump.x2data.name}.kml`,
path: `/Volumes/Storage/Skydive/X2_Kmls/${req.jump.date.getFullYear()}/`,
type: 'kml'
});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user;
files.push(file);
//console.log(chalk.yellow(`jump/${req.jump.x2data.id}/kml`));
return res.json({ file: file.toJSONForJump() });
/*
utils.fetchSkydiverIdApi(`jump/${req.jump.x2data.id}/kml`, {}).then(result => {
if (result.errors === undefined) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception de l'url du fichier kml SkydiverId`));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception de l'url du fichier kml SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
if (result.url !== undefined) {
console.log(chalk.green(result.url));
} else {
console.log(chalk.red('result.url is undefined'));
}
return res.json({ file: file.toJSONForJump() });
}).catch(next);
return file.save().then(function () {
Jump.updateOne({_id: req.jump._id}, {files: files}).then(function () {
utils.fetchSkydiverIdApi(`jump/${req.jump.x2data.id}/kml`, {}).then(result => {
if (result.errors === undefined) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception de l'url du fichier kml SkydiverId`));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception de l'url du fichier kml SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
if (result.url !== undefined) {
console.log(result.url);
} else {
console.log('result.url is undefined');
}
return res.json({ file: file.toJSONForJump() });
}).catch(next);
}).catch(next);
}).catch(next);
*/
}).catch(next);
});
/**
* update a jump
*/
router.put('/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
if (typeof req.body.jump.date !== 'undefined') {
req.jump.date = req.body.jump.date;
}
if (typeof req.body.jump.numero !== 'undefined') {
req.jump.numero = req.body.jump.numero;
}
if (typeof req.body.jump.lieu !== 'undefined') {
req.jump.lieu = req.body.jump.lieu;
}
if (typeof req.body.jump.oaci !== 'undefined') {
req.jump.oaci = req.body.jump.oaci;
}
if (typeof req.body.jump.aeronef !== 'undefined') {
req.jump.aeronef = req.body.jump.aeronef;
}
if (typeof req.body.jump.imat !== 'undefined') {
req.jump.imat = req.body.jump.imat;
}
if (typeof req.body.jump.hauteur !== 'undefined') {
req.jump.hauteur = req.body.jump.hauteur;
}
if (typeof req.body.jump.voile !== 'undefined') {
req.jump.voile = req.body.jump.voile;
}
if (typeof req.body.jump.taille !== 'undefined') {
req.jump.taille = req.body.jump.taille;
}
if (typeof req.body.jump.categorie !== 'undefined') {
req.jump.categorie = req.body.jump.categorie;
}
if (typeof req.body.jump.module !== 'undefined') {
req.jump.module = req.body.jump.module;
}
if (typeof req.body.jump.participants !== 'undefined') {
req.jump.participants = req.body.jump.participants;
}
if (typeof req.body.jump.sautants !== 'undefined') {
req.jump.sautants = req.body.jump.sautants;
}
if (typeof req.body.jump.programme !== 'undefined') {
req.jump.programme = req.body.jump.programme;
}
if (typeof req.body.jump.accessoires !== 'undefined') {
req.jump.accessoires = req.body.jump.accessoires;
}
if (typeof req.body.jump.zone !== 'undefined') {
req.jump.zone = req.body.jump.zone;
}
if (typeof req.body.jump.dossier !== 'undefined') {
req.jump.dossier = req.body.jump.dossier;
}
if (typeof req.body.jump.video !== 'undefined') {
req.jump.video = req.body.jump.video;
}
return req.jump.save().then(function (jump) {
return res.json({ jump: jump.toJSONFor(user) });
});
}).catch(next);
});
/**
* delete a jump
*/
router.delete('/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() === req.payload.id.toString()) {
return req.jump.remove().then(function () {
return res.json({ deleted: true });
});
} else {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
}).catch(next);
});
module.exports = router;
+285
View File
@@ -0,0 +1,285 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth'),
queries = require('../queries'),
utils = require('../utils');
router.get('/aeronefs', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getAeronefsByImatQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getAeronefsByImatByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let aeronefsByImat = results[1].map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, count: data.count };
});
let aeronefsByImatByYear = results[2].map(function (data) {
return {
aeronef: data._id.aeronef,
imat: data._id.imat,
year: data._id.year,
count: data.count
};
});
return res.json({
aeronefsByImat: aeronefsByImat,
aeronefsByImatByYear: aeronefsByImatByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/canopies', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getCanopiesBySizeQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByModelQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByModelByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let canopiesBySize = results[1].map(function (data) {
return { taille: data._id.taille, count: data.count };
});
let canopiesBySizeByYear = results[2].map(function (data) {
return {
taille: data._id.taille,
year: data._id.year,
count: data.count
};
});
let canopiesBySizeByModel = results[3].map(function (data) {
return {
taille: data._id.taille,
voile: data._id.voile,
count: data.count
};
});
let canopiesBySizeByModelByYear = results[4].map(function (data) {
return {
taille: data._id.taille,
voile: data._id.voile,
year: data._id.year,
count: data.count
};
});
return res.json({
canopiesBySize: canopiesBySize,
canopiesBySizeByYear: canopiesBySizeByYear,
canopiesBySizeByModel: canopiesBySizeByModel,
canopiesBySizeByModelByYear: canopiesBySizeByModelByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/dropzones', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getDropZonesByOaciQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getDropZonesByOaciByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let dropZonesByOaci = results[1].map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, count: data.count };
});
let dropZonesByOaciByYear = results[2].map(function (data) {
return {
lieu: data._id.lieu,
oaci: data._id.oaci,
year: data._id.year,
count: data.count
};
});
return res.json({
dropZonesByOaci: dropZonesByOaci,
dropZonesByOaciByYear: dropZonesByOaciByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/jumps', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getJumpByYearsQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByCategoryQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByModuleQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByDateQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByModuleByDateQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
//utils.fetchSkydiverIdApi('jumps')
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let jumpsByYears = results[1].map(function (data) {
return { year: data._id.year, count: data.count };
});
let jumpsByCategory = results[2].map(function (data) {
return { categorie: data._id.categorie, count: data.count };
});
let jumpsByModule = results[3].map(function (data) {
return { categorie: data._id.categorie, module: data._id.module, count: data.count };
});
let jumpsByDate = results[4].map(function (data) {
return { year: data._id.year, month: data._id.month, count: data.count };
});
let jumpsByDateByModule = results[5].map(function (data) {
return {
categorie: data._id.categorie,
module: data._id.module,
year: data._id.year,
month: data._id.month,
count: data.count
};
});
//let jumpsFromSkydiverIdApi = results[6];
return res.json({
jumpsByCategory: jumpsByCategory,
jumpsByDate: jumpsByDate,
jumpsByDateByModule: jumpsByDateByModule,
jumpsByModule: jumpsByModule,
jumpsByYears: jumpsByYears,
//jumpsFromSkydiverIdApi: jumpsFromSkydiverIdApi,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
module.exports = router;
+54 -13
View File
@@ -1,16 +1,57 @@
const express = require("express");
const router = express.Router();
const {
getProfile,
followUser,
unfollowUser,
} = require("../../controllers/profiles");
const { protect } = require("../../middlewares/auth");
var router = require('express').Router(),
mongoose = require('mongoose'),
User = mongoose.model('User');
const auth = require('../auth');
router.route("/profiles/:username").get(protect, getProfile);
router
.route("/profiles/:username/follow")
.post(protect, followUser)
.delete(protect, unfollowUser);
// Preload user profile on routes with ':username'
router.param('username', function (req, res, next, username) {
User.findOne({ username: username }).then(function (user) {
if (!user) {
return res.sendStatus(404);
}
req.profile = user;
return next();
}).catch(next);
});
router.get('/:username', auth.optional, function (req, res) {
if (req.payload) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.json({ profile: req.profile.toProfileJSONFor(false) });
}
return res.json({ profile: req.profile.toProfileJSONFor(user) });
});
} else {
return res.json({ profile: req.profile.toProfileJSONFor(false) });
}
});
router.post('/:username/follow', auth.required, function (req, res, next) {
let profileId = req.profile._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return user.follow(profileId).then(function () {
return res.json({ profile: req.profile.toProfileJSONFor(user) });
});
}).catch(next);
});
router.delete('/:username/follow', auth.required, function (req, res, next) {
let profileId = req.profile._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return user.unfollow(profileId).then(function () {
return res.json({ profile: req.profile.toProfileJSONFor(user) });
});
}).catch(next);
});
module.exports = router;
+157
View File
@@ -0,0 +1,157 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Qcm = mongoose.model('Qcm'),
QcmCategory = mongoose.model('QcmCategory'),
QcmQuestion = mongoose.model('QcmQuestion'),
QcmChoice = mongoose.model('QcmChoice'),
User = mongoose.model('User');
const auth = require('../auth');
// Preload qcm objects on routes with ':type'
router.param('type', function (req, res, next, type) {
Qcm.findOne({ name: type })
.populate('categories')
.then(qcm => {
if (!qcm) {
return res.status(404).json({ errors: { "Not Found": "Le QCM est introuvable ou inexistant." } });
}
req.qcm = qcm;
Promise.all(
req.qcm.categories.map(category => {
return category.populate('questions').then(() => {
return Promise.all(
category.questions.map(question => question.populate('choices'))
).then(() => {
return category;
}).catch(next);
});
})
).then(() => {
return next();
}).catch(next);
}).catch(next);
});
/**
* return all qcm
*/
router.get('/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
let user = results[0];
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ qcm: [] });
}).catch(next);
});
/**
* return a qcm
*/
router.get('/type/:type', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
let user = results[0];
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ qcm: req.qcm.toJSONFor() });
}).catch(next);
});
/**
* save an array of qcm question choice
*/
router.post('/choices/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
QcmQuestion
.findOne({num: req.body.question.num})
.populate('choices')
.exec()
]).then(async function (results) {
const user = results[0];
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role !== 'Admin') {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
const question = results[1];
if (!question) {
return res.status(422).json({ errors: { question: "question introuvable" } });
}
let choices = [];
Promise.all(
req.body.question.choices.map(data => {
const choiceId = new mongoose.Types.ObjectId();
const choice = new QcmChoice({ _id: choiceId, index: data.index, libelle: data.libelle, correct: data.correct});
choices.push(choiceId);
return choice.save();
})
).then(function () {
question.choices = [...choices];
question.save().then(function () {
QcmQuestion
.findOne({num: req.body.question.num})
.populate('choices')
.exec()
.then(function (question) {
return res.json({ question: question.toJSONFor() });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save an array of qcm category questions
*/
router.post('/questions/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
QcmCategory
.findOne({num: req.body.category.num})
.populate('questions')
.exec()
]).then(async function (results) {
const user = results[0];
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role !== 'Admin') {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
const category = results[1];
if (!category) {
return res.status(422).json({ errors: { category: "catégorie introuvable" } });
}
let questions = [];
Promise.all(
req.body.category.questions.map(data => {
const questionId = new mongoose.Types.ObjectId();
const question = new QcmQuestion({ _id: questionId, num: data.num, libelle: data.libelle, choices: []});
questions.push(questionId);
return question.save();
})
).then(function () {
category.questions = [...questions];
category.save().then(function () {
QcmCategory
.findOne({num: req.body.category.num})
.populate('questions')
.exec()
.then(function (category) {
return res.json({ category: category.toJSONFor() });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
module.exports = router;
Regular → Executable
+9 -5
View File
@@ -1,8 +1,12 @@
const express = require("express");
const router = express.Router();
var router = require('express').Router();
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
const { getTags } = require("../../controllers/tags");
router.route("/tags/").get(getTags);
// return a list of tags
router.get('/', function(req, res, next) {
Article.find().distinct('tagList').then( tags => {
return res.json({tags: tags});
}).catch(next);
});
module.exports = router;
+122 -12
View File
@@ -1,16 +1,126 @@
const express = require("express");
const router = express.Router();
const {
createUser,
loginUser,
getCurrentUser,
updateUser,
} = require("../../controllers/users");
const { protect } = require("../../middlewares/auth");
var router = require('express').Router(),
mongoose = require('mongoose'),
User = mongoose.model('User');
const passport = require('passport'),
auth = require('../auth');
router.post("/users", createUser);
router.post("/users/login", loginUser);
router.get('/user', auth.required, function (req, res, next) {
//console.log(req.payload);
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ user: user.toAuthJSON() });
}).catch(next);
});
router.route("/user").get(protect, getCurrentUser).put(protect, updateUser);
router.put('/user', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (typeof req.body.user.username !== 'undefined') {
user.username = req.body.user.username;
}
if (typeof req.body.user.email !== 'undefined') {
user.email = req.body.user.email;
}
if (typeof req.body.user.firstname !== 'undefined') {
user.firstname = req.body.user.firstname;
}
if (typeof req.body.user.lastname !== 'undefined') {
user.lastname = req.body.user.lastname;
}
if (typeof req.body.user.phone !== 'undefined') {
user.phone = req.body.user.phone;
}
if (typeof req.body.user.licence !== 'undefined') {
user.licence = req.body.user.licence;
}
if (typeof req.body.user.poids !== 'undefined') {
user.poids = req.body.user.poids;
}
if (typeof req.body.user.image !== 'undefined') {
user.image = req.body.user.image;
}
if (typeof req.body.user.bg_image !== 'undefined') {
user.bg_image = req.body.user.bg_image;
}
if (typeof req.body.user.password !== 'undefined') {
user.setPassword(req.body.user.password);
}
if (typeof req.body.user.role !== 'undefined') {
user.role = req.body.user.role;
}
return user.save().then(function () {
return res.json({ user: user.toAuthJSON() });
});
}).catch(next);
});
router.post('/users/login', function (req, res, next) {
console.log(req.body.user);
if (!req.body.user.email) {
return res.status(422).json({ errors: { email: "email can't be blank" } });
}
if (!req.body.user.password) {
return res.status(422).json({ errors: { password: " password can't be blank" } });
}
passport.authenticate('local', { session: false }, function (err, user, info) {
if (err) {
return next(err);
}
if (user) {
user.token = user.generateJWT();
return res.json({ user: user.toAuthJSON() });
} else {
return res.status(422).json(info);
}
})(req, res, next);
});
router.get('/authenticate', function (req, res, next) {
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
if (err) {
return res.status(err.status || 500).json({message: "An authentication error occured.", err: err.message});
//return next(err);
}
if (!application) {
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
}
if (application.author) {
application.author.token = application.author.generateJWT();
return res.json({ user: application.author.toAuthJSON(), application: application.toAuthJSON() });
} else {
return res.status(422).json(info);
}
})(req, res, next);
});
router.post('/users', function (req, res, next) {
console.log('ici post users');
let user = new User();
if (typeof req.body.user.username !== 'undefined') {
user.username = req.body.user.username;
} else {
user.username = `${req.body.user.firstname}_${req.body.user.lastname}`;
}
user.email = req.body.user.email;
user.firstname = req.body.user.firstname;
user.lastname = req.body.user.lastname;
user.phone = req.body.user.phone;
if (typeof req.body.user.licence !== 'undefined') {
user.licence = req.body.user.licence;
}
if (typeof req.body.user.poids !== 'undefined') {
user.poids = req.body.user.poids;
}
user.setPassword(req.body.user.password);
user.role = 'User';
user.save().then(function () {
return res.json({ user: user.toAuthJSON() });
}).catch(next);
});
module.exports = router;
+94
View File
@@ -0,0 +1,94 @@
//var jwt = require('express-jwt');
var { expressjwt: jwt } = require("express-jwt"),
secret = require('../config').secret,
bcrypt = require('bcrypt');
const { v4 } = require('uuid'),
passport = require('passport'),
auths = ['Api-Key', 'Basic', 'Bearer', 'Token'];
function getTokenFromHeader(req) {
if(req.headers.authorization && auths.indexOf(req.headers.authorization.split(' ')[0]) !== -1) {
return req.headers.authorization.split(' ')[1];
}
return null;
}
const auth = {
requiredJwt: jwt({
secret: secret,
algorithms: ['HS256'],
requestProperty: 'payload',
getToken: getTokenFromHeader
}),
optional: jwt({
secret: secret,
algorithms: ['HS256'],
requestProperty: 'payload',
credentialsRequired: false,
getToken: getTokenFromHeader
}),
required: async (req, res, next) => {
if(req.headers.authorization && req.headers.authorization.split(' ')[0] === process.env.AUTHORIZATION_PREFIX) {
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
if (err) {
//return res.json({message: "An authentication error occured (required).", err: err.message});
//return res.status(err.status || 500).json({message: "An authentication error occured (required).", err: err.message});
return next({message: "An authentication error occured.", err: err.message});
}
if (!application) {
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
}
req.application = application;
req.payload = {id: application.author._id};
//console.log(application);
//console.log(application.author._id);
return next();
/*
return jwt({
secret: secret,
algorithms: ['HS256'],
requestProperty: 'payload',
getToken: application.author.toAuthJSON().token
})(req, res, next);
*/
})(req, res, next);
} else {
return jwt({
secret: secret,
algorithms: ['HS256'],
requestProperty: 'payload',
getToken: getTokenFromHeader
})(req, res, next);
}
},
getAuthType: (req) => {
if(req.headers.authorization && auths.indexOf(req.headers.authorization.split(' ')[0]) !== -1) {
let value = req.headers.authorization.split(' ')[0];
return value;
}
return null;
},
generateAPIKey: async () => {
const key = v4().replace(/-/g, '');
const salt = secret;
// Génération d'un salt aléatoire : const salt = await Promise.resolve(bcrypt.genSalt(10));
const maskedKey = `${key.slice(0, 4)}...${key.slice(-4)}`;
const encryptedKey = await Promise.resolve(bcrypt.hash(key, salt));
return { key: key, masked: maskedKey, encrypted: encryptedKey};
},
authenticateKey: async (req, res, next) => {
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
if (err) {
return res.status(err.status || 500).json({message: "An authentication error occured (authenticateKey).", err: err.message});
}
if (!application) {
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
}
req.application = application;
return next();
})(req, res, next);
}
};
module.exports = auth;
+507
View File
@@ -0,0 +1,507 @@
const queries = {
getJumpsByCategoryQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'categorie': '$categorie'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByDateQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'year': {
'$year': '$date'
},
'month': {
'$month': '$date'
}
}
}, {
'$group': {
'_id': {
'year': '$year',
'month': '$month'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByModuleByDateQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'module': 1,
'categorie': 1,
'year': {
'$year': '$date'
},
'month': {
'$month': '$date'
}
}
}, {
'$group': {
'_id': {
'module': '$module',
'categorie': '$categorie',
'year': '$year',
'month': '$month'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByModuleQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'categorie': 1,
'module': 1
}
}, {
'$group': {
'_id': {
'categorie': '$categorie',
'module': '$module'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpByYearsQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getAeronefsByImatQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'count': -1
},
}
];
return query;
},
getAeronefsByImatByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'aeronef': 1,
'imat': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getCanopiesBySizeQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getCanopiesBySizeByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getCanopiesBySizeByModelQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getCanopiesBySizeByModelByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'voile': 1,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getDropZonesByOaciQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getDropZonesByOaciByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'lieu': 1,
'oaci': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByDayQuery: (userId, dateRangeStart = null, dateRangeEnd = null) => {
if (dateRangeStart === null) {
dateRangeStart = '1970-01-01 00:00:00';
}
if (dateRangeEnd === null) {
const year = new Date().getFullYear();
dateRangeEnd = `${year}-12-31 23:59:59`;
}
let query = [
{
$match: {
$expr: {
$and: [
{
$eq: [ '$author' , { '$toObjectId': userId } ]
},
{
$gte: ['$date', new Date(dateRangeStart)]
},
{
$lte: ['$date', new Date(dateRangeEnd)]
}
]
}
}
}, {
$project: {
_id: 1,
slug: "$slug",
numero: "$numero",
date: "$date",
year: {
$year: "$date"
},
month: {
$month: "$date"
},
day: {
$dayOfMonth: "$date"
}
}
},
{
$group: {
_id: {
year: "$year",
month: "$month",
day: "$day"
},
jumps: {
$addToSet: {
_id: "$_id",
numero: "$numero",
slug: "$slug",
date: "$date"
}
},
count: {
$sum: 1
}
}
},
{
$sort: {
_id: 1,
}
},
{
$project: {
_id: 0,
jumps: 1,
count: 1
}
}
];
return query;
}
};
module.exports = queries;
+54
View File
@@ -1,3 +1,4 @@
const chalk = require('chalk');
const utils = {
getDateString: () => {
let today = new Date();
@@ -24,6 +25,59 @@ const utils = {
dateString = `[${dateString}]`;
}
return dateString;
},
async fetchSkydiverIdApi(path, query) {
let limit = 50;
let offset = 0;
let args = '';
if (typeof query.limit !== 'undefined') {
limit = query.limit;
}
if (typeof query.offset !== 'undefined') {
offset = ((query.offset/limit)+1);
}
if (offset > 1) {
args += `&page=${offset}`;
}
if (typeof query.dateRangeStart !== 'undefined' && typeof query.dateRangeEnd !== 'undefined') {
args += `&filter[and][0][date][gte]=${query.dateRangeStart}`;
args += `&filter[and][0][date][lte]=${query.dateRangeEnd}`;
}
try {
let url = `${process.env.SKYDIVERID_API_URL}/${path}`;
if (typeof query.limit !== 'undefined') {
url += `?per-page=${limit}${args}`;
}
/* url pour provoquer une erreur en dev : url = `https://www.goldapi.ioppppp/api/${price.metal}/${price.currency}`; */
let options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.SKYDIVERID_API_TOKEN}`,
'Content-Type': 'application/json'
},
redirect: 'follow'
};
/* Pour tester le retour d'erreur : return { errors: { name: 'error name', message: 'error message', type: 'TYPE', code: 'CODE' } }; */
//const response = await fetch(url, options);
return fetch(url, options).then(function (response) {
if (response.status >= 200 && response.status < 400) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception des sauts via SkydiverId API`), `${response.status} ${response.statusText}`);
const data = response.json();
console.log(data);
return data;
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Erreur ${response.status} ${response.statusText}`));
return { errors: { name: response.statusText, message: `Une erreur ${response.status} '${response.statusText}' est survenue lors de la récupération des sauts via SkydiverId API`, type: 'API Error', code: response.status } };
}
})
.catch(error => {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`A fetchSkydiverIdApi error occured ${error.code} ${error.type}`));
return { errors: { name: error.name, message: `A fetchSkydiverIdApi error occured : ${error.message}`, type: error.type, code: error.code } };
});
} catch (error) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`fetchSkydiverIdApi error`));
return { errors: { name: error.name, message: error.message, type: error.type, code: error.code } };
}
}
};
-132
View File
@@ -1,132 +0,0 @@
var appEnv = process.env.APP_ENV;
if (appEnv == undefined) {
appEnv = 'development';
}
require('dotenv').config({ path: `.env.${appEnv}` });
const { promisify } = require('util');
const express = require("express");
const sequelize = require("./util/database");
const chalk = require('chalk');
const morgan = require("morgan");
const colors = require("colors");
const utils = require('./routes/utils');
const { errorHandler } = require("./middlewares/errorHandler");
var isProduction = appEnv === 'production';
const app = express();
// Body parser
app.use(express.json());
if (process.env.NODE_ENV === "development") {
morgan.token('statusColor', (req, res) => {
let status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
? res.statusCode
: undefined
return status >= 500 ? chalk.red(status)
: status >= 429 ? chalk.magenta(status)
: status >= 400 ? chalk.yellow(status)
: status >= 300 ? chalk.cyan(status)
: status >= 200 ? chalk.green(status)
: chalk.underline(status);
});
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
//app.use(require('method-override')());
//app.use(express.static(__dirname + '/public'));
} else {
app.use(morgan("dev"));
}
// CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
/*
var db = require("./models");
*/
// Import Models
const User = require("./models/User");
const Article = require("./models/Article");
const Tag = require("./models/Tag");
const Comment = require("./models/Comment");
// Relations
User.belongsToMany(User, { as: "followers", through: "Followers", foreignKey: "userId", timestamps: false });
User.belongsToMany(User, { as: "following", through: "Followers", foreignKey: "followerId", timestamps: false });
User.hasMany(Article, { foreignKey: "authorId", onDelete: "CASCADE" });
Article.belongsTo(User, { as: "author", foreignKey: "authorId" });
User.hasMany(Comment, { foreignKey: "authorId", onDelete: "CASCADE" });
Comment.belongsTo(User, { as: "author", foreignKey: "authorId" });
Article.hasMany(Comment, { foreignKey: "articleId", onDelete: "CASCADE" });
Comment.belongsTo(Article, { foreignKey: "articleId" });
User.belongsToMany(Article, { as: "favorites", through: "Favorites", timestamps: false });
Article.belongsToMany(User, { through: "Favorites", foreignKey: "articleId", timestamps: false });
Article.belongsToMany(Tag, { through: "TagLists", as: "tagLists", foreignKey: "articleId", timestamps: false, onDelete: "CASCADE" });
Tag.belongsToMany(Article, { through: "ArticleTags", uniqueKey: false, timestamps: false });
// Route files
const users = require("./routes/api/users");
const profiles = require("./routes/api/profiles");
const articles = require("./routes/api/articles");
const comments = require("./routes/api/comments");
const tags = require("./routes/api/tags");
// Mount routers
app.use(users);
app.use(profiles);
app.use(articles);
app.use(comments);
app.use(tags);
//app.use(require('./routes'));
app.use(errorHandler);
//console.log(`User: ${User}`);
//Article.sync();
/*
const sync = async () => await sequelize.sync({ force: true });
sync().then(() => {
User.create({
email: "jgautier.webdev@gmail.com",
username: "adastra",
firstname: "Julien",
lastname: "Gautier",
password: "DKxp24PSnr",
role: "admin"
});
User.create({
email: "rampeur@gmail.com",
username: "solide",
firstname: "Rampeur",
lastname: "Solide",
password: "DKxp24PSnr",
role: "user"
});
});
*/
const startServer = async () => {
const port = process.env.SERVER_PORT || 3200;
await promisify(app.listen).bind(app)(port);
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
}
// finally, let's start our server...
startServer();
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
{
"id": "4aa60b52-97fc-456d-4d4f-14a350e95dff",
"name": "Ad Astra API Tests - Environment",
"values": [
{
"enabled": true,
"key": "apiUrl",
"value": "http://localhost:3200/api",
"type": "text"
}
],
"timestamp": 1505871382668,
"_postman_variable_scope": "environment",
"_postman_exported_at": "2017-09-20T01:36:34.835Z",
"_postman_exported_using": "Postman/5.2.0"
}
-28
View File
@@ -1,28 +0,0 @@
const { Sequelize } = require('sequelize');
const Op = Sequelize.Op;
const sequelize = new Sequelize(
process.env.MYSQL_DBNAME,
process.env.MYSQL_DBUSER,
process.env.MYSQL_DBPASS,
{
host: process.env.MYSQL_DBHOST,
port: process.env.MYSQL_DBPORT,
dialect: process.env.MYSQL_DBTYPE,
$like: Op.like,
$not: Op.not
}
);
const checkConnection = async () => {
try {
await sequelize.authenticate();
console.log(`DB Connected`.cyan.underline.bold);
} catch (error) {
console.error("Unable to connect to the database:".red.bold, error);
}
};
checkConnection();
module.exports = sequelize;
-8
View File
@@ -1,8 +0,0 @@
class ErrorResponse extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
module.exports = ErrorResponse;
-38
View File
@@ -1,38 +0,0 @@
const appendTagList = (articleTags, article) => {
const tagList = articleTags.map((tag) => tag.name);
if (!article) return tagList;
delete article.dataValues.tagLists;
article.dataValues.tagList = tagList;
};
const appendFavorites = async (loggedUser, article) => {
const favorited = await article.hasUser(loggedUser ? loggedUser : null);
article.dataValues.favorited = loggedUser ? favorited : false;
const favoritesCount = await article.countUsers();
article.dataValues.favoritesCount = favoritesCount;
};
const appendFollowers = async (loggedUser, toAppend) => {
//
if (toAppend?.author) {
const author = await toAppend.getAuthor();
const following = await author.hasFollower(loggedUser ? loggedUser : null);
toAppend.author.dataValues.following = loggedUser ? following : false;
const followersCount = await author.countFollowers();
toAppend.author.dataValues.followersCount = followersCount;
//
} else {
const following = await toAppend.hasFollower(
loggedUser ? loggedUser : null
);
toAppend.dataValues.following = loggedUser ? following : false;
const followersCount = await toAppend.countFollowers();
toAppend.dataValues.followersCount = followersCount;
}
};
module.exports = { appendTagList, appendFavorites, appendFollowers };
-14
View File
@@ -1,14 +0,0 @@
const jwt = require("jsonwebtoken");
module.exports.sign = async (user) => {
const token = await jwt.sign(
{ userId: user.userId, username: user.username, email: user.email },
process.env.JWT_SECRET
);
return token;
};
module.exports.verify = async (token) => {
const decoded = await jwt.verify(token, process.env.JWT_SECRET);
return decoded;
};