@crowdin/app-project-module
Version:
Module that generates for you all common endpoints for serving standalone Crowdin App
124 lines (123 loc) • 5.79 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getToken = exports.prepareCrowdinRequest = void 0;
const crowdin_apps_functions_1 = require("@crowdin/crowdin-apps-functions");
const storage_1 = require("../storage");
const util_1 = require("../util");
const api_1 = require("../modules/api/api");
const connection_1 = require("../util/connection");
const logger_1 = require("../util/logger");
const subscription_1 = require("../util/subscription");
function prepareCrowdinRequest({ jwtToken, config, optional = false, checkSubscriptionExpiration = true, moduleKey, }) {
return __awaiter(this, void 0, void 0, function* () {
(0, logger_1.log)('Validating jwt token from incoming request');
const jwtPayload = yield (0, crowdin_apps_functions_1.validateJwtToken)(jwtToken, config.clientSecret, config.jwtValidationOptions);
const context = {
jwtPayload,
clientId: (0, crowdin_apps_functions_1.constructCrowdinIdFromJwtPayload)(jwtPayload),
crowdinId: `${jwtPayload.domain || jwtPayload.context.organization_id}`,
appIdentifier: config.identifier,
};
const logInfo = (0, logger_1.withContext)(context);
const logError = (0, logger_1.withContextError)(context);
logInfo('Loading crowdin credentials');
const credentials = yield (0, storage_1.getStorage)().getCrowdinCredentials(context.crowdinId);
if (!credentials) {
if (optional) {
return { context, logInfo, logError };
}
throw new Error("Can't find organization by id");
}
if (!!moduleKey && !!jwtPayload.module) {
if (typeof moduleKey === 'string' && moduleKey !== jwtPayload.module) {
throw new Error("Module key doesn't match");
}
if (Array.isArray(moduleKey) && !moduleKey.includes(jwtPayload.module)) {
throw new Error("Module key doesn't match");
}
}
logInfo('Building crowdin client instance');
const { client, token } = yield (0, connection_1.prepareCrowdinClient)({ config, credentials, autoRenew: true, context });
let subscriptionInfo;
if (checkSubscriptionExpiration) {
subscriptionInfo = yield (0, subscription_1.checkSubscription)({
config,
token,
organization: credentials.id,
accountType: credentials.type,
});
if (subscriptionInfo.expired) {
throw new util_1.CodeError(subscriptionInfo.subscribeLink || '', 402);
}
}
return { context, client, subscriptionInfo, logInfo, logError };
});
}
exports.prepareCrowdinRequest = prepareCrowdinRequest;
function handle({ config, optional = false, checkSubscriptionExpiration = true, moduleKey, }) {
return (0, util_1.runAsyncWrapper)((req, res, next) => __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const jwtToken = getToken(req);
if (!jwtToken) {
(0, logger_1.temporaryErrorDebug)('Access denied: crowdin-client', req);
return res.status(403).send({ error: 'Access denied' });
}
try {
const data = yield prepareCrowdinRequest({
jwtToken,
config,
optional,
checkSubscriptionExpiration,
moduleKey,
});
if ((_a = config.api) === null || _a === void 0 ? void 0 : _a.default) {
if (req.isApiCall && !((_b = req.body) === null || _b === void 0 ? void 0 : _b.projectId)) {
return res.status(400).json({
error: {
message: 'Missing required parameter: projectId',
},
});
}
data.context = (0, api_1.updateCrowdinContext)(req, data.context);
}
req.crowdinContext = data.context;
if (data.client) {
req.crowdinApiClient = data.client;
}
req.subscriptionInfo = data.subscriptionInfo;
req.logInfo = data.logInfo;
req.logError = data.logError;
next();
}
catch (e) {
const errorMessage = (0, logger_1.getErrorMessage)(e);
if (e instanceof util_1.CodeError) {
return res.status(402).send({ message: errorMessage || 'Error', code: e.code });
}
(0, logger_1.logError)(e);
return res.status(403).send({ error: errorMessage || 'Error' });
}
}));
}
exports.default = handle;
function getToken(req) {
const jwtToken = req.query.jwtToken;
if (jwtToken) {
return jwtToken;
}
if (req.headers.authorization) {
if (req.headers.authorization.startsWith('Bearer ') || req.headers.authorization.startsWith('bearer ')) {
return req.headers.authorization.substring(7);
}
}
}
exports.getToken = getToken;