mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2025-12-24 20:42:43 +00:00
Merge branch 'master' into v3.15.2
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
const HomebrewModel = require('./homebrew.model.js').model;
|
||||
const NotificationModel = require('./notifications.model.js').model;
|
||||
const router = require('express').Router();
|
||||
const Moment = require('moment');
|
||||
//const render = require('vitreum/steps/render');
|
||||
const templateFn = require('../client/template.js');
|
||||
const zlib = require('zlib');
|
||||
|
||||
@@ -22,7 +22,7 @@ const mw = {
|
||||
if(process.env.ADMIN_USER === username && process.env.ADMIN_PASS === password){
|
||||
return next();
|
||||
}
|
||||
return res.status(401).send('Access denied');
|
||||
throw { HBErrorCode: '52', code: 401, message: 'Access denied' };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -138,12 +138,48 @@ router.get('/admin/stats', mw.adminOnly, async (req, res)=>{
|
||||
}
|
||||
});
|
||||
|
||||
// ####################### NOTIFICATIONS
|
||||
|
||||
router.get('/admin/notification/all', async (req, res, next)=>{
|
||||
try {
|
||||
const notifications = await NotificationModel.getAll();
|
||||
return res.json(notifications);
|
||||
} catch (error) {
|
||||
console.log('Error getting all notifications: ', error.message);
|
||||
return res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next)=>{
|
||||
console.table(req.body);
|
||||
try {
|
||||
const notification = await NotificationModel.addNotification(req.body);
|
||||
return res.status(201).json(notification);
|
||||
} catch (error) {
|
||||
console.log('Error adding notification: ', error.message);
|
||||
return res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/admin/notification/delete/:id', mw.adminOnly, async (req, res, next)=>{
|
||||
try {
|
||||
const notification = await NotificationModel.deleteNotification(req.params.id);
|
||||
return res.json(notification);
|
||||
} catch (error) {
|
||||
console.error('Error deleting notification: { key: ', req.params.id, ' error: ', error.message, ' }');
|
||||
return res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/admin', mw.adminOnly, (req, res)=>{
|
||||
templateFn('admin', {
|
||||
url : req.originalUrl
|
||||
})
|
||||
.then((page)=>res.send(page))
|
||||
.catch((err)=>res.sendStatus(500));
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
res.sendStatus(500);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
116
server/admin.api.spec.js
Normal file
116
server/admin.api.spec.js
Normal file
@@ -0,0 +1,116 @@
|
||||
const supertest = require('supertest');
|
||||
|
||||
const app = supertest.agent(require('app.js').app)
|
||||
.set('X-Forwarded-Proto', 'https');
|
||||
|
||||
const NotificationModel = require('./notifications.model.js').model;
|
||||
|
||||
describe('Tests for admin api', ()=>{
|
||||
afterEach(()=>{
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('Notifications', ()=>{
|
||||
it('should return list of all notifications', async ()=>{
|
||||
const testNotifications = ['a', 'b'];
|
||||
|
||||
jest.spyOn(NotificationModel, 'find')
|
||||
.mockImplementationOnce(() => {
|
||||
return { exec: jest.fn().mockResolvedValue(testNotifications) };
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.get('/admin/notification/all')
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(testNotifications);
|
||||
});
|
||||
|
||||
it('should add a new notification', async ()=>{
|
||||
const inputNotification = {
|
||||
title : 'Test Notification',
|
||||
text : 'This is a test notification',
|
||||
startAt : new Date().toISOString(),
|
||||
stopAt : new Date().toISOString(),
|
||||
dismissKey : 'testKey'
|
||||
};
|
||||
|
||||
const savedNotification = {
|
||||
...inputNotification,
|
||||
_id : expect.any(String),
|
||||
createdAt : expect.any(String),
|
||||
startAt : inputNotification.startAt,
|
||||
stopAt : inputNotification.stopAt,
|
||||
};
|
||||
|
||||
jest.spyOn(NotificationModel.prototype, 'save')
|
||||
.mockImplementationOnce(function() {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.post('/admin/notification/add')
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.send(inputNotification);
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body).toEqual(savedNotification);
|
||||
});
|
||||
|
||||
it('should handle error adding a notification without dismissKey', async () => {
|
||||
const inputNotification = {
|
||||
title : 'Test Notification',
|
||||
text : 'This is a test notification',
|
||||
startAt : new Date().toISOString(),
|
||||
stopAt : new Date().toISOString()
|
||||
};
|
||||
|
||||
//Change 'save' function to just return itself instead of actually interacting with the database
|
||||
jest.spyOn(NotificationModel.prototype, 'save')
|
||||
.mockImplementationOnce(function() {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.post('/admin/notification/add')
|
||||
.set('Authorization', 'Basic ' + Buffer.from('admin:password3').toString('base64'))
|
||||
.send(inputNotification);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ message: 'Dismiss key is required!' });
|
||||
});
|
||||
|
||||
it('should delete a notification based on its dismiss key', async ()=>{
|
||||
const dismissKey = 'testKey';
|
||||
|
||||
jest.spyOn(NotificationModel, 'findOneAndDelete')
|
||||
.mockImplementationOnce((key) => {
|
||||
return { exec: jest.fn().mockResolvedValue(key) };
|
||||
});
|
||||
const response = await app
|
||||
.delete(`/admin/notification/delete/${dismissKey}`)
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
|
||||
|
||||
expect(NotificationModel.findOneAndDelete).toHaveBeenCalledWith({'dismissKey': 'testKey'});
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ dismissKey: 'testKey' });
|
||||
});
|
||||
|
||||
it('should handle error deleting a notification that doesnt exist', async ()=>{
|
||||
const dismissKey = 'testKey';
|
||||
|
||||
jest.spyOn(NotificationModel, 'findOneAndDelete')
|
||||
.mockImplementationOnce(() => {
|
||||
return { exec: jest.fn().mockResolvedValue() };
|
||||
});
|
||||
const response = await app
|
||||
.delete(`/admin/notification/delete/${dismissKey}`)
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
|
||||
|
||||
expect(NotificationModel.findOneAndDelete).toHaveBeenCalledWith({'dismissKey': 'testKey'});
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ message: 'Notification not found' });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -222,7 +222,6 @@ const GoogleActions = {
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log('Error while creating new Google brew');
|
||||
console.error(err);
|
||||
throw (err);
|
||||
});
|
||||
|
||||
|
||||
@@ -924,7 +924,7 @@ brew`);
|
||||
expect(req.brew).toEqual(testBrew);
|
||||
expect(req.brew).toHaveProperty('style', '\nI Have a style!\n');
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.send).toHaveBeenCalledWith("\nI Have a style!\n");
|
||||
expect(res.send).toHaveBeenCalledWith('\nI Have a style!\n');
|
||||
expect(res.set).toHaveBeenCalledWith({
|
||||
'Cache-Control' : 'no-cache',
|
||||
'Content-Type' : 'text/css'
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
const config = require('../config.js');
|
||||
const nodeEnv = config.get('node_env');
|
||||
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
|
||||
|
||||
module.exports = (req, res, next)=>{
|
||||
const isImageRequest = req.get('Accept')?.split(',')
|
||||
?.filter((h)=>!h.includes('q='))
|
||||
?.every((h)=>/image\/.*/.test(h));
|
||||
if(isImageRequest) {
|
||||
if(isImageRequest && !isLocalEnvironment && !req.url?.startsWith('/staticImages')) {
|
||||
return res.status(406).send({
|
||||
message : 'Request for image at this URL is not supported'
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
62
server/notifications.model.js
Normal file
62
server/notifications.model.js
Normal file
@@ -0,0 +1,62 @@
|
||||
const mongoose = require('mongoose');
|
||||
const _ = require('lodash');
|
||||
|
||||
const NotificationSchema = new mongoose.Schema({
|
||||
dismissKey : { type: String, unique: true, required: true },
|
||||
title : { type: String, default: '' },
|
||||
text : { type: String, default: '' },
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
startAt : { type: Date, default: Date.now },
|
||||
stopAt : { type: Date, default: Date.now },
|
||||
}, { versionKey: false });
|
||||
|
||||
NotificationSchema.statics.addNotification = async function(data) {
|
||||
if(!data.dismissKey) throw { message: 'Dismiss key is required!' };
|
||||
|
||||
const defaults = {
|
||||
title : '',
|
||||
text : '',
|
||||
startAt : new Date(),
|
||||
stopAt : new Date(),
|
||||
};
|
||||
|
||||
const notificationData = _.defaults(data, defaults);
|
||||
|
||||
try {
|
||||
const newNotification = new this(notificationData);
|
||||
const savedNotification = await newNotification.save();
|
||||
return savedNotification;
|
||||
} catch (err) {
|
||||
throw { message: err.message || 'Error saving notification' };
|
||||
}
|
||||
};
|
||||
|
||||
NotificationSchema.statics.deleteNotification = async function(dismissKey) {
|
||||
if(!dismissKey) throw { message: 'Dismiss key is required!' };
|
||||
|
||||
try {
|
||||
const deletedNotification = await this.findOneAndDelete({ dismissKey }).exec();
|
||||
if(!deletedNotification) {
|
||||
throw { message: 'Notification not found' };
|
||||
}
|
||||
return deletedNotification;
|
||||
} catch (err) {
|
||||
throw { message: err.message || 'Error deleting notification' };
|
||||
}
|
||||
};
|
||||
|
||||
NotificationSchema.statics.getAll = async function() {
|
||||
try {
|
||||
const notifications = await this.find().exec();
|
||||
return notifications;
|
||||
} catch (err) {
|
||||
throw { message: err.message || 'Error retrieving notifications' };
|
||||
}
|
||||
};
|
||||
|
||||
const Notification = mongoose.model('Notification', NotificationSchema);
|
||||
|
||||
module.exports = {
|
||||
schema : NotificationSchema,
|
||||
model : Notification,
|
||||
};
|
||||
@@ -29,12 +29,18 @@ const rendererConditions = (legacy, v3)=>{
|
||||
return {}; // If all renderers selected, renderer field not needed in query for speed
|
||||
};
|
||||
|
||||
const sortConditions = (sort, dir) => {
|
||||
return { [sort]: dir === 'asc' ? 1 : -1 };
|
||||
};
|
||||
|
||||
const findBrews = async (req, res)=>{
|
||||
const title = req.query.title || '';
|
||||
const author = req.query.author || '';
|
||||
const page = Math.max(parseInt(req.query.page) || 1, 1);
|
||||
const count = Math.max(parseInt(req.query.count) || 20, 10);
|
||||
const skip = (page - 1) * count;
|
||||
const sort = req.query.sort || 'title';
|
||||
const dir = req.query.dir || 'asc';
|
||||
|
||||
const combinedQuery = {
|
||||
$and : [
|
||||
@@ -54,6 +60,7 @@ const findBrews = async (req, res)=>{
|
||||
};
|
||||
|
||||
await HomebrewModel.find(combinedQuery, projection)
|
||||
.sort(sortConditions(sort, dir))
|
||||
.skip(skip)
|
||||
.limit(count)
|
||||
.maxTimeMS(5000)
|
||||
|
||||
Reference in New Issue
Block a user