mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2025-12-24 20:42:43 +00:00
Merge branch 'master' into dependabot/npm_and_yarn/babel/runtime-7.27.0
This commit is contained in:
@@ -3,14 +3,15 @@ import React, { useEffect, useState } from 'react';
|
||||
const BrewUtils = require('./brewUtils/brewUtils.jsx');
|
||||
const NotificationUtils = require('./notificationUtils/notificationUtils.jsx');
|
||||
import AuthorUtils from './authorUtils/authorUtils.jsx';
|
||||
import LockTools from './lockTools/lockTools.jsx';
|
||||
|
||||
const tabGroups = ['brew', 'notifications', 'authors'];
|
||||
const tabGroups = ['brew', 'notifications', 'authors', 'locks'];
|
||||
|
||||
const Admin = ()=>{
|
||||
const [currentTab, setCurrentTab] = useState('brew');
|
||||
const [currentTab, setCurrentTab] = useState('');
|
||||
|
||||
useEffect(()=>{
|
||||
setCurrentTab(localStorage.getItem('hbAdminTab'));
|
||||
setCurrentTab(localStorage.getItem('hbAdminTab') || 'brew');
|
||||
}, []);
|
||||
|
||||
useEffect(()=>{
|
||||
@@ -40,6 +41,7 @@ const Admin = ()=>{
|
||||
{currentTab === 'brew' && <BrewUtils />}
|
||||
{currentTab === 'notifications' && <NotificationUtils />}
|
||||
{currentTab === 'authors' && <AuthorUtils />}
|
||||
{currentTab === 'locks' && <LockTools />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
342
client/admin/lockTools/lockTools.jsx
Normal file
342
client/admin/lockTools/lockTools.jsx
Normal file
@@ -0,0 +1,342 @@
|
||||
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
|
||||
require('./lockTools.less');
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
|
||||
import request from '../../homebrew/utils/request-middleware.js';
|
||||
|
||||
const LockTools = createClass({
|
||||
displayName : 'LockTools',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
fetching : false,
|
||||
reviewCount : 0
|
||||
};
|
||||
},
|
||||
|
||||
componentDidMount : function() {
|
||||
this.updateReviewCount();
|
||||
},
|
||||
|
||||
updateReviewCount : async function() {
|
||||
const newCount = await request.get('/api/lock/count')
|
||||
.then((res)=>{return res.body?.count || 'Unknown';});
|
||||
if(newCount != this.state.reviewCount){
|
||||
this.setState({
|
||||
reviewCount : newCount
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
updateLockData : function(lock){
|
||||
this.setState({
|
||||
lock : lock
|
||||
});
|
||||
},
|
||||
|
||||
render : function() {
|
||||
return <div className='lockTools'>
|
||||
<h2>Lock Count</h2>
|
||||
<p>Number of brews currently locked: {this.state.reviewCount}</p>
|
||||
<button onClick={this.updateReviewCount}>REFRESH</button>
|
||||
<hr />
|
||||
<LockTable title='Locked Brews' text='Total Locked Brews' resultName='lockedDocuments' fetchURL='/api/locks' propertyNames={['shareId', 'title']} loadBrew={this.updateLockData} ></LockTable>
|
||||
<hr />
|
||||
<LockTable title='Brews Awaiting Review' text='Total Reviews Waiting' resultName='reviewDocuments' fetchURL='/api/lock/reviews' propertyNames={['shareId', 'title']} loadBrew={this.updateLockData} ></LockTable>
|
||||
<hr />
|
||||
<LockBrew key={this.state.lock?.key || 0} lock={this.state.lock}></LockBrew>
|
||||
<hr />
|
||||
<div style={{ columns: 2 }}>
|
||||
<LockLookup title='Unlock Brew' fetchURL='/api/unlock' updateFn={this.updateReviewCount}></LockLookup>
|
||||
<LockLookup title='Clear Review Request' fetchURL='/api/lock/review/remove'></LockLookup>
|
||||
</div>
|
||||
<hr />
|
||||
</div>;
|
||||
}
|
||||
});
|
||||
|
||||
const LockBrew = createClass({
|
||||
displayName : 'LockBrew',
|
||||
getInitialState : function() {
|
||||
// Default values
|
||||
return {
|
||||
brewId : this.props.lock?.shareId || '',
|
||||
code : this.props.lock?.code || 455,
|
||||
editMessage : this.props.lock?.editMessage || '',
|
||||
shareMessage : this.props.lock?.shareMessage || 'This Brew has been locked.',
|
||||
result : {},
|
||||
overwrite : false,
|
||||
};
|
||||
},
|
||||
|
||||
handleChange : function(e, varName) {
|
||||
const output = {};
|
||||
output[varName] = e.target.value;
|
||||
this.setState(output);
|
||||
},
|
||||
|
||||
submit : function(e){
|
||||
e.preventDefault();
|
||||
if(!this.state.editMessage) return;
|
||||
const newLock = {
|
||||
overwrite : this.state.overwrite,
|
||||
code : parseInt(this.state.code) || 100,
|
||||
editMessage : this.state.editMessage,
|
||||
shareMessage : this.state.shareMessage,
|
||||
applied : new Date
|
||||
};
|
||||
|
||||
request.post(`/api/lock/${this.state.brewId}`)
|
||||
.send(newLock)
|
||||
.set('Content-Type', 'application/json')
|
||||
.then((response)=>{
|
||||
this.setState({ result: response.body });
|
||||
})
|
||||
.catch((err)=>{
|
||||
this.setState({ result: err.response.body });
|
||||
});
|
||||
},
|
||||
|
||||
renderInput : function (name) {
|
||||
return <input type='text' name={name} value={this.state[name]} onChange={(e)=>this.handleChange(e, name)} autoComplete='off' required/>;
|
||||
},
|
||||
|
||||
renderResult : function(){
|
||||
return <>
|
||||
<h3>Result:</h3>
|
||||
<table>
|
||||
<tbody>
|
||||
{Object.keys(this.state.result).map((key, idx)=>{
|
||||
return <tr key={`${idx}-row`}>
|
||||
<td key={`${idx}-key`}>{key}</td>
|
||||
<td key={`${idx}-value`}>{this.state.result[key].toString()}
|
||||
</td>
|
||||
</tr>;
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</>;
|
||||
},
|
||||
|
||||
render : function() {
|
||||
return <div className='lockBrew'>
|
||||
<div className='lockForm'>
|
||||
<h2>Lock Brew</h2>
|
||||
<form onSubmit={this.submit}>
|
||||
<label>
|
||||
ID:
|
||||
{this.renderInput('brewId')}
|
||||
</label>
|
||||
<br />
|
||||
<label>
|
||||
Error Code:
|
||||
{this.renderInput('code')}
|
||||
</label>
|
||||
<br />
|
||||
<label>
|
||||
Private Message:
|
||||
{this.renderInput('editMessage')}
|
||||
</label>
|
||||
<br />
|
||||
<label>
|
||||
Public Message:
|
||||
{this.renderInput('shareMessage')}
|
||||
</label>
|
||||
<br />
|
||||
<label className='checkbox'>
|
||||
Overwrite
|
||||
<input name='overwrite' className='checkbox' type='checkbox' value={this.state.overwrite} onClick={()=>{return this.setState((prevState)=>{return { overwrite: !prevState.overwrite };});}} />
|
||||
</label>
|
||||
<label>
|
||||
<input type='submit' />
|
||||
</label>
|
||||
</form>
|
||||
{this.state.result && this.renderResult()}
|
||||
</div>
|
||||
<div className='lockSuggestions'>
|
||||
<h2>Suggestions</h2>
|
||||
<div className='lockCodes'>
|
||||
<h3>Codes</h3>
|
||||
<ul>
|
||||
<li>455 - Generic Lock</li>
|
||||
<li>456 - Copyright issues</li>
|
||||
<li>457 - Confidential Information Leakage</li>
|
||||
<li>458 - Sensitive Personal Information</li>
|
||||
<li>459 - Defamation or Libel</li>
|
||||
<li>460 - Hate Speech or Discrimination</li>
|
||||
<li>461 - Illegal Activities</li>
|
||||
<li>462 - Malware or Phishing</li>
|
||||
<li>463 - Plagiarism</li>
|
||||
<li>465 - Misrepresentation</li>
|
||||
<li>466 - Inappropriate Content</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className='lockMessages'>
|
||||
<h3>Messages</h3>
|
||||
<ul>
|
||||
<li><b>Private Message:</b> This is the private message that is ONLY displayed to the authors of the locked brew. This message MUST specify exactly what actions must be taken in order to have the brew unlocked.</li>
|
||||
<li><b>Public Message:</b> This is the public message that is displayed to the EVERYONE that attempts to view the locked brew.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
});
|
||||
|
||||
const LockTable = createClass({
|
||||
displayName : 'LockTable',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
title : '',
|
||||
text : '',
|
||||
fetchURL : '/api/locks',
|
||||
resultName : '',
|
||||
propertyNames : ['shareId'],
|
||||
loadBrew : ()=>{}
|
||||
};
|
||||
},
|
||||
|
||||
getInitialState : function() {
|
||||
return {
|
||||
result : '',
|
||||
error : '',
|
||||
searching : false
|
||||
};
|
||||
},
|
||||
|
||||
lockKey : React.createRef(0),
|
||||
|
||||
clickFn : function (){
|
||||
this.setState({ searching: true, error: null });
|
||||
|
||||
request.get(this.props.fetchURL)
|
||||
.then((res)=>this.setState({ result: res.body }))
|
||||
.catch((err)=>this.setState({ result: err.response.body }))
|
||||
.finally(()=>{
|
||||
this.setState({ searching: false });
|
||||
});
|
||||
},
|
||||
|
||||
updateBrewLockData : function (lockData){
|
||||
this.lockKey.current++;
|
||||
const brewData = {
|
||||
key : this.lockKey.current,
|
||||
shareId : lockData.shareId,
|
||||
code : lockData.lock.code,
|
||||
editMessage : lockData.lock.editMessage,
|
||||
shareMessage : lockData.lock.shareMessage
|
||||
};
|
||||
this.props.loadBrew(brewData);
|
||||
},
|
||||
|
||||
render : function () {
|
||||
return <>
|
||||
<div className='brewsAwaitingReview'>
|
||||
<div className='brewBlock'>
|
||||
<h2>{this.props.title}</h2>
|
||||
<button onClick={this.clickFn}>
|
||||
REFRESH
|
||||
<i className={`fas ${!this.state.searching ? 'fa-search' : 'fa-spin fa-spinner'}`} />
|
||||
</button>
|
||||
</div>
|
||||
{this.state.result[this.props.resultName] &&
|
||||
<>
|
||||
<p>{this.props.text}: {this.state.result[this.props.resultName].length}</p>
|
||||
<table className='lockTable'>
|
||||
<thead>
|
||||
<tr>
|
||||
{this.props.propertyNames.map((name, idx)=>{
|
||||
return <th key={idx}>{name}</th>;
|
||||
})}
|
||||
<th>clip</th>
|
||||
<th>load</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{this.state.result[this.props.resultName].map((result, resultIdx)=>{
|
||||
return <tr className='row' key={`${resultIdx}-row`}>
|
||||
{this.props.propertyNames.map((name, nameIdx)=>{
|
||||
return <td key={`${resultIdx}-${nameIdx}`}>
|
||||
{result[name].toString()}
|
||||
</td>;
|
||||
})}
|
||||
<td className='icon' title='Copy ID to Clipboard' onClick={()=>{navigator.clipboard.writeText(result.shareId.toString());}}><i className='fa-regular fa-clipboard'></i></td>
|
||||
<td className='icon' title='View Lock details' onClick={()=>{this.updateBrewLockData(result);}}><i className='fa-regular fa-circle-down'></i></td>
|
||||
</tr>;
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
}
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
});
|
||||
|
||||
const LockLookup = createClass({
|
||||
displayName : 'LockLookup',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
fetchURL : '/api/lookup'
|
||||
};
|
||||
},
|
||||
|
||||
getInitialState : function() {
|
||||
return {
|
||||
query : '',
|
||||
result : '',
|
||||
error : '',
|
||||
searching : false
|
||||
};
|
||||
},
|
||||
|
||||
handleChange(e){
|
||||
this.setState({ query: e.target.value });
|
||||
},
|
||||
|
||||
clickFn(){
|
||||
this.setState({ searching: true, error: null });
|
||||
|
||||
request.put(`${this.props.fetchURL}/${this.state.query}`)
|
||||
.then((res)=>this.setState({ result: res.body }))
|
||||
.catch((err)=>this.setState({ result: err.response.body }))
|
||||
.finally(()=>{
|
||||
this.setState({ searching: false });
|
||||
});
|
||||
},
|
||||
|
||||
renderResult : function(){
|
||||
return <div className='lockLookup'>
|
||||
<h3>Result:</h3>
|
||||
<table>
|
||||
<tbody>
|
||||
{Object.keys(this.state.result).map((key, idx)=>{
|
||||
return <tr key={`${idx}-row`}>
|
||||
<td key={`${idx}-key`}>{key}</td>
|
||||
<td key={`${idx}-value`}>{this.state.result[key].toString()}
|
||||
</td>
|
||||
</tr>;
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
},
|
||||
|
||||
render : function() {
|
||||
return <div className='brewLookup'>
|
||||
<h2>{this.props.title}</h2>
|
||||
<input type='text' value={this.state.query} onChange={this.handleChange} placeholder='share id' />
|
||||
<button onClick={this.clickFn}>
|
||||
<i className={`fas ${!this.state.searching ? 'fa-search' : 'fa-spin fa-spinner'}`} />
|
||||
</button>
|
||||
|
||||
{this.state.error
|
||||
&& <div className='error'>{this.state.error.toString()}</div>
|
||||
}
|
||||
|
||||
{this.state.result && this.renderResult()}
|
||||
</div>;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = LockTools;
|
||||
66
client/admin/lockTools/lockTools.less
Normal file
66
client/admin/lockTools/lockTools.less
Normal file
@@ -0,0 +1,66 @@
|
||||
.lockTools {
|
||||
.lockBrew {
|
||||
columns : 2;
|
||||
|
||||
.lockForm {
|
||||
break-inside : avoid;
|
||||
|
||||
label {
|
||||
display : inline-block;
|
||||
width : 100%;
|
||||
line-height : 2.25em;
|
||||
text-align : right;
|
||||
input {
|
||||
float : right;
|
||||
width : 65%;
|
||||
margin-left : 10px;
|
||||
}
|
||||
&.checkbox {
|
||||
line-height: 1.5em;
|
||||
input {
|
||||
width : 1.5em;
|
||||
height : 1.5em;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.lockSuggestions {
|
||||
line-height : 1.2em;
|
||||
break-inside : avoid;
|
||||
columns : 2;
|
||||
h2 { column-span : all; }
|
||||
h3 { margin-top : 0px; }
|
||||
b { font-weight : 600; }
|
||||
|
||||
.lockCodes { break-inside : avoid; }
|
||||
}
|
||||
}
|
||||
|
||||
.lockTable {
|
||||
cursor : default;
|
||||
break-inside : avoid;
|
||||
.row:hover {
|
||||
color : #000000;
|
||||
background-color : #CCCCCC;
|
||||
}
|
||||
.icon {
|
||||
cursor : pointer;
|
||||
&:hover { text-shadow : 0px 0px 6px black; }
|
||||
}
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding : 4px 10px;
|
||||
text-align : center;
|
||||
}
|
||||
table, td { border : 1px solid #333333; }
|
||||
|
||||
.brewLookup {
|
||||
min-height : 175px;
|
||||
break-inside : avoid;
|
||||
h2 { margin-top : 0px; }
|
||||
}
|
||||
|
||||
button i { padding-left : 5px; }
|
||||
}
|
||||
@@ -455,7 +455,7 @@ const EditPage = createClass({
|
||||
<Meta name='robots' content='noindex, nofollow' />
|
||||
{this.renderNavbar()}
|
||||
|
||||
{this.props.brew.lock && <LockNotification shareId={this.props.brew.shareId} message={this.props.brew.lock.editMessage} />}
|
||||
{this.props.brew.lock && <LockNotification shareId={this.props.brew.shareId} message={this.props.brew.lock.editMessage} reviewRequested={this.props.brew.lock.reviewRequested} />}
|
||||
<div className='content'>
|
||||
<SplitPane onDragFinish={this.handleSplitMove}>
|
||||
<Editor
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
require('./lockNotification.less');
|
||||
const React = require('react');
|
||||
import './lockNotification.less';
|
||||
import * as React from 'react';
|
||||
import request from '../../../utils/request-middleware.js';
|
||||
import Dialog from '../../../../components/dialog.jsx';
|
||||
|
||||
function LockNotification(props) {
|
||||
props = {
|
||||
shareId : 0,
|
||||
disableLock : ()=>{},
|
||||
message : '',
|
||||
shareId : 0,
|
||||
disableLock : ()=>{},
|
||||
lock : {},
|
||||
message : 'Unable to retrieve Lock Message',
|
||||
reviewRequested : false,
|
||||
...props
|
||||
};
|
||||
|
||||
const removeLock = ()=>{
|
||||
alert(`Not yet implemented - ID ${props.shareId}`);
|
||||
const [reviewState, setReviewState] = React.useState(props.reviewRequested);
|
||||
|
||||
const removeLock = async ()=>{
|
||||
await request.put(`/api/lock/review/request/${props.shareId}`)
|
||||
.then(()=>{
|
||||
setReviewState(true);
|
||||
});
|
||||
};
|
||||
|
||||
const renderReviewButton = function(){
|
||||
if(reviewState){ return <button className='inactive'>REVIEW REQUESTED</button>; };
|
||||
return <button onClick={removeLock}>REQUEST LOCK REMOVAL</button>;
|
||||
};
|
||||
|
||||
return <Dialog className='lockNotification' blocking closeText='CONTINUE TO EDITOR' >
|
||||
@@ -19,11 +32,11 @@ function LockNotification(props) {
|
||||
<p>This brew been locked by the Administrators. It will not be accessible by any method other than the Editor until the lock is removed.</p>
|
||||
<hr />
|
||||
<h3>LOCK REASON</h3>
|
||||
<p>{props.message || 'Unable to retrieve Lock Message'}</p>
|
||||
<p>{props.message}</p>
|
||||
<hr />
|
||||
<p>Once you have resolved this issue, click REQUEST LOCK REMOVAL to notify the Administrators for review.</p>
|
||||
<p>Click CONTINUE TO EDITOR to temporarily hide this notification; it will reappear the next time the page is reloaded.</p>
|
||||
<button onClick={removeLock}>REQUEST LOCK REMOVAL</button>
|
||||
{renderReviewButton()}
|
||||
</Dialog>;
|
||||
};
|
||||
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
&::backdrop { background-color : #000000AA; }
|
||||
|
||||
button {
|
||||
padding : 2px 15px;
|
||||
margin : 10px;
|
||||
color : white;
|
||||
background-color : #333333;
|
||||
|
||||
&.inactive,
|
||||
&:hover { background-color : #777777; }
|
||||
}
|
||||
|
||||
|
||||
@@ -194,13 +194,47 @@ const errorIndex = (props)=>{
|
||||
|
||||
**Brew ID:** ${props.brew.brewId}
|
||||
|
||||
**Brew Title:** ${escape(props.brew.brewTitle)}`,
|
||||
**Brew Title:** ${escape(props.brew.brewTitle)}
|
||||
|
||||
**Brew Authors:** ${props.brew.authors?.map((author)=>{return `[${author}](/user/${author})`;}).join(', ') || 'Unable to list authors'}`,
|
||||
|
||||
// ####### Admin page error #######
|
||||
'52' : dedent`
|
||||
## Access Denied
|
||||
You need to provide correct administrator credentials to access this page.`,
|
||||
|
||||
// ####### Lock Errors
|
||||
|
||||
'60' : dedent`Lock Error: General`,
|
||||
|
||||
'61' : dedent`Lock Get Error: Unable to get lock count`,
|
||||
|
||||
'62' : dedent`Lock Set Error: Cannot lock`,
|
||||
|
||||
'63' : dedent`Lock Set Error: Brew not found`,
|
||||
|
||||
'64' : dedent`Lock Set Error: Already locked`,
|
||||
|
||||
'65' : dedent`Lock Remove Error: Cannot unlock`,
|
||||
|
||||
'66' : dedent`Lock Remove Error: Brew not found`,
|
||||
|
||||
'67' : dedent`Lock Remove Error: Not locked`,
|
||||
|
||||
'68' : dedent`Lock Get Review Error: Cannot get review requests`,
|
||||
|
||||
'69' : dedent`Lock Set Review Error: Cannot set review request`,
|
||||
|
||||
'70' : dedent`Lock Set Review Error: Brew not found`,
|
||||
|
||||
'71' : dedent`Lock Set Review Error: Review already requested`,
|
||||
|
||||
'72' : dedent`Lock Remove Review Error: Cannot clear review request`,
|
||||
|
||||
'73' : dedent`Lock Remove Review Error: Brew not found`,
|
||||
|
||||
// ####### Other Errors
|
||||
|
||||
'90' : dedent` An unexpected error occurred while looking for these brews.
|
||||
Try again in a few minutes.`,
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
import { model as NotificationModel } from './notifications.model.js';
|
||||
import express from 'express';
|
||||
@@ -11,6 +12,7 @@ import { splitTextStyleAndMetadata } from '../shared/helpers.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
|
||||
process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin';
|
||||
process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password3';
|
||||
|
||||
@@ -162,6 +164,180 @@ router.get('/admin/stats', mw.adminOnly, async (req, res)=>{
|
||||
}
|
||||
});
|
||||
|
||||
// ####################### LOCKS
|
||||
|
||||
router.get('/api/lock/count', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const countLocksQuery = {
|
||||
lock : { $exists: true }
|
||||
};
|
||||
const count = await HomebrewModel.countDocuments(countLocksQuery)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Lock Count Error', message: 'Unable to get lock count', status: 500, HBErrorCode: '61', error };
|
||||
});
|
||||
|
||||
return res.json({ count });
|
||||
|
||||
}));
|
||||
|
||||
router.get('/api/locks', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
const countLocksPipeline = [
|
||||
{
|
||||
$match :
|
||||
{
|
||||
'lock' : { '$exists': 1 }
|
||||
},
|
||||
},
|
||||
{
|
||||
$project : {
|
||||
shareId : 1,
|
||||
editId : 1,
|
||||
title : 1,
|
||||
lock : 1
|
||||
}
|
||||
}
|
||||
];
|
||||
const lockedDocuments = await HomebrewModel.aggregate(countLocksPipeline)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Get Locked Brews', message: 'Unable to get locked brew collection', status: 500, HBErrorCode: '68', error };
|
||||
});
|
||||
return res.json({
|
||||
lockedDocuments
|
||||
});
|
||||
|
||||
}));
|
||||
|
||||
router.post('/api/lock/:id', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const lock = req.body;
|
||||
|
||||
lock.applied = new Date;
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
|
||||
if(!brew) throw { name: 'Brew Not Found', message: 'Cannot find brew to lock', shareId: req.params.id, status: 500, HBErrorCode: '63' };
|
||||
|
||||
if(brew.lock && !lock.overwrite) {
|
||||
throw { name: 'Already Locked', message: 'Lock already exists on brew', shareId: req.params.id, title: brew.title, status: 500, HBErrorCode: '64' };
|
||||
}
|
||||
|
||||
lock.overwrite = undefined;
|
||||
|
||||
brew.lock = lock;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Lock Error', message: 'Unable to set lock', shareId: req.params.id, status: 500, HBErrorCode: '62', error };
|
||||
});
|
||||
|
||||
return res.json({ name: 'LOCKED', message: `Lock applied to brew ID ${brew.shareId} - ${brew.title}`, ...lock });
|
||||
|
||||
}));
|
||||
|
||||
router.put('/api/unlock/:id', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
|
||||
if(!brew) throw { name: 'Brew Not Found', message: 'Cannot find brew to unlock', shareId: req.params.id, status: 500, HBErrorCode: '66' };
|
||||
|
||||
if(!brew.lock) throw { name: 'Not Locked', message: 'Cannot unlock as brew is not locked', shareId: req.params.id, status: 500, HBErrorCode: '67' };
|
||||
|
||||
brew.lock = undefined;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Cannot Unlock', message: 'Unable to clear lock', shareId: req.params.id, status: 500, HBErrorCode: '65', error };
|
||||
});
|
||||
|
||||
return res.json({ name: 'Unlocked', message: `Lock removed from brew ID ${req.params.id}` });
|
||||
}));
|
||||
|
||||
router.get('/api/lock/reviews', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
const countReviewsPipeline = [
|
||||
{
|
||||
$match :
|
||||
{
|
||||
'lock.reviewRequested' : { '$exists': 1 }
|
||||
},
|
||||
},
|
||||
{
|
||||
$project : {
|
||||
shareId : 1,
|
||||
editId : 1,
|
||||
title : 1,
|
||||
lock : 1
|
||||
}
|
||||
}
|
||||
];
|
||||
const reviewDocuments = await HomebrewModel.aggregate(countReviewsPipeline)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Get Reviews', message: 'Unable to get review collection', status: 500, HBErrorCode: '68', error };
|
||||
});
|
||||
return res.json({
|
||||
reviewDocuments
|
||||
});
|
||||
|
||||
}));
|
||||
|
||||
router.put('/api/lock/review/request/:id', asyncHandler(async (req, res)=>{
|
||||
// === This route is NOT Admin only ===
|
||||
// Any user can request a review of their document
|
||||
const filter = {
|
||||
shareId : req.params.id,
|
||||
lock : { $exists: 1 }
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
if(!brew) { throw { name: 'Brew Not Found', message: `Cannot find a locked brew with ID ${req.params.id}`, code: 500, HBErrorCode: '70' }; };
|
||||
|
||||
if(brew.lock.reviewRequested){
|
||||
throw { name: 'Review Already Requested', message: `Review already requested for brew ${brew.shareId} - ${brew.title}`, code: 500, HBErrorCode: '71' };
|
||||
};
|
||||
|
||||
brew.lock.reviewRequested = new Date();
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Set Review Request', message: `Unable to set request for review on brew ID ${req.params.id}`, code: 500, HBErrorCode: '69', error };
|
||||
});
|
||||
|
||||
return res.json({ name: 'Review Requested', message: `Review requested on brew ID ${brew.shareId} - ${brew.title}` });
|
||||
|
||||
}));
|
||||
|
||||
router.put('/api/lock/review/remove/:id', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id,
|
||||
'lock.reviewRequested' : { $exists: 1 }
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
if(!brew) { throw { name: 'Can Not Clear Review Request', message: `Brew ID ${req.params.id} does not have a review pending!`, HBErrorCode: '73' }; };
|
||||
|
||||
brew.lock.reviewRequested = undefined;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Clear Review Request', message: `Unable to remove request for review on brew ID ${req.params.id}`, HBErrorCode: '72', error };
|
||||
});
|
||||
|
||||
return res.json({ name: 'Review Request Cleared', message: `Review request removed for brew ID ${brew.shareId} - ${brew.title}` });
|
||||
|
||||
}));
|
||||
|
||||
// ####################### NOTIFICATIONS
|
||||
|
||||
router.get('/admin/notification/all', async (req, res, next)=>{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/*eslint max-lines: ["warn", {"max": 1000, "skipBlankLines": true, "skipComments": true}]*/
|
||||
import supertest from 'supertest';
|
||||
import HBApp from './app.js';
|
||||
import { model as NotificationModel } from './notifications.model.js';
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
|
||||
|
||||
// Mimic https responses to avoid being redirected all the time
|
||||
@@ -114,4 +116,590 @@ describe('Tests for admin api', ()=>{
|
||||
expect(response.body).toEqual({ message: 'Notification not found' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Locks', ()=>{
|
||||
describe('Count', ()=>{
|
||||
it('Count of all locked documents', async ()=>{
|
||||
const testNumber = 16777216; // 8^8, because why not
|
||||
|
||||
jest.spyOn(HomebrewModel, 'countDocuments')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testNumber);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/lock/count');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ count: testNumber });
|
||||
});
|
||||
|
||||
it('Handle error while fetching count of locked documents', async ()=>{
|
||||
jest.spyOn(HomebrewModel, 'countDocuments')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.reject();
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/lock/count');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '61',
|
||||
message : 'Unable to get lock count',
|
||||
name : 'Lock Count Error',
|
||||
originalUrl : '/api/lock/count',
|
||||
status : 500,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Lists', ()=>{
|
||||
it('Get list of all locked documents', async ()=>{
|
||||
const testLocks = ['a', 'b'];
|
||||
|
||||
jest.spyOn(HomebrewModel, 'aggregate')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testLocks);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/locks');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ lockedDocuments: testLocks });
|
||||
});
|
||||
|
||||
it('Handle error while fetching list of all locked documents', async ()=>{
|
||||
jest.spyOn(HomebrewModel, 'aggregate')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.reject();
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/locks');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '68',
|
||||
message : 'Unable to get locked brew collection',
|
||||
name : 'Can Not Get Locked Brews',
|
||||
originalUrl : '/api/locks',
|
||||
status : 500
|
||||
});
|
||||
});
|
||||
|
||||
it('Get list of all locked documents with pending review requests', async ()=>{
|
||||
const testLocks = ['a', 'b'];
|
||||
|
||||
jest.spyOn(HomebrewModel, 'aggregate')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testLocks);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/lock/reviews');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ reviewDocuments: testLocks });
|
||||
});
|
||||
|
||||
it('Handle error while fetching list of all locked documents with pending review requests', async ()=>{
|
||||
jest.spyOn(HomebrewModel, 'aggregate')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.reject();
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.get('/api/lock/reviews');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '68',
|
||||
message : 'Unable to get review collection',
|
||||
name : 'Can Not Get Reviews',
|
||||
originalUrl : '/api/lock/reviews',
|
||||
status : 500
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Lock', ()=>{
|
||||
it('Lock a brew', async ()=>{
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); }
|
||||
};
|
||||
|
||||
const testLock = {
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.post(`/api/lock/${testBrew.shareId}`)
|
||||
.send(testLock);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
applied : expect.any(String),
|
||||
code : testLock.code,
|
||||
editMessage : testLock.editMessage,
|
||||
shareMessage : testLock.shareMessage,
|
||||
name : 'LOCKED',
|
||||
message : `Lock applied to brew ID ${testBrew.shareId} - ${testBrew.title}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Overwrite lock on a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
code : 999,
|
||||
editMessage : 'newEdit',
|
||||
shareMessage : 'newShare',
|
||||
overwrite : true
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : {
|
||||
code : 1,
|
||||
editMessage : 'oldEdit',
|
||||
shareMessage : 'oldShare',
|
||||
}
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.post(`/api/lock/${testBrew.shareId}`)
|
||||
.send(testLock);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
applied : expect.any(String),
|
||||
code : testLock.code,
|
||||
editMessage : testLock.editMessage,
|
||||
shareMessage : testLock.shareMessage,
|
||||
name : 'LOCKED',
|
||||
message : `Lock applied to brew ID ${testBrew.shareId} - ${testBrew.title}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Error when locking a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
code : 999,
|
||||
editMessage : 'newEdit',
|
||||
shareMessage : 'newShare'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : {
|
||||
code : 1,
|
||||
editMessage : 'oldEdit',
|
||||
shareMessage : 'oldShare',
|
||||
}
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.post(`/api/lock/${testBrew.shareId}`)
|
||||
.send(testLock);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '64',
|
||||
message : 'Lock already exists on brew',
|
||||
name : 'Already Locked',
|
||||
originalUrl : `/api/lock/${testBrew.shareId}`,
|
||||
shareId : testBrew.shareId,
|
||||
status : 500,
|
||||
title : 'title'
|
||||
});
|
||||
});
|
||||
|
||||
it('Handle save error while locking a brew', async ()=>{
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.reject(); }
|
||||
};
|
||||
|
||||
const testLock = {
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.post(`/api/lock/${testBrew.shareId}`)
|
||||
.send(testLock);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '62',
|
||||
message : 'Unable to set lock',
|
||||
name : 'Lock Error',
|
||||
originalUrl : `/api/lock/${testBrew.shareId}`,
|
||||
shareId : testBrew.shareId,
|
||||
status : 500
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Unlock', ()=>{
|
||||
it('Unlock a brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/unlock/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
name : 'Unlocked',
|
||||
message : `Lock removed from brew ID ${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Error when unlocking a brew with no lock', async ()=>{
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/unlock/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '67',
|
||||
message : 'Cannot unlock as brew is not locked',
|
||||
name : 'Not Locked',
|
||||
originalUrl : `/api/unlock/${testBrew.shareId}`,
|
||||
shareId : testBrew.shareId,
|
||||
status : 500,
|
||||
});
|
||||
});
|
||||
|
||||
it('Handle error while unlocking a brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.reject(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/unlock/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '65',
|
||||
message : 'Unable to clear lock',
|
||||
name : 'Cannot Unlock',
|
||||
originalUrl : `/api/unlock/${testBrew.shareId}`,
|
||||
shareId : testBrew.shareId,
|
||||
status : 500
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Reviews', ()=>{
|
||||
it('Add review request to a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.put(`/api/lock/review/request/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
message : `Review requested on brew ID ${testBrew.shareId} - ${testBrew.title}`,
|
||||
name : 'Review Requested',
|
||||
});
|
||||
});
|
||||
|
||||
it('Error when cannot find a locked brew', async ()=>{
|
||||
const testBrew = {
|
||||
shareId : 'shareId'
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
|
||||
const response = await app
|
||||
.put(`/api/lock/review/request/${testBrew.shareId}`)
|
||||
.catch((err)=>{return err;});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
message : `Cannot find a locked brew with ID ${testBrew.shareId}`,
|
||||
name : 'Brew Not Found',
|
||||
HBErrorCode : '70',
|
||||
code : 500,
|
||||
originalUrl : `/api/lock/review/request/${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Error when review is already requested', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share',
|
||||
reviewRequested : 'YES'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
|
||||
const response = await app
|
||||
.put(`/api/lock/review/request/${testBrew.shareId}`)
|
||||
.catch((err)=>{return err;});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '70',
|
||||
code : 500,
|
||||
message : `Cannot find a locked brew with ID ${testBrew.shareId}`,
|
||||
name : 'Brew Not Found',
|
||||
originalUrl : `/api/lock/review/request/${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Handle error while adding review request to a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.reject(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.put(`/api/lock/review/request/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '69',
|
||||
code : 500,
|
||||
message : `Unable to set request for review on brew ID ${testBrew.shareId}`,
|
||||
name : 'Can Not Set Review Request',
|
||||
originalUrl : `/api/lock/review/request/${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Clear review request from a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share',
|
||||
reviewRequested : 'YES'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.resolve(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/lock/review/remove/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
message : `Review request removed for brew ID ${testBrew.shareId} - ${testBrew.title}`,
|
||||
name : 'Review Request Cleared'
|
||||
});
|
||||
});
|
||||
|
||||
it('Error when clearing review request from a brew with no review request', async ()=>{
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/lock/review/remove/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '73',
|
||||
message : `Brew ID ${testBrew.shareId} does not have a review pending!`,
|
||||
name : 'Can Not Clear Review Request',
|
||||
originalUrl : `/api/lock/review/remove/${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
|
||||
it('Handle error while clearing review request from a locked brew', async ()=>{
|
||||
const testLock = {
|
||||
applied : 'YES',
|
||||
code : 999,
|
||||
editMessage : 'edit',
|
||||
shareMessage : 'share',
|
||||
reviewRequested : 'YES'
|
||||
};
|
||||
|
||||
const testBrew = {
|
||||
shareId : 'shareId',
|
||||
title : 'title',
|
||||
markModified : ()=>{ return true; },
|
||||
save : ()=>{ return Promise.reject(); },
|
||||
lock : testLock
|
||||
};
|
||||
|
||||
jest.spyOn(HomebrewModel, 'findOne')
|
||||
.mockImplementationOnce(()=>{
|
||||
return Promise.resolve(testBrew);
|
||||
});
|
||||
|
||||
const response = await app
|
||||
.set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`)
|
||||
.put(`/api/lock/review/remove/${testBrew.shareId}`);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
HBErrorCode : '72',
|
||||
message : `Unable to remove request for review on brew ID ${testBrew.shareId}`,
|
||||
name : 'Can Not Clear Review Request',
|
||||
originalUrl : `/api/lock/review/remove/${testBrew.shareId}`
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// Set working directory to project root
|
||||
import { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import packageJSON from './../package.json' with { type: 'json' };
|
||||
import packageJSON from './../package.json' with { type: 'json' };
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
process.chdir(`${__dirname}/..`);
|
||||
|
||||
@@ -120,8 +120,8 @@ const api = {
|
||||
throw { ...accessError, message: 'User is not logged in', HBErrorCode: '04' };
|
||||
}
|
||||
|
||||
if(stub?.lock?.locked && accessType != 'edit') {
|
||||
throw { HBErrorCode: '51', code: stub?.lock.code, message: stub?.lock.shareMessage, brewId: stub?.shareId, brewTitle: stub?.title };
|
||||
if(stub?.lock && accessType === 'share') {
|
||||
throw { HBErrorCode: '51', code: stub.lock.code, message: stub.lock.shareMessage, brewId: stub.shareId, brewTitle: stub.title, brewAuthors: stub.authors };
|
||||
}
|
||||
|
||||
// If there's a google id, get it if requesting the full brew or if no stub found yet
|
||||
|
||||
@@ -302,7 +302,7 @@ describe('Tests for api', ()=>{
|
||||
});
|
||||
|
||||
it('access is denied to a locked brew', async()=>{
|
||||
const lockBrew = { title: 'test brew', shareId: '1', lock: { locked: true, code: 404, shareMessage: 'brew locked' } };
|
||||
const lockBrew = { title: 'test brew', shareId: '1', lock: { code: 404, shareMessage: 'brew locked' } };
|
||||
model.get = jest.fn(()=>toBrewPromise(lockBrew));
|
||||
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ const HomebrewSchema = mongoose.Schema({
|
||||
updatedAt : { type: Date, default: Date.now },
|
||||
lastViewed : { type: Date, default: Date.now },
|
||||
views : { type: Number, default: 0 },
|
||||
version : { type: Number, default: 1 }
|
||||
version : { type: Number, default: 1 },
|
||||
|
||||
lock : { type: Object }
|
||||
}, { versionKey: false });
|
||||
|
||||
HomebrewSchema.statics.increaseView = async function(query) {
|
||||
|
||||
Reference in New Issue
Block a user