Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #338

Merged
merged 7 commits into from
Sep 27, 2023
Merged

Dev #338

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
],
"scripts": {
"dev": "evershop dev",
"dev:debug": "evershop dev --debug",
"setup": "evershop install",
"build": "evershop build",
"start": "evershop start",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ function FileBrowser({
.then((res) => res.json())
.then((response) => {
if (!response.error) {
setFolders(folders.concat(response.data.name));
// Get the first level folder, incase of recursive folder creation
const recursiveFolders = folder.split('/');
setFolders([...new Set(folders.concat(recursiveFolders[0]))]);
} else {
setError(response.error.message);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ ProductList.propTypes = {
products: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
sku: PropTypes.string,
productId: PropTypes.number,
url: PropTypes.string,
price: PropTypes.shape({
Expand Down
70 changes: 36 additions & 34 deletions packages/evershop/src/lib/log/debuger.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,45 @@
const { green, red, blue, yellow, white } = require('kleur');
const isDevelopmentMode = require('../util/isDevelopmentMode');

// Define logger function
function debug(level, message) {
if (!process.argv.includes('--debug')) {
return; // Do not output message to console or file
}
let logMessage = ``;
let textMessage = `${message}`;
// If message is an exception object, include the stack trace
if (message instanceof Error) {
textMessage = `${message.message}\n${message.stack}`;
}
// Switch color based on level
switch (level) {
case 'critical':
logMessage += red(`[debug] ❌ ${textMessage}`);
break;
case 'warning':
logMessage += yellow(`[debug] ⚠️ ${textMessage}`);
break;
case 'info':
logMessage += blue(`[debug] ℹ️ ${textMessage}`);
break;
case 'success':
logMessage += green(`[debug] ✅ ${textMessage}`);
break;
default:
logMessage += white(`[debug] - ${textMessage}`);
break;
}
if (isDevelopmentMode() || process.argv.includes('--debug')) {
let logMessage = ``;
let textMessage = `${message}`;
// If message is an exception object, include the stack trace
if (message instanceof Error) {
textMessage = `${message.message}\n${message.stack}`;
}
// Switch color based on level
switch (level) {
case 'critical':
logMessage += red(`[debug] ❌ ${textMessage}`);
break;
case 'warning':
logMessage += yellow(`[debug] ⚠️ ${textMessage}`);
break;
case 'info':
logMessage += blue(`[debug] ℹ️ ${textMessage}`);
break;
case 'success':
logMessage += green(`[debug] ✅ ${textMessage}`);
break;
default:
logMessage += white(`[debug] - ${textMessage}`);
break;
}

// If message is added to a group, store it in the group
if (this.group && Array.isArray(this.group.messages)) {
this.group.messages.push(logMessage);
return; // Do not output message to console or file
}
// If message is added to a group, store it in the group
if (this.group && Array.isArray(this.group.messages)) {
this.group.messages.push(logMessage);
return; // Do not output message to console or file
}

// eslint-disable-next-line no-console
console.log(logMessage);
// eslint-disable-next-line no-console
console.log(logMessage);
} else {
// Do not output message to console or file
}
}

function error(e) {
Expand Down
2 changes: 1 addition & 1 deletion packages/evershop/src/lib/util/buildFilterFromUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ module.exports.buildFilterFromUrl = (query) => {
filtersFromUrl.push({
key: 'sortBy',
operation: '=',
value: sortBy
value: sortBy.toString()
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { encode } = require('html-entities');
const {
INTERNAL_SERVER_ERROR
} = require('@evershop/evershop/src/lib/util/httpStatus');
Expand Down Expand Up @@ -30,6 +31,6 @@ module.exports = async (err, request, response, delegate, next) => {
}
});
} else {
response.status(500).send(err.message);
response.status(500).send(encode(err.message));
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ module.exports = async (request, response, delegate, next) => {
filtersFromUrl.push({
key: 'sortBy',
operation: '=',
value: sortBy
value: sortBy.toString()
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ FeaturedProducts.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
productId: PropTypes.number.isRequired,
sku: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.shape({
regular: PropTypes.shape({
Expand Down Expand Up @@ -62,6 +63,7 @@ export const query = `
items {
productId
name
sku
price {
regular {
value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ function ToastMessage({ thumbnail, name, qty, count, cartUrl, toastId }) {
<div className="name">
<span className="font-bold">{name}</span>
</div>
<div>
Qty:
{qty}
</div>
<div>{_('QTY: ${qty}', { qty })}</div>
</div>
</div>
<a className="add-cart-popup-button" href={cartUrl}>
Expand Down Expand Up @@ -92,7 +89,7 @@ function AddToCart({ stockAvaibility, loading = false, error }) {
validationRules={['notEmpty']}
className="qty"
name="qty"
placeholder="Qty"
placeholder={_('Qty')}
formId="productForm"
/>
</div>
Expand All @@ -113,7 +110,7 @@ function AddToCart({ stockAvaibility, loading = false, error }) {
/>
)}
{stockAvaibility === false && (
<Button title="SOLD OUT" onAction={() => {}} />
<Button title={_('SOLD OUT')} onAction={() => {}} />
)}
</div>
</div>
Expand Down Expand Up @@ -151,7 +148,7 @@ export default function ProductForm({ product, action }) {
<ToastMessage
thumbnail={response.data.item.thumbnail}
name={product.name}
qty={1}
qty={response.data.item.qty}
count={response.data.count}
cartUrl="/cart"
toastId={toastId}
Expand Down
10 changes: 10 additions & 0 deletions packages/evershop/src/modules/cms/api/fileBrowser/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ const {
// eslint-disable-next-line no-unused-vars
module.exports = (request, response, delegate, next) => {
const path = request.params[0] || '';
// Validate the path to avoid Relative Path Traversal attack
if (path && /^(?!\/|.*\/{2,})[a-zA-Z0-9_\-/]+$/.test(path) === false) {
response.status(INVALID_PAYLOAD).json({
error: {
status: INVALID_PAYLOAD,
message: 'Invalid path'
}
});
return;
}
if (!existsSync(join(CONSTANTS.MEDIAPATH, path))) {
response.status(INVALID_PAYLOAD).json({
error: {
Expand Down
13 changes: 13 additions & 0 deletions packages/evershop/src/modules/cms/api/fileDelete/deleteFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ const {
// eslint-disable-next-line no-unused-vars
module.exports = (request, response, delegate, next) => {
const path = request.params[0] || '';
// Validate the path to avoid Relative Path Traversal attack
if (
// eslint-disable-next-line no-useless-escape
/^(?!(\/|\.{2,}\/))[a-zA-Z0-9_\-/]*\.[a-zA-Z0-9_\-]+$/.test(path) === false
) {
response.status(INVALID_PAYLOAD).json({
error: {
status: INVALID_PAYLOAD,
message: 'Invalid path'
}
});
return;
}
if (!existsSync(join(CONSTANTS.MEDIAPATH, path))) {
response.status(INVALID_PAYLOAD).json({
error: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@ const {

// eslint-disable-next-line no-unused-vars
module.exports = (request, response, delegate, next) => {
const { path } = request.body;
const { path } = request.body || '';
// Validate the path to avoid Relative Path Traversal attack
if (/^(?!\/|.*\/{2,})[a-zA-Z0-9_\-/]+$/.test(path) === false) {
response.status(INVALID_PAYLOAD).json({
error: {
status: INVALID_PAYLOAD,
message: 'Invalid path'
}
});
return;
}
if (existsSync(join(CONSTANTS.MEDIAPATH, path))) {
response.status(INVALID_PAYLOAD).json({
error: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ const { execute } = require('graphql');
const { parse } = require('graphql');
const { validate } = require('graphql/validation');
const isDevelopmentMode = require('@evershop/evershop/src/lib/util/isDevelopmentMode');
const { debug } = require('@evershop/evershop/src/lib/log/debuger');
let schema = require('../../services/buildSchema');
const { getContext } = require('../../services/contextHelper');
const {
graphqlErrorMessageFormat
} = require('../../services/graphqlErrorMessageFormat');

module.exports = async function graphql(request, response, delegate, next) {
// TODO: Should we wait for previous async middlewares?
Expand All @@ -23,6 +27,15 @@ module.exports = async function graphql(request, response, delegate, next) {
// Validate the query
const validationErrors = validate(schema, document);
if (validationErrors.length > 0) {
const formatedErrorMessage = graphqlErrorMessageFormat(
graphqlQuery,
validationErrors[0].locations[0].line,
validationErrors[0].locations[0].column
);
debug(
'critical',
`GraphQL validation error: ${formatedErrorMessage}`
);
next(validationErrors[0]);
} else {
if (isDevelopmentMode()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
module.exports.graphqlErrorMessageFormat = function graphqlErrorMessageFormat(
inputString,
lineNumber,
columnNumber
) {
if (!inputString) {
return '';
}
const lines = inputString.split('\n');
if (lineNumber <= 0 || lineNumber > lines.length) {
return 'Invalid line number';
}

const zeroBasedLineNumber = lineNumber - 1;
const line = lines[zeroBasedLineNumber];
if (columnNumber <= 0 || columnNumber > line.length) {
return 'Invalid column number for the given line';
}
const zeroBasedColumnNumber = columnNumber - 1;
const startIndex = zeroBasedColumnNumber;
let endIndex = line.indexOf(')', startIndex);

if (endIndex === -1) {
endIndex = line.length; // If the special character is not found, highlight until the end of the line
}

const ANSI_RESET = '\x1b[0m';
const ANSI_HIGHLIGHT = '\x1b[33m';

// Apply highlighting to the text
const highlightedText = line.substring(startIndex, endIndex);
const highlightedLine = line.replace(
highlightedText,
`${ANSI_HIGHLIGHT}${highlightedText}${ANSI_RESET}`
);

return highlightedLine;
};
Loading