Skip to content

Commit

Permalink
more ts conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
tsullivan committed Jan 21, 2020
1 parent 8fbd4fb commit d321897
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,4 @@ describe('Cancellation Token', () => {

expect(onCancelled).toBeCalled();
});

it('throws an error when the callback is not a function', () => {
const cancellationToken = new CancellationToken();

expect(() => {
// @ts-ignore
cancellationToken.on('cool!');
}).toThrowError('Expected callback to be a function');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
*/

import { i18n } from '@kbn/i18n';
import { ExecuteJobFactory, ESQueueWorkerExecuteFn, ServerFacade } from '../../../types';
import {
ExecuteJobFactory,
ESQueueWorkerExecuteFn,
FieldFormats,
ServerFacade,
} from '../../../types';
import { CSV_JOB_TYPE, PLUGIN_ID } from '../../../common/constants';
import { cryptoFactory, LevelLogger } from '../../../server/lib';
import { JobDocPayloadDiscoverCsv } from '../types';
Expand Down Expand Up @@ -84,7 +89,7 @@ export const executeJobFactory: ExecuteJobFactory<ESQueueWorkerExecuteFn<

const [formatsMap, uiSettings] = await Promise.all([
(async () => {
const fieldFormats = await server.fieldFormatServiceFactory(uiConfig);
const fieldFormats = (await server.fieldFormatServiceFactory(uiConfig)) as FieldFormats;
return fieldFormatMapFactory(indexPatternSavedObject, fieldFormats);
})(),
(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import _ from 'lodash';
import { FieldFormats } from '../../../../types';

interface IndexPatternSavedObject {
attributes: {
Expand All @@ -15,12 +16,6 @@ interface IndexPatternSavedObject {
version: string;
}

interface FieldFormats {
getConfig: number;
getInstance: (config: any) => any;
getDefaultInstance: (key: string) => any;
}

/**
* Create a map of FieldFormat instances for index pattern fields
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,48 @@
*/

import { get } from 'lodash';
import { ServerFacade, JobSource } from '../../types';

const defaultSize = 10;

export function jobsQueryFactory(server) {
interface QueryBody {
size?: number;
from?: number;
_source?: {
excludes: string[];
};
query: {
constant_score: {
filter: {
bool: {
must: Array<Record<string, any>>;
};
};
};
};
}

interface GetOpts {
includeContent?: boolean;
}

interface CountAggResult {
count: number;
}

export function jobsQueryFactory(server: ServerFacade) {
const index = server.config().get('xpack.reporting.index');
// @ts-ignore `errors` does not exist on type Cluster
const { callWithInternalUser, errors: esErrors } = server.plugins.elasticsearch.getCluster(
'admin'
);

function getUsername(user) {
function getUsername(user: any) {
return get(user, 'username', false);
}

function execQuery(queryType, body) {
const defaultBody = {
function execQuery(queryType: string, body: QueryBody) {
const defaultBody: Record<string, object> = {
search: {
_source: {
excludes: ['output.content'],
Expand All @@ -42,15 +69,17 @@ export function jobsQueryFactory(server) {
});
}

function getHits(query) {
type Result = number;

function getHits(query: Promise<Result>) {
return query.then(res => get(res, 'hits.hits', []));
}

return {
list(jobTypes, user, page = 0, size = defaultSize, jobIds) {
list(jobTypes: string[], user: any, page = 0, size = defaultSize, jobIds: string[] | null) {
const username = getUsername(user);

const body = {
const body: QueryBody = {
size,
from: size * page,
query: {
Expand All @@ -73,10 +102,10 @@ export function jobsQueryFactory(server) {
return getHits(execQuery('search', body));
},

count(jobTypes, user) {
count(jobTypes: string[], user: any) {
const username = getUsername(user);

const body = {
const body: QueryBody = {
query: {
constant_score: {
filter: {
Expand All @@ -88,18 +117,18 @@ export function jobsQueryFactory(server) {
},
};

return execQuery('count', body).then(doc => {
return execQuery('count', body).then((doc: CountAggResult) => {
if (!doc) return 0;
return doc.count;
});
},

get(user, id, opts = {}) {
get(user: any, id: string, opts: GetOpts = {}): Promise<JobSource<unknown> | void> {
if (!id) return Promise.resolve();

const username = getUsername(user);

const body = {
const body: QueryBody = {
query: {
constant_score: {
filter: {
Expand Down
45 changes: 23 additions & 22 deletions x-pack/legacy/plugins/reporting/server/routes/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,19 @@ export function registerJobInfoRoutes(
const { docId } = request.params;

return jobsQuery.get(request.pre.user, docId, { includeContent: true }).then(
({ _source: job }: JobSource<any>): JobDocOutput => {
if (!job) {
(result): JobDocOutput => {
if (!result) {
throw boom.notFound();
}
const {
_source: { jobtype: jobType, output: jobOutput },
} = result;

const { jobtype: jobType } = job;
if (!request.pre.management.jobTypes.includes(jobType)) {
throw boom.unauthorized(`Sorry, you are not authorized to download ${jobType} reports`);
}

return job.output;
return jobOutput;
}
);
},
Expand All @@ -107,26 +109,25 @@ export function registerJobInfoRoutes(
const request = makeRequestFacade(legacyRequest);
const { docId } = request.params;

return jobsQuery
.get(request.pre.user, docId)
.then(({ _source: job }: JobSource<any>): JobSource<any>['_source'] => {
if (!job) {
throw boom.notFound();
}
return jobsQuery.get(request.pre.user, docId).then((result): JobSource<any>['_source'] => {
if (!result) {
throw boom.notFound();
}

const { jobtype: jobType, payload } = job;
if (!request.pre.management.jobTypes.includes(jobType)) {
throw boom.unauthorized(`Sorry, you are not authorized to view ${jobType} info`);
}
const { _source: job } = result;
const { jobtype: jobType, payload: jobPayload } = job;
if (!request.pre.management.jobTypes.includes(jobType)) {
throw boom.unauthorized(`Sorry, you are not authorized to view ${jobType} info`);
}

return {
...job,
payload: {
...payload,
headers: undefined,
},
};
});
return {
...job,
payload: {
...jobPayload,
headers: undefined,
},
};
});
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,33 @@
* you may not use this file except in compliance with the Elastic License.
*/

import boom from 'boom';
import Boom from 'boom';
import { Legacy } from 'kibana';
import { AuthenticatedUser } from '../../../../../../plugins/security/server';
import { getUserFactory } from '../../lib/get_user';
import { ServerFacade } from '../../../types';

const superuserRole = 'superuser';

export const authorizedUserPreRoutingFactory = function authorizedUserPreRoutingFn(server) {
export type PreRoutingFunction = (
request: Legacy.Request
) => Promise<Boom<null> | AuthenticatedUser | null>;

export const authorizedUserPreRoutingFactory = function authorizedUserPreRoutingFn(
server: ServerFacade
) {
const getUser = getUserFactory(server);
const config = server.config();

return async function authorizedUserPreRouting(request) {
return async function authorizedUserPreRouting(request: Legacy.Request) {
const xpackInfo = server.plugins.xpack_main.info;

if (!xpackInfo || !xpackInfo.isAvailable()) {
server.log(
['reporting', 'authorizedUserPreRouting', 'debug'],
'Unable to authorize user before xpack info is available.'
);
return boom.notFound();
return Boom.notFound();
}

const security = xpackInfo.feature('security');
Expand All @@ -32,12 +41,15 @@ export const authorizedUserPreRoutingFactory = function authorizedUserPreRouting
const user = await getUser(request);

if (!user) {
return boom.unauthorized(`Sorry, you aren't authenticated`);
return Boom.unauthorized(`Sorry, you aren't authenticated`);
}

const authorizedRoles = [superuserRole, ...config.get('xpack.reporting.roles.allow')];
const authorizedRoles = [
superuserRole,
...(config.get('xpack.reporting.roles.allow') as string[]),
];
if (!user.roles.find(role => authorizedRoles.includes(role))) {
return boom.forbidden(`Sorry, you don't have access to Reporting`);
return Boom.forbidden(`Sorry, you don't have access to Reporting`);
}

return user;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@
*/

import Boom from 'boom';
import { Legacy } from 'kibana';
import { ServerFacade } from '../../../types';

export const reportingFeaturePreRoutingFactory = function reportingFeaturePreRoutingFn(server) {
export type GetReportingFeatureIdFn = (request: Legacy.Request) => string;

export const reportingFeaturePreRoutingFactory = function reportingFeaturePreRoutingFn(
server: ServerFacade
) {
const xpackMainPlugin = server.plugins.xpack_main;
const pluginId = 'reporting';

// License checking and enable/disable logic
return function reportingFeaturePreRouting(getReportingFeatureId) {
return function licensePreRouting(request) {
return function reportingFeaturePreRouting(getReportingFeatureId: GetReportingFeatureIdFn) {
return function licensePreRouting(request: Legacy.Request) {
const licenseCheckResults = xpackMainPlugin.info.feature(pluginId).getLicenseCheckResults();
const reportingFeatureId = getReportingFeatureId(request);
const reportingFeature = licenseCheckResults[reportingFeatureId];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@

import Joi from 'joi';
import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants';
import { ServerFacade, RequestFacade } from '../../../types';
// @ts-ignore
import { ServerFacade } from '../../../types';
import { authorizedUserPreRoutingFactory } from './authorized_user_pre_routing';
// @ts-ignore
import { reportingFeaturePreRoutingFactory } from './reporting_feature_pre_routing';
import { GetReportingFeatureIdFn } from './reporting_feature_pre_routing';

const API_TAG = 'api';

Expand All @@ -22,19 +21,16 @@ export interface RouteConfigFactory {
};
}

type GetFeatureFunction = (request: RequestFacade) => any;
type PreRoutingFunction = (getFeatureId?: GetFeatureFunction) => any;

export type GetRouteConfigFactoryFn = (
getFeatureId?: GetFeatureFunction | undefined
getFeatureId?: GetReportingFeatureIdFn
) => RouteConfigFactory;

export function getRouteConfigFactoryReportingPre(server: ServerFacade): GetRouteConfigFactoryFn {
const authorizedUserPreRouting: PreRoutingFunction = authorizedUserPreRoutingFactory(server);
const reportingFeaturePreRouting: PreRoutingFunction = reportingFeaturePreRoutingFactory(server);
const authorizedUserPreRouting = authorizedUserPreRoutingFactory(server);
const reportingFeaturePreRouting = reportingFeaturePreRoutingFactory(server);

return (getFeatureId?: GetFeatureFunction): RouteConfigFactory => {
const preRouting = [{ method: authorizedUserPreRouting, assign: 'user' }];
return (getFeatureId?: GetReportingFeatureIdFn): RouteConfigFactory => {
const preRouting: any[] = [{ method: authorizedUserPreRouting, assign: 'user' }];
if (getFeatureId) {
preRouting.push(reportingFeaturePreRouting(getFeatureId));
}
Expand Down
6 changes: 6 additions & 0 deletions x-pack/legacy/plugins/reporting/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,3 +355,9 @@ export interface InterceptedRequest {
frameId: string;
resourceType: string;
}

export interface FieldFormats {
getConfig: number;
getInstance: (config: any) => any;
getDefaultInstance: (key: string) => any;
}

0 comments on commit d321897

Please sign in to comment.