fix: updated e2e tests

This commit is contained in:
montaghanmy
2023-04-10 11:58:53 +01:00
parent c4b9fba621
commit b26d6b33c1
24 changed files with 3067 additions and 11 deletions
@@ -8,13 +8,7 @@ export type TwakeLogger = pino.Logger;
export const logger = pino({
name: "TwakeApp",
level: config.get("level", "info") || "info",
prettyPrint:
process.env.NODE_ENV?.indexOf("test") > -1
? {
translateTime: "HH:MM:ss Z",
ignore: "pid,hostname,name",
}
: false,
prettyPrint: false,
});
export const getLogger = (name?: string): TwakeLogger =>
@@ -0,0 +1,33 @@
import Application, { TYPE } from "./application";
export default {
index: TYPE,
source: (entity: Application) => {
return {
company_id: entity.company_id,
name: entity.identity.name,
description: entity.identity.description,
categories: entity.identity.categories,
compatibility: entity.identity.compatibility,
published: entity.publication.published,
created_at: entity.stats.created_at,
};
},
mongoMapping: {
text: {
name: "text",
description: "text",
},
},
esMapping: {
properties: {
company_id: { type: "keyword" },
name: { type: "text", index_prefixes: { min_chars: 1 } },
description: { type: "text" },
categories: { type: "keyword" },
compatibility: { type: "keyword" },
published: { type: "boolean" },
created_at: { type: "number" },
},
},
};
@@ -0,0 +1,212 @@
import { Type } from "class-transformer";
import _, { merge } from "lodash";
import { Column, Entity } from "../../../core/platform/services/database/services/orm/decorators";
import search from "./application.search";
export const TYPE = "applications";
@Entity(TYPE, {
primaryKey: ["id"],
type: TYPE,
search,
})
export default class Application {
@Type(() => String)
@Column("id", "timeuuid", { generator: "timeuuid" })
id: string;
@Type(() => String)
@Column("group_id", "timeuuid")
company_id: string;
@Column("is_default", "boolean")
is_default: boolean;
@Column("identity", "json")
identity: ApplicationIdentity;
//This information is private to the application, make sure not to disclose it
@Column("api", "encoded_json")
api: ApplicationApi;
@Column("access", "json")
access: ApplicationAccess;
@Column("display", "json")
display: ApplicationDisplay;
@Column("publication", "json")
publication: ApplicationPublication;
@Column("stats", "json")
stats: ApplicationStatistics;
getPublicObject(): PublicApplicationObject {
const i = _.pick(
this,
"id",
"company_id",
"is_default",
"identity",
"access",
"display",
"publication",
"stats",
);
i.is_default = !!i.is_default;
return i;
}
getApplicationObject(): ApplicationObject {
const i = _.pick(
this,
"id",
"company_id",
"is_default",
"identity",
"access",
"display",
"publication",
"stats",
"api",
);
i.is_default = !!i.is_default;
return i;
}
}
export type PublicApplicationObject = Pick<
Application,
"id" | "company_id" | "is_default" | "identity" | "access" | "display" | "publication" | "stats"
>;
export type ApplicationObject = Pick<
Application,
| "id"
| "company_id"
| "is_default"
| "identity"
| "access"
| "display"
| "publication"
| "stats"
| "api"
>;
export type ApplicationPrimaryKey = { id: string };
export function getInstance(message: Application): Application {
return merge(new Application(), message);
}
export type ApplicationIdentity = {
code: string;
name: string;
icon: string;
description: string;
website: string;
categories: string[];
compatibility: "twake"[];
repository?: string;
};
export type ApplicationPublication = {
published: boolean; //Publication accepted // RO
requested: boolean; //Publication requested
};
export type ApplicationStatistics = {
created_at: number; // RO
updated_at: number; // RO
version: number; // RO
};
export type ApplicationApi = {
hooks_url: string;
allowed_ips: string;
private_key: string; // RO
};
type ApplicationScopes =
| "files"
| "applications"
| "workspaces"
| "users"
| "messages"
| "channels";
export type ApplicationAccess = {
read: ApplicationScopes[];
write: ApplicationScopes[];
delete: ApplicationScopes[];
hooks: ApplicationScopes[];
};
export type ApplicationDisplay = {
twake: {
files?: {
editor?: {
preview_url: string; //Open a preview inline (iframe)
edition_url: string; //Url to edit the file (full screen)
extensions?: string[]; //Main extensions app can read
// if file was created by the app, then the app is able to edit with or without extension
empty_files?: {
url: string; // "https://[...]/empty.docx";
filename: string; // "Untitled.docx";
name: string; // "Word Document";
}[];
};
actions?: //List of action that can apply on a file
{
name: string;
id: string;
}[];
};
//Chat plugin
chat?: {
input?:
| true
| {
icon?: string; //If defined replace original icon url of your app
type?: "file" | "call"; //To add in existing apps folder / default icon
};
commands?: {
command: string; // my_app mycommand
description: string;
}[];
actions?: //List of action that can apply on a message
{
name: string;
id: string;
}[];
};
//Allow app to appear as a bot user in direct chat
direct?:
| true
| {
name?: string;
icon?: string; //If defined replace original icon url of your app
};
//Display app as a standalone application in a tab
tab?:
| {
url: string;
}
| true;
//Display app as a standalone application on the left bar
standalone?:
| {
url: string;
}
| true;
//Define where the app can be configured from
configuration?: ("global" | "channel")[];
};
};
@@ -0,0 +1,40 @@
import { Type } from "class-transformer";
import { Column, Entity } from "../../../core/platform/services/database/services/orm/decorators";
import { PublicApplicationObject } from "./application";
export const TYPE = "group_app";
@Entity(TYPE, {
primaryKey: [["group_id"], "app_id", "id"],
type: TYPE,
})
export default class CompanyApplication {
@Type(() => String)
@Column("group_id", "timeuuid")
company_id: string;
@Type(() => String)
@Column("app_id", "timeuuid")
application_id: string;
@Type(() => String)
@Column("id", "timeuuid", { generator: "timeuuid" })
id: string;
@Column("created_at", "number")
created_at: number;
@Type(() => String)
@Column("created_by", "string")
created_by: string; //Will be the default delegated user when doing actions on Twake
}
export type CompanyApplicationPrimaryKey = Pick<
CompanyApplication,
"company_id" | "application_id" | "id"
>;
export class CompanyApplicationWithApplication extends CompanyApplication {
//Not in database but attached to this object
application?: PublicApplicationObject;
}
@@ -0,0 +1,24 @@
import { Prefix, TwakeService } from "../../core/platform/framework";
import WebServerAPI from "../../core/platform/services/webserver/provider";
import web from "./web";
@Prefix("/internal/services/applications/v1")
export default class ApplicationsService extends TwakeService<undefined> {
version = "1";
name = "applications";
public async doInit(): Promise<this> {
const fastify = this.context.getProvider<WebServerAPI>("webserver").getServer();
fastify.register((instance, _opts, next) => {
web(instance, { prefix: this.prefix });
next();
});
return this;
}
// TODO: remove
api(): undefined {
return undefined;
}
}
@@ -0,0 +1,13 @@
import { WebsocketMetadata } from "../../utils/types";
export function getCompanyApplicationRooms(companyId: string): WebsocketMetadata[] {
return [
{
room: getCompanyApplicationRoom(companyId),
},
];
}
export function getCompanyApplicationRoom(companyApplicationId: string): string {
return `/company-application/${companyApplicationId}`;
}
@@ -0,0 +1,143 @@
import Application, {
ApplicationPrimaryKey,
getInstance as getApplicationInstance,
PublicApplicationObject,
TYPE,
} from "../entities/application";
import Repository from "../../../core/platform/services/database/services/orm/repository/repository";
import { Initializable, logger, TwakeServiceProvider } from "../../../core/platform/framework";
import {
DeleteResult,
ExecutionContext,
ListResult,
OperationType,
Pagination,
SaveResult,
} from "../../../core/platform/framework/api/crud-service";
import SearchRepository from "../../../core/platform/services/search/repository";
import assert from "assert";
import gr from "../../global-resolver";
import { InternalToHooksProcessor } from "./internal-event-to-hooks";
export class ApplicationServiceImpl implements TwakeServiceProvider, Initializable {
version: "1";
repository: Repository<Application>;
searchRepository: SearchRepository<Application>;
async init(): Promise<this> {
try {
this.searchRepository = gr.platformServices.search.getRepository<Application>(
TYPE,
Application,
);
this.repository = await gr.database.getRepository<Application>(TYPE, Application);
} catch (err) {
console.log(err);
logger.error("Error while initializing applications service");
}
gr.platformServices.messageQueue.processor.addHandler(new InternalToHooksProcessor());
return this;
}
async get(pk: ApplicationPrimaryKey, context: ExecutionContext): Promise<Application> {
return await this.repository.findOne(pk, {}, context);
}
async list(
pagination: Pagination,
options?: { search?: string },
context?: ExecutionContext,
): Promise<ListResult<PublicApplicationObject>> {
let entities: ListResult<Application>;
if (options.search) {
entities = await this.searchRepository.search(
{},
{
pagination,
$text: {
$search: options.search,
},
},
context,
);
} else {
entities = await this.repository.find({}, { pagination }, context);
}
entities.filterEntities(app => app.publication.published);
const applications = entities
.getEntities()
.filter(app => app)
.map(app => app.getPublicObject());
return new ListResult(entities.type, applications, entities.nextPage);
}
async listUnpublished(context: ExecutionContext): Promise<Application[]> {
const entities = await this.repository.find({}, {}, context);
entities.filterEntities(app => !app.publication.published);
return entities.getEntities();
}
async listDefaults(context: ExecutionContext): Promise<ListResult<PublicApplicationObject>> {
const entities = [];
let page: Pagination = { limitStr: "100" };
do {
const applicationListResult = await this.repository.find({}, { pagination: page }, context);
page = applicationListResult.nextPage as Pagination;
applicationListResult.filterEntities(app => app.publication.published && app.is_default);
for (const application of applicationListResult.getEntities()) {
if (application) entities.push(application.getPublicObject());
}
} while (page.page_token);
return new ListResult(TYPE, entities);
}
async save<SaveOptions>(
item: Application,
options?: SaveOptions,
context?: ExecutionContext,
): Promise<SaveResult<Application>> {
assert(item.company_id, "company_id is not defined");
try {
const entity = getApplicationInstance(item);
await this.repository.save(entity, context);
return new SaveResult<Application>("application", entity, OperationType.UPDATE);
} catch (e) {
throw e;
}
}
async delete(
pk: ApplicationPrimaryKey,
context?: ExecutionContext,
): Promise<DeleteResult<Application>> {
const entity = await this.get(pk, context);
await this.repository.remove(entity, context);
return new DeleteResult<Application>("application", entity, true);
}
async publish(pk: ApplicationPrimaryKey, context: ExecutionContext): Promise<void> {
const entity = await this.get(pk, context);
if (!entity) {
throw new Error("Entity not found");
}
entity.publication.published = true;
await this.repository.save(entity, context);
}
async unpublish(pk: ApplicationPrimaryKey, context: ExecutionContext): Promise<void> {
const entity = await this.get(pk, context);
if (!entity) {
throw new Error("Entity not found");
}
entity.publication.published = false;
await this.repository.save(entity, context);
}
}
@@ -0,0 +1,188 @@
import CompanyApplication, {
CompanyApplicationPrimaryKey,
CompanyApplicationWithApplication,
TYPE,
} from "../entities/company-application";
import Repository from "../../../core/platform/services/database/services/orm/repository/repository";
import {
Initializable,
logger,
RealtimeDeleted,
RealtimeSaved,
TwakeServiceProvider,
} from "../../../core/platform/framework";
import {
DeleteResult,
ListResult,
OperationType,
Paginable,
Pagination,
SaveResult,
} from "../../../core/platform/framework/api/crud-service";
import { CompanyExecutionContext } from "../web/types";
import { getCompanyApplicationRoom } from "../realtime";
import gr from "../../global-resolver";
export class CompanyApplicationServiceImpl implements TwakeServiceProvider, Initializable {
version: "1";
repository: Repository<CompanyApplication>;
async init(): Promise<this> {
try {
this.repository = await gr.database.getRepository<CompanyApplication>(
TYPE,
CompanyApplication,
);
} catch (err) {
console.log(err);
logger.error("Error while initializing applications service");
}
return this;
}
// TODO: remove logic from context
async get(
pk: Pick<CompanyApplicationPrimaryKey, "company_id" | "application_id"> & { id?: string },
context?: CompanyExecutionContext,
): Promise<CompanyApplicationWithApplication> {
const companyApplication = await this.repository.findOne(
{
group_id: context ? context.company.id : pk.company_id,
app_id: pk.application_id,
},
{},
context,
);
const application = await gr.services.applications.marketplaceApps.get(
{
id: pk.application_id,
},
context,
);
return {
...companyApplication,
application: application,
};
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@RealtimeSaved<CompanyApplication>((companyApplication, _context) => {
return [
{
room: getCompanyApplicationRoom(companyApplication.id),
resource: companyApplication,
},
];
})
async save<SaveOptions>(
item: Pick<CompanyApplicationPrimaryKey, "company_id" | "application_id">,
_?: SaveOptions,
context?: CompanyExecutionContext,
): Promise<SaveResult<CompanyApplication>> {
if (!context?.user?.id && !context?.user?.server_request) {
throw new Error("Only an user of a company can add an application to a company.");
}
let operation = OperationType.UPDATE;
let companyApplication = await this.repository.findOne(
{
group_id: context?.company.id,
app_id: item.application_id,
},
{},
context,
);
if (!companyApplication) {
operation = OperationType.CREATE;
companyApplication = new CompanyApplication();
companyApplication.company_id = context.company.id;
companyApplication.application_id = item.application_id;
companyApplication.created_at = new Date().getTime();
companyApplication.created_by = context?.user?.id || "";
await this.repository.save(companyApplication, context);
}
return new SaveResult(TYPE, companyApplication, operation);
}
async initWithDefaultApplications(
companyId: string,
context: CompanyExecutionContext,
): Promise<void> {
const defaultApps = await gr.services.applications.marketplaceApps.listDefaults(context);
for (const defaultApp of defaultApps.getEntities()) {
await this.save({ company_id: companyId, application_id: defaultApp.id }, {}, context);
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@RealtimeDeleted<CompanyApplication>((companyApplication, _context) => {
return [
{
room: getCompanyApplicationRoom(companyApplication.id),
resource: companyApplication,
},
];
})
async delete(
pk: CompanyApplicationPrimaryKey,
context?: CompanyExecutionContext,
): Promise<DeleteResult<CompanyApplication>> {
const companyApplication = await this.repository.findOne(
{
group_id: context.company.id,
app_id: pk.application_id,
},
{},
context,
);
let deleted = false;
if (companyApplication) {
this.repository.remove(companyApplication, context);
deleted = true;
}
return new DeleteResult(TYPE, companyApplication, deleted);
}
async list<ListOptions>(
pagination: Paginable,
options?: ListOptions,
context?: CompanyExecutionContext,
): Promise<ListResult<CompanyApplicationWithApplication>> {
const companyApplications = await this.repository.find(
{
group_id: context.company.id,
},
{ pagination: Pagination.fromPaginable(pagination) },
context,
);
const applications = [];
for (const companyApplication of companyApplications.getEntities()) {
const application = await gr.services.applications.marketplaceApps.get(
{
id: companyApplication.application_id,
},
context,
);
if (application)
applications.push({
...companyApplication,
application: application,
});
}
return new ListResult<CompanyApplicationWithApplication>(
TYPE,
applications,
companyApplications.nextPage,
);
}
}
@@ -0,0 +1,96 @@
import Application from "../entities/application";
import Repository from "../../../core/platform/services/database/services/orm/repository/repository";
import {
Initializable,
logger as log,
TwakeServiceProvider,
} from "../../../core/platform/framework";
import { CrudException, ExecutionContext } from "../../../core/platform/framework/api/crud-service";
import SearchRepository from "../../../core/platform/services/search/repository";
import axios from "axios";
import * as crypto from "crypto";
import { isObject } from "lodash";
import gr from "../../global-resolver";
export class ApplicationHooksService implements TwakeServiceProvider, Initializable {
version: "1";
repository: Repository<Application>;
searchRepository: SearchRepository<Application>;
async init() {
return this;
}
async notifyApp(
application_id: string,
connection_id: string,
user_id: string,
type: string,
name: string,
content: any,
company_id: string,
workspace_id: string,
context: ExecutionContext,
): Promise<void> {
const app = await gr.services.applications.marketplaceApps.get({ id: application_id }, context);
if (!app) {
throw CrudException.notFound("Application not found");
}
if (!app.api.hooks_url) {
throw CrudException.badRequest("Application hooks_url is not defined");
}
const payload = {
type,
name,
content,
connection_id: connection_id,
user_id: user_id,
company_id,
workspace_id,
};
const signature = crypto
.createHmac("sha256", app.api.private_key)
.update(JSON.stringify(payload))
.digest("hex");
return await axios
.post(app.api.hooks_url, payload, {
headers: {
"Content-Type": "application/json",
"X-Twake-Signature": signature,
},
})
.then(({ data }) => data)
.catch(e => {
log.error(e.message);
const r = e.response;
if (!r) {
throw CrudException.badGateway("Can't connect remote application");
}
let msg = r.data;
if (isObject(msg)) {
// parse typical responses
if (r.data.message) {
msg = r.data.message;
} else if (r.data.error) {
msg = r.data.error;
} else {
msg = JSON.stringify(r.data);
}
}
if (r.status == 403) {
throw CrudException.forbidden(msg);
} else {
throw CrudException.badRequest(msg);
}
});
}
}
@@ -0,0 +1,64 @@
import { logger } from "../../../core/platform/framework";
import { HookType } from "../../applications-api/types";
import { MessageQueueHandler } from "../../../core/platform/services/message-queue/api";
import { MessageHook } from "../../messages/types";
import gr from "../../global-resolver";
import { ExecutionContext } from "../../../core/platform/framework/api/crud-service";
export class InternalToHooksProcessor implements MessageQueueHandler<MessageHook, void> {
readonly topics = {
in: "application:hook:message",
};
readonly options = {
unique: true,
ack: true,
queue: "application:hook:message:consumer1",
};
readonly name = "Application::InternalToHooksProcessor";
validate(_: HookType): boolean {
return true;
}
async process(message: HookType, context?: ExecutionContext): Promise<void> {
logger.debug(`${this.name} - Receive hook of type ${message.type}`);
const application = await gr.services.applications.marketplaceApps.get(
{
id: message.application_id,
},
context,
);
//TODO Check application access rights (hooks)
const _access = application.access;
// Check application still exists in the company
if (
!(await gr.services.applications.companyApps.get({
company_id: message.company_id,
application_id: message.application_id,
id: undefined,
}))
) {
logger.error(
`${this.name} - Application ${message.application_id} not found in company ${message.company_id}`,
);
return;
}
await gr.services.applications.hooks.notifyApp(
message.application_id,
null,
null,
"hook",
null,
{ message },
null,
null,
context,
);
}
}
@@ -0,0 +1,296 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { CrudController } from "../../../../core/platform/services/webserver/types";
import {
PaginationQueryParameters,
ResourceCreateResponse,
ResourceDeleteResponse,
ResourceGetResponse,
ResourceListResponse,
ResourceUpdateResponse,
} from "../../../../utils/types";
import Application, {
ApplicationObject,
PublicApplicationObject,
} from "../../entities/application";
import {
CrudException,
ExecutionContext,
Pagination,
} from "../../../../core/platform/framework/api/crud-service";
import _ from "lodash";
import { randomBytes } from "crypto";
import { ApplicationEventRequestBody } from "../types";
import { logger as log } from "../../../../core/platform/framework";
import { hasCompanyAdminLevel } from "../../../../utils/company";
import gr from "../../../global-resolver";
import config from "../../../../core/config";
import axios from "axios";
export class ApplicationController
implements
CrudController<
ResourceGetResponse<PublicApplicationObject>,
ResourceUpdateResponse<PublicApplicationObject>,
ResourceListResponse<PublicApplicationObject>,
ResourceDeleteResponse
>
{
async get(
request: FastifyRequest<{ Params: { application_id: string } }>,
): Promise<ResourceGetResponse<ApplicationObject | PublicApplicationObject>> {
const context = getExecutionContext(request);
const entity = await gr.services.applications.marketplaceApps.get(
{
id: request.params.application_id,
},
context,
);
const companyUser = await gr.services.companies.getCompanyUser(
{ id: entity.company_id },
{ id: context.user.id },
);
const isAdmin = companyUser && companyUser.role == "admin";
return {
resource: isAdmin ? entity.getApplicationObject() : entity.getPublicObject(),
};
}
async list(
request: FastifyRequest<{
Querystring: PaginationQueryParameters & { search: string };
}>,
): Promise<ResourceListResponse<PublicApplicationObject>> {
const entities = await gr.services.applications.marketplaceApps.list(new Pagination(), {
search: request.query.search,
});
return {
resources: entities.getEntities(),
next_page_token: entities.nextPage.page_token,
};
}
async save(
request: FastifyRequest<{
Params: { application_id: string };
Body: { resource: Application };
}>,
_reply: FastifyReply,
): Promise<ResourceGetResponse<ApplicationObject | PublicApplicationObject>> {
const context = getExecutionContext(request);
try {
const app = request.body.resource;
const now = new Date().getTime();
const pluginsEndpoint = config.get("plugins.api");
let entity: Application;
if (request.params.application_id) {
entity = await gr.services.applications.marketplaceApps.get(
{
id: request.params.application_id,
},
context,
);
if (!entity) {
throw CrudException.notFound("Application not found");
}
entity.publication.requested = app.publication.requested;
if (app.publication.requested === false) {
entity.publication.published = false;
}
if (entity.publication.published) {
if (
!_.isEqual(
_.pick(entity, "identity", "api", "access", "display"),
_.pick(app, "identity", "api", "access", "display"),
)
) {
throw CrudException.badRequest(
"You can't update applications details while it published",
);
}
}
entity.identity = app.identity;
entity.api.hooks_url = app.api.hooks_url;
entity.api.allowed_ips = app.api.allowed_ips;
entity.access = app.access;
entity.display = app.display;
entity.stats.updated_at = now;
entity.stats.version++;
const res = await gr.services.applications.marketplaceApps.save(entity);
entity = res.entity;
} else {
// INSERT
app.is_default = false;
app.publication.published = false;
app.api.private_key = randomBytes(32).toString("base64");
app.stats = {
created_at: now,
updated_at: now,
version: 0,
};
const res = await gr.services.applications.marketplaceApps.save(app);
entity = res.entity;
}
// SYNC PLUGINS
if (app.identity.repository) {
try {
axios
.post(
`${pluginsEndpoint}/add`,
{
gitRepo: app.identity.repository,
pluginId: entity.getApplicationObject().id,
pluginSecret: entity.getApplicationObject().api.private_key,
},
{
headers: {
"Content-Type": "application/json",
},
},
)
.then(response => {
log.info(response.data);
})
.catch(error => {
log.error(error);
});
} catch (error) {
console.error(error);
}
}
return {
resource: entity.getApplicationObject(),
};
} catch (e) {
log.error(e);
throw e;
}
}
async delete(
request: FastifyRequest<{ Params: { application_id: string } }>,
reply: FastifyReply,
): Promise<ResourceDeleteResponse> {
const context = getExecutionContext(request);
const application = await gr.services.applications.marketplaceApps.get(
{
id: request.params.application_id,
},
context,
);
const compUser = await gr.services.companies.getCompanyUser(
{ id: application.company_id },
{ id: context.user.id },
);
if (!compUser || !hasCompanyAdminLevel(compUser.role)) {
throw CrudException.forbidden("You don't have the rights to delete this application");
}
const deleteResult = await gr.services.applications.marketplaceApps.delete(
{
id: request.params.application_id,
},
context,
);
if (deleteResult.deleted) {
reply.code(204);
return {
status: "success",
};
}
return {
status: "error",
};
}
async event(
request: FastifyRequest<{
Body: ApplicationEventRequestBody;
Params: { application_id: string };
}>,
_reply: FastifyReply,
): Promise<ResourceCreateResponse<any>> {
const context = getExecutionContext(request);
const content = request.body.data;
const applicationEntity = await gr.services.applications.marketplaceApps.get(
{
id: request.params.application_id,
},
context,
);
if (!applicationEntity) {
throw CrudException.notFound("Application not found");
}
const companyUser = gr.services.companies.getCompanyUser(
{ id: request.body.company_id },
{ id: context.user.id },
);
if (!companyUser) {
throw CrudException.badRequest(
"You cannot send event to an application from another company",
);
}
const applicationInCompany = await gr.services.applications.companyApps.get({
company_id: request.body.company_id,
application_id: request.params.application_id,
id: undefined,
});
if (!applicationInCompany) {
throw CrudException.badRequest("Application isn't installed in this company");
}
const hookResponse = await gr.services.applications.hooks.notifyApp(
request.params.application_id,
request.body.connection_id,
context.user.id,
request.body.type,
request.body.name,
content,
request.body.company_id,
request.body.workspace_id,
context,
);
return {
resource: hookResponse,
};
}
}
function getExecutionContext(request: FastifyRequest): ExecutionContext {
return {
user: request.currentUser,
url: request.url,
method: request.routerMethod,
transport: "http",
};
}
@@ -0,0 +1,119 @@
import { FastifyReply, FastifyRequest } from "fastify";
import {
PaginationQueryParameters,
ResourceDeleteResponse,
ResourceGetResponse,
ResourceListResponse,
ResourceUpdateResponse,
} from "../../../../utils/types";
import { PublicApplicationObject } from "../../entities/application";
import { CompanyExecutionContext } from "../types";
import { CrudController } from "../../../../core/platform/services/webserver/types";
import { getCompanyApplicationRooms } from "../../realtime";
import gr from "../../../global-resolver";
export class CompanyApplicationController
implements
CrudController<
ResourceGetResponse<PublicApplicationObject>,
ResourceUpdateResponse<PublicApplicationObject>,
ResourceListResponse<PublicApplicationObject>,
ResourceDeleteResponse
>
{
async get(
request: FastifyRequest<{ Params: { company_id: string; application_id: string } }>,
): Promise<ResourceGetResponse<PublicApplicationObject>> {
const context = getCompanyExecutionContext(request);
const resource = await gr.services.applications.companyApps.get(
{
application_id: request.params.application_id,
company_id: context.company.id,
id: undefined,
},
context,
);
return {
resource: resource?.application,
};
}
async list(
request: FastifyRequest<{
Params: { company_id: string };
Querystring: PaginationQueryParameters & { search: string };
}>,
): Promise<ResourceListResponse<PublicApplicationObject>> {
const context = getCompanyExecutionContext(request);
const resources = await gr.services.applications.companyApps.list(
request.query,
{ search: request.query.search },
context,
);
return {
resources: resources.getEntities().map(ca => ca.application),
next_page_token: resources.nextPage.page_token,
websockets:
gr.platformServices.realtime.sign(
getCompanyApplicationRooms(request.params.company_id),
context.user.id,
) || [],
};
}
async save(
request: FastifyRequest<{
Params: { company_id: string; application_id: string };
Body: PublicApplicationObject;
}>,
): Promise<ResourceGetResponse<PublicApplicationObject>> {
const context = getCompanyExecutionContext(request);
const resource = await gr.services.applications.companyApps.save(
{ application_id: request.params.application_id, company_id: context.company.id },
{},
context,
);
const app = await gr.services.applications.companyApps.get(resource.entity);
return {
resource: app.application,
};
}
async delete(
request: FastifyRequest<{ Params: { company_id: string; application_id: string } }>,
_reply: FastifyReply,
): Promise<ResourceDeleteResponse> {
const context = getCompanyExecutionContext(request);
const resource = await gr.services.applications.companyApps.delete(
{
application_id: request.params.application_id,
company_id: context.company.id,
id: undefined,
},
context,
);
return {
status: resource.deleted ? "success" : "error",
};
}
}
function getCompanyExecutionContext(
request: FastifyRequest<{
Params: { company_id: string };
}>,
): CompanyExecutionContext {
return {
user: request.currentUser,
company: { id: request.params.company_id },
url: request.url,
method: request.routerMethod,
reqId: request.id,
transport: "http",
};
}
@@ -0,0 +1 @@
export * from "./applications";
@@ -0,0 +1,12 @@
import { FastifyInstance, FastifyRegisterOptions } from "fastify";
import routes from "./routes";
export default (
fastify: FastifyInstance,
options: FastifyRegisterOptions<{
prefix: string;
}>,
): void => {
fastify.log.debug("Configuring /internal/services/applications/v1 routes");
fastify.register(routes, options);
};
@@ -0,0 +1,161 @@
import { FastifyInstance, FastifyPluginCallback, FastifyRequest } from "fastify";
import { ApplicationController } from "./controllers/applications";
import { CompanyApplicationController } from "./controllers/company-applications";
import Application from "../entities/application";
import { applicationEventHookSchema, applicationPostSchema } from "./schemas";
import { logger as log } from "../../../core/platform/framework";
import { checkUserBelongsToCompany, hasCompanyAdminLevel } from "../../../utils/company";
import gr from "../../global-resolver";
const applicationsUrl = "/applications";
const companyApplicationsUrl = "/companies/:company_id/applications";
const routes: FastifyPluginCallback = (fastify: FastifyInstance, options, next) => {
const applicationController = new ApplicationController();
const companyApplicationController = new CompanyApplicationController();
const adminCheck = async (
request: FastifyRequest<{
Body: { resource: Application };
Params: { application_id: string };
}>,
) => {
try {
let companyId: string = request.body?.resource?.company_id;
if (request.params.application_id) {
const application = await gr.services.applications.marketplaceApps.get(
{
id: request.params.application_id,
},
undefined,
);
if (!application) {
throw fastify.httpErrors.notFound("Application is not defined");
}
companyId = application.company_id;
}
const userId = request.currentUser.id;
if (!companyId) {
throw fastify.httpErrors.forbidden(`Company ${companyId} not found`);
}
const companyUser = await checkUserBelongsToCompany(userId, companyId);
if (!hasCompanyAdminLevel(companyUser.role)) {
throw fastify.httpErrors.forbidden("You must be an admin of this company");
}
} catch (e) {
log.error(e);
throw e;
}
};
/**
* Applications collection
* Marketplace of applications
*/
//Get and search list of applications in the marketplace
fastify.route({
method: "GET",
url: `${applicationsUrl}`,
preValidation: [fastify.authenticate],
// schema: applicationGetSchema,
handler: applicationController.list.bind(applicationController),
});
//Get a single application in the marketplace
fastify.route({
method: "GET",
url: `${applicationsUrl}/:application_id`,
preValidation: [fastify.authenticate],
// schema: applicationGetSchema,
handler: applicationController.get.bind(applicationController),
});
//Create application (must be my company application and I must be company admin)
fastify.route({
method: "POST",
url: `${applicationsUrl}`,
preHandler: [adminCheck],
preValidation: [fastify.authenticate],
schema: applicationPostSchema,
handler: applicationController.save.bind(applicationController),
});
//Edit application (must be my company application and I must be company admin)
fastify.route({
method: "POST",
url: `${applicationsUrl}/:application_id`,
preHandler: [adminCheck],
preValidation: [fastify.authenticate],
schema: applicationPostSchema,
handler: applicationController.save.bind(applicationController),
});
// Delete application (must be my company application and I must be company admin)
fastify.route({
method: "DELETE",
url: `${applicationsUrl}/:application_id`,
preHandler: [adminCheck],
preValidation: [fastify.authenticate],
handler: applicationController.delete.bind(applicationController),
});
/**
* Company applications collection
* Company-wide available applications
* (must be my company application and I must be company admin)
*/
//Get list of applications for a company
fastify.route({
method: "GET",
url: `${companyApplicationsUrl}`,
preValidation: [fastify.authenticate],
handler: companyApplicationController.list.bind(companyApplicationController),
});
//Get one application of a company
fastify.route({
method: "GET",
url: `${companyApplicationsUrl}/:application_id`,
preValidation: [fastify.authenticate],
handler: companyApplicationController.get.bind(companyApplicationController),
});
//Remove an application from a company
fastify.route({
method: "DELETE",
url: `${companyApplicationsUrl}/:application_id`,
preValidation: [fastify.authenticate],
handler: companyApplicationController.delete.bind(companyApplicationController),
});
//Add an application to the company
fastify.route({
method: "POST",
url: `${companyApplicationsUrl}/:application_id`,
preValidation: [fastify.authenticate],
handler: companyApplicationController.save.bind(companyApplicationController),
});
//Application event triggered by a user
fastify.route({
method: "POST",
url: `${applicationsUrl}/:application_id/event`,
preValidation: [fastify.authenticate],
schema: applicationEventHookSchema,
handler: applicationController.event.bind(applicationController),
});
next();
};
export default routes;
@@ -0,0 +1,129 @@
export const applicationsSchema = {
type: "object",
properties: {},
};
const applicationIdentity = {
type: "object",
properties: {
code: { type: "string" },
name: { type: "string" },
icon: { type: "string" },
description: { type: "string" },
website: { type: "string" },
categories: { type: "array", items: { type: "string" } },
compatibility: { type: "array", items: { type: "string" } },
},
required: ["code", "name", "icon", "description", "website", "categories", "compatibility"],
};
const applicationAccess = {
type: "object",
properties: {
read: { type: "array", items: { type: "string" } },
write: { type: "array", items: { type: "string" } },
delete: { type: "array", items: { type: "string" } },
hooks: { type: "array", items: { type: "string" } },
},
required: ["read", "write", "delete", "hooks"],
};
const requestApplicationPublication = {
type: "object",
properties: {
requested: { type: "boolean" },
},
required: ["requested"],
};
const responseApplicationPublication = {
type: "object",
properties: {
published: { type: "boolean" },
requested: { type: "boolean" },
},
required: ["requested", "published"],
};
const applicationStats = {
type: "object",
properties: {
created_at: { type: "number" },
updated_at: { type: "number" },
version: { type: "number" },
},
required: ["created_at", "updated_at", "version"],
};
const apiObject = {
type: "object",
properties: {
hooks_url: { type: "string" },
allowed_ips: { type: "string" },
private_key: { type: "string" },
},
required: ["hooks_url", "allowed_ips"],
};
const requestApplicationObject = {
type: "object",
properties: {
company_id: { type: "string" },
identity: applicationIdentity,
access: applicationAccess,
display: {},
api: apiObject,
publication: requestApplicationPublication,
},
required: ["company_id", "identity", "access", "display", "api", "publication"],
additionalProperties: false,
};
const responseApplicationObject = {
type: "object",
properties: {
id: { type: "string" },
is_default: { type: "boolean" },
company_id: { type: "string" },
identity: applicationIdentity,
access: applicationAccess,
display: {},
publication: responseApplicationPublication,
api: apiObject,
stats: applicationStats,
},
required: [
"id",
"is_default",
"company_id",
"identity",
"access",
"display",
"publication",
"stats",
],
additionalProperties: false,
};
export const applicationPostSchema = {
body: { type: "object", properties: { resource: requestApplicationObject } },
response: {
"2xx": {
resource: responseApplicationObject,
},
},
};
export const applicationEventHookSchema = {
body: {
type: "object",
properties: {
company_id: { type: "string" },
workspace_id: { type: "string" },
type: { type: "string" },
name: { type: "string" },
content: {},
},
required: ["company_id", "workspace_id", "type", "content"],
},
};
@@ -0,0 +1,15 @@
import { ExecutionContext } from "../../../core/platform/framework/api/crud-service";
export interface CompanyExecutionContext extends ExecutionContext {
company: { id: string };
}
export interface ApplicationEventRequestBody {
company_id: string;
workspace_id: string;
connection_id: string;
type: string;
name?: string;
content: any;
data: any;
}