Files
adastra_api/src/routes/api/skydive/applications.routes.js
T
julien 66821427be fix(skydive): migrate author field from ObjectId to UUID string
- Register SkydiverProfile model in mysql.js (fixes startup crash on association)
- Replace $toObjectId with direct string match in all 12 aggregation queries
- Guard toJSONFor on all Mongo models to fall back to MySQL user.toProfileJSONFor()
  when author is a UUID string (restores username/image in API responses)
- Pass user to toJSONFor() everywhere instead of null
- Remove dead .populate('author') calls (author: String has no ref)
- Fix ownership check in /last route: compare author string to req.payload.id
  instead of the now-absent author.username property
2026-04-26 04:27:47 +02:00

173 lines
6.2 KiB
JavaScript

var router = require('express').Router(),
mongoose = require('mongoose'),
Application = mongoose.model('Application');
const auth = require('../../../middlewares/auth'),
mailer = require('@sendgrid/mail');
const { UserService } = require('../../../services');
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 })
.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 ? UserService.getUserByUsername(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' })
.exec(),
Application.countDocuments(query).exec(),
req.payload ? UserService.getUserById(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([
UserService.getUserById(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.id;
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 ? UserService.getUserById(req.payload.id) : null
]).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) {
UserService.getUserById(req.payload.id).then(function (user) {
const authorId = req.application.author?.id ?? req.application.author?.toString();
if (authorId === req.payload.id) {
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) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.application.author?.id ?? req.application.author?.toString();
if (user.role == 'Admin' || authorId === req.payload.id) {
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;