@crowdin/app-project-module
Version:
Module that generates for you all common endpoints for serving standalone Crowdin App
164 lines (163 loc) • 7.68 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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 });
const storage_1 = require("../storage");
const util_1 = require("../util");
const connection_1 = require("../util/connection");
const logger_1 = require("../util/logger");
const crowdinAppFunctions = __importStar(require("@crowdin/crowdin-apps-functions"));
function handle(config, integration, optional = false) {
return (0, util_1.runAsyncWrapper)((req, res, next) => __awaiter(this, void 0, void 0, function* () {
let clientId = req.crowdinContext.clientId;
const isApiCall = req === null || req === void 0 ? void 0 : req.isApiCall;
const { organization, projectId, userId } = crowdinAppFunctions.parseCrowdinId(clientId);
req.logInfo(`Loading integration credentials for client ${clientId}`);
let integrationCredentials = yield (0, storage_1.getStorage)().getIntegrationCredentials(clientId);
const ownerIds = [];
// check if user has access to integration in settings(managers)
if (!integrationCredentials) {
const projectIntegrationCredentials = (yield (0, storage_1.getStorage)().getAllIntegrationCredentials(organization)).filter((item) => {
const { organization: itemOrganization, projectId: itemProjectId } = crowdinAppFunctions.parseCrowdinId(item.id);
return itemOrganization === organization && itemProjectId === projectId;
});
if (projectIntegrationCredentials.length) {
for (const credentials of projectIntegrationCredentials) {
ownerIds.push(crowdinAppFunctions.parseCrowdinId(credentials.id).userId);
if (checkUserAccessToIntegration(credentials, `${userId}`)) {
integrationCredentials = credentials;
clientId = credentials.id;
req.crowdinContext.clientId = clientId;
break;
}
}
}
}
if (!integrationCredentials) {
const owners = yield getIntegrationManagedBy(ownerIds, req);
if (optional && !owners.length) {
return next();
}
const errorOptions = {
code: 403,
message: 'Access denied',
owners: null,
hideActions: false,
};
if (isApiCall) {
return res.status(errorOptions.code).json({
error: {
message: errorOptions.message,
},
});
}
if (owners) {
errorOptions.message = 'Looks like you don’t have access';
errorOptions.hideActions = true;
errorOptions.owners = owners;
}
else {
(0, logger_1.temporaryErrorDebug)('Access denied: integration-credentials', req);
}
return res.render('error', errorOptions);
}
try {
req.integrationCredentials = yield (0, connection_1.prepareIntegrationCredentials)(config, integration, integrationCredentials);
}
catch (e) {
console.error(e);
const message = 'Credentials to integration either expired or invalid';
if (isApiCall) {
return res.status(401).json({
error: {
message,
},
});
}
else {
throw new util_1.CodeError(message, 401);
}
}
const integrationConfig = yield (0, storage_1.getStorage)().getIntegrationConfig(clientId);
if (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.config) {
let integrationSettings = JSON.parse(integrationConfig.config) || {};
if (integration.normalizeSettings) {
integrationSettings = yield integration.normalizeSettings({
appSettings: integrationSettings,
apiCredentials: req.integrationCredentials,
client: req.crowdinApiClient,
});
}
req.integrationSettings = integrationSettings;
}
next();
}));
}
exports.default = handle;
function checkUserAccessToIntegration(integrationCredentials, userId) {
if (integrationCredentials === null || integrationCredentials === void 0 ? void 0 : integrationCredentials.managers) {
const managers = JSON.parse(integrationCredentials.managers);
return (managers || []).includes(userId);
}
return false;
}
function getIntegrationManagedBy(ownerIds, req) {
return __awaiter(this, void 0, void 0, function* () {
if (!ownerIds.length) {
return [];
}
const projectId = crowdinAppFunctions.getProjectId(req.crowdinContext.clientId);
let owners = [];
try {
owners =
ownerIds.length > 1
? (yield req.crowdinApiClient.usersApi.listProjectMembers(projectId)).data.filter((member) => ownerIds.includes(member.data.id))
: [yield req.crowdinApiClient.usersApi.getProjectMemberPermissions(projectId, ownerIds[0])];
}
catch (e) {
console.warn('Failed to get project members', e);
return [];
}
return owners.map((owner) => {
const ownerFullName = 'fullName' in owner.data
? owner.data.fullName
: `${owner.data.firstName || ''} ${owner.data.lastName || ''}`.trim();
return {
id: owner.data.id,
name: !!ownerFullName && owner.data.username !== ownerFullName
? `${ownerFullName} (${owner.data.username})`
: owner.data.username,
};
});
});
}