feat(auth): migrate Application model from MongoDB to MySQL
- Add Sequelize migration creating the 'application' table
- Add Application Sequelize model with slugify, toJSONFor, toAuthJSON
- Rewrite passport-headerapikey strategy to use DB.Application
- Rewrite applications.routes.js to use Sequelize (findAll, count,
build/save, destroy) instead of Mongoose
- Fix pre-existing bug: passport was querying { encryptedKey } but the
stored field is named 'apikey'
- Add Application to MySQL models index and relationships
- Remove Application from Mongoose models index and delete the schema
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Application = mongoose.model('Application');
|
||||
const auth = require('../../../middlewares/auth'),
|
||||
mailer = require('@sendgrid/mail');
|
||||
var router = require('express').Router();
|
||||
const { Op } = require('sequelize');
|
||||
const DB = require('../../../database/mysql');
|
||||
const auth = require('../../../middlewares/auth');
|
||||
const 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 })
|
||||
DB.Application.findOne({ where: { slug } })
|
||||
.then(function (application) {
|
||||
if (!application) {
|
||||
return res.sendStatus(404);
|
||||
@@ -23,47 +23,26 @@ router.param('application', function (req, res, next, slug) {
|
||||
* return all applications
|
||||
*/
|
||||
router.get('/', auth.required, function (req, res, next) {
|
||||
let query = {};
|
||||
let limit = 25;
|
||||
let offset = 0;
|
||||
const limit = parseInt(req.query.limit) || 25;
|
||||
const offset = parseInt(req.query.offset) || 0;
|
||||
const where = {};
|
||||
|
||||
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;
|
||||
}
|
||||
if (req.query.apikey) where.apikey = req.query.apikey;
|
||||
if (req.query.maskedkey) where.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];
|
||||
req.query.author ? UserService.getUserByUsername(req.query.author) : null,
|
||||
req.payload ? UserService.getUserById(req.payload.id) : null
|
||||
]).then(function ([author, user]) {
|
||||
if (author) where.authorId = author.id;
|
||||
|
||||
return Promise.all([
|
||||
DB.Application.findAll({ where, limit, offset, order: [['createdAt', 'DESC']] }),
|
||||
DB.Application.count({ where })
|
||||
]).then(function ([applications, applicationsCount]) {
|
||||
return res.json({
|
||||
applications: applications.map(function (application) {
|
||||
return application.toJSONFor(user);
|
||||
}),
|
||||
applicationsCount: applicationsCount
|
||||
applications: applications.map((a) => a.toJSONFor(user)),
|
||||
applicationsCount
|
||||
});
|
||||
});
|
||||
}).catch(next);
|
||||
@@ -76,18 +55,18 @@ 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];
|
||||
]).then(function ([user, keys]) {
|
||||
if (!user) {
|
||||
return res.sendStatus(401).json({message: "Unauthorized - You are not allowed to access this resource."});
|
||||
return res.status(401).json({ message: 'Unauthorized - You are not allowed to access this resource.' });
|
||||
}
|
||||
let application = new Application(req.body.application);
|
||||
application.author = user.id;
|
||||
|
||||
const application = DB.Application.build(req.body.application);
|
||||
application.authorId = user.id;
|
||||
application.apikey = keys.encrypted;
|
||||
application.maskedkey = keys.masked;
|
||||
|
||||
return application.save().then(function () {
|
||||
let msg = {
|
||||
const msg = {
|
||||
to: user.email,
|
||||
from: process.env.SENDGRID_FROM_MAIL,
|
||||
subject: `Api-Key ${application.title}`,
|
||||
@@ -100,11 +79,10 @@ router.post('/', auth.required, function (req, res, next) {
|
||||
<hr />
|
||||
<p>${application.description}</p>`
|
||||
};
|
||||
mailer.send(msg).then(() => {
|
||||
return 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(err => {
|
||||
return res.status(500).json({ message: 'A SendGrid error occured while sending an email', err });
|
||||
});
|
||||
});
|
||||
}).catch(next);
|
||||
@@ -114,12 +92,10 @@ router.post('/', auth.required, function (req, res, 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);
|
||||
Promise.resolve(req.payload ? UserService.getUserById(req.payload.id) : null)
|
||||
.then(function (user) {
|
||||
return res.json({ application: req.application.toJSONFor(user) });
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -127,26 +103,20 @@ router.get('/:application', auth.required, function (req, res, next) {
|
||||
*/
|
||||
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" } });
|
||||
if (req.application.authorId !== req.payload.id) {
|
||||
return res.status(403).json({ errors: { Forbidden: 'Vous ne disposez pas des autorisations suffisantes' } });
|
||||
}
|
||||
|
||||
const fields = ['title', 'description', 'apikey', 'maskedkey'];
|
||||
fields.forEach((f) => {
|
||||
if (typeof req.body.application[f] !== 'undefined') {
|
||||
req.application[f] = req.body.application[f];
|
||||
}
|
||||
});
|
||||
|
||||
return req.application.save().then(function (application) {
|
||||
return res.json({ application: application.toJSONFor(user) });
|
||||
}).catch(next);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -156,16 +126,14 @@ router.put('/:application', auth.required, function (req, res, next) {
|
||||
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" } });
|
||||
return res.status(401).json({ errors: { Unauthorized: 'authentification 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" } });
|
||||
if (user.role !== 'Admin' && req.application.authorId !== req.payload.id) {
|
||||
return res.status(403).json({ errors: { Forbidden: 'Vous ne disposez pas des autorisations suffisantes' } });
|
||||
}
|
||||
return req.application.destroy().then(function () {
|
||||
return res.json({ deleted: true });
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user