Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if (isLeft(errorOrAttachment)) {
return left(
TransientError("Cannot store message content")
);
}
// Now that the message content has been stored, we can make the message
// visible to getMessages by changing the pending flag to false
const updatedMessageOrError = await lMessageModel.createOrUpdate(
{
...newMessageWithoutContent,
isPending: false
},
createdMessageEvent.message.fiscalCode
);
if (isLeft(updatedMessageOrError)) {
return left(
TransientError("Cannot update message pending status")
);
}
//
// Email notification
//
// check if the user has blocked emails sent from this service
// 'some(true)' in case we must send the notification by email
// 'none' in case the user has blocked the email channel
const isEmailBlockedForService = blockedInboxOrChannels.has(
BlockedInboxOrChannelEnum.EMAIL
);
if (isLeft(errorOrActiveMessage)) {
// if the message is expired no more processing is necessary
return left(
ExpiredError(
`Message expired|notification=${notificationId}|message=${message.id}`
)
);
}
// fetch the notification
const errorOrMaybeNotification = await lNotificationModel.find(
notificationId,
message.id
);
if (isLeft(errorOrMaybeNotification)) {
const error = errorOrMaybeNotification.value;
// we got an error while fetching the notification
return left(
TransientError(
`Error while fetching the notification|notification=${notificationId}|message=${
message.id
}|error=${error.code}`
)
);
}
const maybeEmailNotification = errorOrMaybeNotification.value;
if (isNone(maybeEmailNotification)) {
// it may happen that the object is not yet visible to this function due to latency
// as the notification object is retrieved from database (?)
static fromRawString(rawData: string) {
const data = JSON.parse(rawData)
// TODO: We should validate:
// 1. data.claims being an array
// 2. payload being JSON-parsable
// This is hard to put into io-ts + we need to eventually do signature checking
const parsedData = {
claims: data.claims.map((claim: any) => ({
payload: JSON.parse(claim.payload),
signature: claim.signature,
})),
}
const validatedData = IdentityMetadataType.decode(parsedData)
if (isLeft(validatedData)) {
// TODO: We could probably return a more useful error in the future
throw new Error(PathReporter.report(validatedData).join(', '))
}
return new IdentityMetadataWrapper(validatedData.right)
}
// the user is allowed to see the message when he is either
// a trusted application or he is the sender of the message
const isUserAllowed =
canListMessages ||
retrievedMessage.senderServiceId === userAttributes.service.serviceId;
if (!isUserAllowed) {
// the user is not allowed to see the message
return ResponseErrorForbiddenNotAuthorized;
}
const errorOrMaybeNotification = await notificationModel.findNotificationForMessage(
retrievedMessage.id
);
if (isLeft(errorOrMaybeNotification)) {
// query failed
return ResponseErrorQuery(
"Error while retrieving the notification status",
errorOrMaybeNotification.value
);
}
const maybeNotification = errorOrMaybeNotification.value;
const maybeNotificationStatus = maybeNotification.map(n => {
return {
email: n.emailNotification ? n.emailNotification.status : undefined
};
});
const maybeContentOrError = await messageModel.getStoredContent(
}
// media exists but the content is empty
const maybeContentAsText = maybeContentAsTextOrError.value;
if (isNone(maybeContentAsText)) {
return left>(
new Error("Cannot get stored message content from attachment")
);
}
const contentAsText = maybeContentAsText.value;
// deserialize text into JSON
const contentOrError = MessageContent.decode(JSON.parse(contentAsText));
if (isLeft(contentOrError)) {
const errors: string = readableReport(contentOrError.value);
return left>(
new Error(`Cannot deserialize stored message content: ${errors}`)
);
}
const content = contentOrError.value;
return right>(some(content));
}
}
kind: "INewMessageWithoutContent",
senderServiceId: userService.serviceId,
senderUserId: auth.userId
};
//
// handle real message creation requests
//
// attempt to create the message
const errorOrMessage = await messageModel.create(
newMessageWithoutContent,
newMessageWithoutContent.fiscalCode
);
if (isLeft(errorOrMessage)) {
// we got an error while creating the message
// track the event that a message has failed to be created
applicationInsightsClient.trackEvent({
name: appInsightsEventName,
properties: {
...appInsightsEventProps,
error: "IResponseErrorQuery",
success: "false"
}
});
winston.debug(
`CreateMessageHandler|error|${JSON.stringify(errorOrMessage.value)}`
);
const assertFailure = <a>(parser: parser.Parser, input: string, expected: string) => {
const result = parser(stream.stream(input.split('')))
if (isLeft(result)) {
assert.deepStrictEqual(result.left.expected.join(', '), expected)
} else {
throw new Error(`${result} is not a left`)
}
}
</a>
export const checkForUpdates = async function() {
const pkg = getPackageInfo();
const npmInfoRaw = await request({
uri: `https://registry.npmjs.org/${pkg.name}`,
json: true,
});
const npmInfo = NPMPkgInfo.decode(npmInfoRaw);
if (isLeft(npmInfo)) {
throw new Error(failure(npmInfo.left).join('\n'));
}
return {
isOutdated: (pkg.version !== npmInfo.right['dist-tags'].latest),
name: pkg.name,
current: pkg.version,
latest: npmInfo.right['dist-tags'].latest,
};
};
export const serializeParameterToTemplate = (
from: Ref,
parameter: ParameterObject,
parameterSchema: SchemaObject,
serializedSchema: SerializedType,
target: string,
): Either => {
if (isLeft(openapi3utilsRef)) {
return openapi3utilsRef;
}
const pathToUtils = getRelativePath(from, openapi3utilsRef.right);
const required = isRequired(parameter);
const encoded = serializedFragment(
`${serializedSchema.io}.encode(${target}.${parameter.name})`,
serializedSchema.dependencies,
serializedSchema.refs,
);
return pipe(
getFn(pathToUtils, parameterSchema, parameter),
either.map(fn => getSerializedOptionCallFragment(!required, fn, encoded)),
);
};
export const readConfig = function(configPath: string, encoding = 'utf8') {
const content = fs.readFileSync(configPath, encoding);
const rawConfig = yaml.safeLoad(content);
const config = AccordanceConfig.decode(rawConfig);
if (isLeft(config)) {
throw new Error(failure(config.left).join('\n'));
}
return config.right;
};