Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
db.cbFind(db.model.TABLE_USER, {[db.model.ID]: userId}, (err, results) => {
if (err) {
callback({
http: httpStatus.UNAUTHORIZED,
error: constants.ERROR_SQL,
message: constants.ERROR_MSG_SQL
});
} else {
if (results.length > 0) {
let user = results[0];
if (user.Password) {
delete user.Password;
}
if (user.Type === constants.USER_TYPE_NOTCONFIRMED) {
// registration is not completed yet
callback({
http: httpStatus.UNAUTHORIZED,
error: constants.ERROR_USERNOTREGISTERED
});
} else {
async deleteFromCart(userObj, arrayOfCartItemIds) {
let result = {};
try {
// find the user first
let user = await User.findOne({email: userObj.email}).exec();
// If the user is not found, its most likely they are not authenticated and don't have user info under session
if (!user) {
result = {httpStatus: httpStatus.UNAUTHORIZED, status: "failed", errorDetails: httpStatus.getStatusText(httpStatus.UNAUTHORIZED)};
return result;
}
// Remove the items from cart for which the ids exists in the arrayOfCartItemIds requested for removal
for(let cartItemId of arrayOfCartItemIds) {
user = await User.findOneAndUpdate({'cart.items._id': cartItemId},
{$pull: { 'cart.items': { _id: cartItemId}}},
{new: true}
).exec()
}
// This means the deleteFromCart was successful if there were any elements worth removing, so return the cart details saving extra api calls from front end
let updatedCartResponse = await this.getCart(userObj);
return updatedCartResponse;
}
catch(err) {
module.exports.getFormConfig = function (req, res) {
var modelName = req.params.modelname;
try {
var Model = mongoose.model(modelName);
var minjector = Model.injector();
var shard = _.clone(minjector.shard, true);
if (injector.security.permissions.shards) {
if (!req.user || !req.user.role) {
res.statusCode = statusCode.UNAUTHORIZED;
res.json("Unauthorized");
return res.end();
}
if (minjector.shard && minjector.shard.shardValues) {
var restrictions = injector.config.permissions.shards[req.user.role];
if (restrictions && restrictions.blacklist) {
shard.shardValues = _.xor(restrictions.blacklist, minjector.shard.shardValues);
shard.filtered = true;
}
if (restrictions && restrictions.whitelist) {
// Region "$OWN_REGION" is translated to the user own region
var list = _.clone(restrictions.whitelist);
var match = list.indexOf("$OWN_REGION");
*
******************************************************************************/
'use strict';
const ITransformerPipelineAction = require('./transformer-pipeline').ITransformerPipelineAction;
const HttpStatusCodes = require('http-status-codes');
const ErrorResponse = require('@adobe/commerce-cif-model').ErrorResponse;
const ERROR_NAME_TO_STATUS_CODE = {
'InvalidArgumentError': HttpStatusCodes.BAD_REQUEST,
'MissingPropertyError': HttpStatusCodes.BAD_REQUEST,
'CommerceServiceResourceNotFoundError': HttpStatusCodes.NOT_FOUND,
'CommerceServiceBadRequestError': HttpStatusCodes.BAD_REQUEST,
'CommerceServiceForbiddenError': HttpStatusCodes.FORBIDDEN,
'CommerceServiceUnauthorizedError': HttpStatusCodes.UNAUTHORIZED,
'NotImplementedError': HttpStatusCodes.NOT_IMPLEMENTED
};
/**
* If the action ended with an error, this transformer maps the error to a status code and updates the response message.
*
* @extends ITransformerPipelineAction
*/
class ExceptionMapperTransformerPipelineAction extends ITransformerPipelineAction {
transform(httpResponse, resultFromOwSequence) {
if (!httpResponse.error) {
return httpResponse;
}
let message;
let reason;
credsAuthUser.write(credentials.authUser);
var pwdLen = req.authorization.basic.password.length;
pwdLen = pwdLen > credentials.authPassword.length ? pwdLen : credentials.authPassword.length;
const reqAuthPassword = Buffer.alloc(pwdLen);
reqAuthPassword.write(req.authorization.basic.password);
const credsAuthPassword = Buffer.alloc(pwdLen);
credsAuthPassword.write(credentials.authPassword);
if (crypto.timingSafeEqual(credsAuthUser, reqAuthUser) & crypto.timingSafeEqual(credsAuthPassword, reqAuthPassword)) {
return next();
}
}
log.error('Invalid auth credentials for requests.');
res.send(HttpStatus.UNAUTHORIZED, {});
return next(false);
};
};
if(userProfile){
var isAuthorized = isCreateRolePresent(userProfile, config.sourceid);
if (isAuthorized) {
next()
} else {
throw "UNAUTHORIZED_USER"
}
}else{
throw 'UNAUTHORIZED_USER'
}
} catch (error) {
if (error === 'USER_NOT_FOUND') {
sendErrorResponse(responseObj, config.apiid, "USER_NOT_FOUND", HttpStatus.BAD_REQUEST)
} else if (error === 'UNAUTHORIZED_USER') {
sendErrorResponse(responseObj, config.apiid, "UNAUTHORIZED_USER", HttpStatus.UNAUTHORIZED)
} else {
sendErrorResponse(responseObj, config.apiid, "UNAUTHORIZED_USER", HttpStatus.UNAUTHORIZED)
}
}
})
}
async fetchWithAuth(url, options: any = {}, forceRefresh: boolean = false) {
if (this.msaAppId) {
options.headers = {
...options.headers,
Authorization: `Bearer ${await this.getAccessToken(forceRefresh)}`
};
}
const response = await this.options.fetch(url, options);
if (
(response.status === HttpStatus.UNAUTHORIZED || response.status === HttpStatus.FORBIDDEN)
&& (!forceRefresh && this.msaAppId)
) {
return await this.fetchWithAuth(url, options, true);
}
return response;
}
function kick() {
res.statusCode = statusCode.UNAUTHORIZED;
res.json("Unauthorized. User role is " + req.user.role + " and this operation needs " + role);
return res.end();
}
usersRouter.get('/:userId/pinned', keycloak.protect(), async (request, response) => {
try {
let userId = request.kauth.grant.access_token.content.sub;
if ( userId !== request.params.userId ) {
return response
.status(HttpStatus.UNAUTHORIZED)
.send(new MyError('Unauthorized', ['the userId does not match the subject in the access token']));
}
const userData = await User.findOne({
userId: request.params.userId
});
if ( !userData ) {
return response
.status(HttpStatus.NOT_FOUND)
.send(new MyError(
'User data was not found',
['User data of the user with the userId ' + request.params.userId + ' was not found']
)
);
} else {
const bookmarks = await Bookmark.find({"_id": {$in: userData.pinned}});
request(options, function (err, response, body) {
if (err) {
logger.error('Request to api failed.', err);
reject(errHandler(HttpStatus.INTERNAL_SERVER_ERROR, err));
}
if (response) {
if (response.statusCode === HttpStatus.INTERNAL_SERVER_ERROR) {
logger.debug('Internal Server Error');
reject(errHandler(HttpStatus.INTERNAL_SERVER_ERROR, errMessages.GENERAL.INTERNAL_SERVER_ERROR));
}
if (response.statusCode === HttpStatus.UNAUTHORIZED) {
logger.debug('Unauthorized request to API');
reject(errHandler(HttpStatus.UNAUTHORIZED, errMessages.AUTH.UNAUTHORIZED_OPERATION));
}
if (response.statusCode === HttpStatus.FORBIDDEN) {
logger.debug('Forbidden request to API');
reject(errHandler(HttpStatus.FORBIDDEN, errMessages.AUTH.FORBIDDEN_OPERATION));
}
logger.debug('Data from API has been retrieved');
try {
const data = JSON.parse(body);
resolve(data);
} catch (err) {
logger.warn('Cannot parse response body');
}
resolve(body);
}
});