aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/FileRouter.ts34
-rw-r--r--src/app.ts18
-rw-r--r--src/logger.ts61
-rw-r--r--src/matcher/options.ts1
-rw-r--r--test/integration/protocol.routes.test.ts315
5 files changed, 240 insertions, 189 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index ff0e65d..4e32fb3 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -65,6 +65,7 @@ const getProtocols: Middleware = (
const postLog: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
+ res.locals.modified = true;
logger.debug('Adding forwarded log');
if (!req.user.hasPrivilege('logging')) {
next(new RequestError(401, 'invalid_privilege'));
@@ -108,9 +109,15 @@ const getLog: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Fetching log');
+ res.locals.modified = true;
if (!req.user.hasPrivilege('admin')) {
next(new RequestError(401, 'invalid_privilege'));
}
+ /* tslint:disable */
+ if(!req.params.level) req.params.level = 'info';
+ if(!req.params.before) req.params.before = new Date();
+ if(!req.params.after) req.params.after = new Date(0);
+ /* tslint:enable */
res.locals.data = logger.fetch(
req.params.level, {
before: new Date(req.params.before),
@@ -165,6 +172,7 @@ const postProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Editing server properties');
+ res.locals.modified = true;
for (const newProp of req.body) {
const prop: Property | undefined = serverConfig.find(
(p: Property): boolean => p.id === newProp.id
@@ -257,6 +265,7 @@ const getUserProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Listing additional properties for a user');
+ res.locals.modified = true;
if (res.locals.user == null) {
next(new RequestError(404, 'user_not_found'));
return;
@@ -289,6 +298,7 @@ const getUsername: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug(`Listing user ${res.locals.user}`);
+ res.locals.modified = true;
if (res.locals.user == null) {
next(new RequestError(404, 'user_not_found'));
return;
@@ -327,6 +337,7 @@ const postCurUser: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Editing current user');
+ res.locals.modified = true;
try {
await req.user.updateInfo(req.body);
await req.user.save();
@@ -357,14 +368,15 @@ const postUsername: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
let user: User | null | undefined = res.locals.user;
+ res.locals.modified = true;
if (user == null) {
- console.log('Adding new user');
+ logger.debug('Adding new user');
user = new User({
username: req.params.username,
password: req.params.password
});
} else {
- console.log('Editing user');
+ logger.debug('Editing user');
user.password = req.params.password;
}
if (req.body) {
@@ -387,6 +399,7 @@ const postUsername: Middleware = async(
const getProjectRoles: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
+ res.locals.modified = true;
logger.debug('Listing available project roles');
const roles: ContributorGroup[] = await ContributorGroup.findAll();
res.locals.data = roles.filter(
@@ -418,6 +431,7 @@ const getProjects: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Listing all projects');
+ res.locals.modified = true;
const projects: Project[] = await Project.findAll({
include: [
User
@@ -425,7 +439,7 @@ const getProjects: Middleware = async(
});
res.locals.data = projects.map(
(p: Project): ProjectFullInfo => p.fullInfo
- );
+ );
next();
};
@@ -450,6 +464,7 @@ const getProjectName: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Getting project properties');
+ res.locals.modified = true;
const project: Project | null = res.locals.project;
if (project == null) {
return next(new RequestError(404, 'project_not_found'));
@@ -476,6 +491,7 @@ const postProjectName: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
let project: Project | null = res.locals.project;
+ res.locals.modified = true;
let promise: PromiseLike<File> | null = null;
if (project == null) {
logger.debug('Adding new project');
@@ -505,6 +521,7 @@ const getProjectProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Getting project properties');
+ res.locals.modified = true;
if (res.locals.project == null) {
next(new RequestError(404, 'project_not_found'));
} else {
@@ -520,6 +537,7 @@ const getFile: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug(`Getting file in ${req.query.view} view`);
+ res.locals.modified = true;
const file: File | null = res.locals.file;
if (file == null) {
return next(new RequestError(404, 'file_not_found'));
@@ -547,7 +565,8 @@ const getFileId: Middleware = getFile;
const postFilePath: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
- logger.debug('Receiving file to ' + res.locals.parentFolder);
+ logger.debug(`Receiving file to ${res.locals.parentFolder}`);
+ res.locals.modified = true;
if (res.locals.file != null) {
next(new RequestError(400, 'file_exists'));
}
@@ -611,7 +630,7 @@ export class FileRouter {
this.router.get ('/projects/:project_name/properties', getProjectProperties);
// File access
this.router.get ('/projects/:project_name/files/:path', getFilePath);
- this.router.post('/projects/:project_name/files/:id', postFilePath);
+ this.router.post('/projects/:project_name/files/:path', postFilePath);
this.router.get ('/projects/:project_name/files_by_id/:id', getFileId);
}
@@ -668,7 +687,7 @@ export class FileRouter {
req: Request, res: Response, next: NextFunction,
filename: string
): Promise<void> => {
- console.log("wrong precond")
+ console.log(`parsing path ${filename}`)
logger.debug(`Searching for file ${filename}`);
const fileNames: string[] = req.params.path.split('/');
const project: Project | null = res.locals.project;
@@ -721,7 +740,7 @@ export class FileRouter {
req: Request, res: Response, next: NextFunction,
fileId: string
): Promise<void> => {
- console.log(`Searching for file ${fileId}`);
+ console.log(`parsing id ${fileId}`);
const file: File | null = await File.findOne({
include: [{all: true}],
where: {
@@ -729,7 +748,6 @@ export class FileRouter {
}
});
res.locals.file = file;
- console.log("precondition: " + file)
next();
}
);
diff --git a/src/app.ts b/src/app.ts
index 1d1c9cb..e9d1d68 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -110,26 +110,22 @@ class App {
message: 'Welcome to the CS3099 BE4 server!',
important: 'Endpoints start from /cs3099group-be-4/'
});
- });
- //const errRouter: ex.Router = ex.Router();
-
+ });
this.express.use('/cs3099group-be-4', FileRouter);
this.express.use('/cs3099group-be-4', authRouter);
- this.express.use('/', defRouter);
- this.express.use((req: ex.Request, res: ex.Response, next: ex.NextFunction): void => {
- console.log(res.locals)
+ this.express.use('/', defRouter);
+ this.express.use((req: ex.Request, res: ex.Response,
+ next: ex.NextFunction): void => {
if (Object.keys(res.locals).length === 0) {
- console.log(404)
res.status(404)
.json({
status: 'error',
error : 'invalid_route',
error_description: 'Endpoints start from /cs3099group-be-4/'
});
+ } else {
+ next();
}
- else {
- next();
- }
});
}
@@ -149,5 +145,5 @@ export default new App(true).express;
*/
// tslint:disable-next-line:variable-name
export const TestApp: () => ex.Express = (): ex.Express => {
- return new App(false).express;
+ return new App(true).express;
};
diff --git a/src/logger.ts b/src/logger.ts
index aefb751..9025814 100644
--- a/src/logger.ts
+++ b/src/logger.ts
@@ -4,6 +4,7 @@ import * as colors from 'colors/safe';
import * as winston from 'winston';
import { files } from './files';
+import { QueryOptions } from 'sequelize';
type Colour = (s: string) => string;
@@ -252,6 +253,11 @@ const makeLogFunction: (level: LogLevel) => LogFunction = (
};
};
+function forwardLog(level: LogLevel, message: string, meta: LoggingMetadata)
+ : any {
+ basicLogger.log(level, message, meta);
+}
+
interface FetchParams {
before?: Date;
after?: Date;
@@ -265,40 +271,27 @@ interface LogItem {
timestamp: string;
}
-const fetchLogs: (level?: LogLevel, params?: FetchParams) => LogItem[] = (
- level?: LogLevel, params: FetchParams = {}
-): LogItem[] => {
- const matches: (log: any, level?: LogLevel, params?: FetchParams)
- => boolean = (
- log: any, minLevel?: LogLevel, fetchParams: FetchParams = {}
- ): boolean => {
- if (!minLevel) {
- // tslint:disable-next-line:no-parameter-reassignment
- minLevel = 'info';
- }
- const time: Date = new Date(log.timestamp);
- if (params.before && params.before < time) {
- return false;
- } else if (params.after && params.after > time) {
- return false;
- } else {
- return true;
- }
+/* tslint:disable */
+const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise<LogItem[]> = (level?: LogLevel, params: FetchParams = {}): Promise<LogItem[]> => {
+ const options: winston.QueryOptions = {
+ from: params.after,
+ until: params.before,
+ start: 0,
+ order: 'desc',
+ fields: ['user', 'component', 'level', 'message', 'label', 'timestamp']
};
- const out: LogItem[] = [];
- basicLogger.stream({ level }).on('log', (log: any): void => {
- if (matches(log, level, params)) {
- out.push({
- component: log.component,
- level: log.level,
- value: log.message,
- username: log.user,
- timestamp: log.timestamp
- });
- }
+
+ return new Promise((res, rej): void => {
+ basicLogger.query(options, function (err, results) {
+ if (err) {
+ /* TODO: handle me */
+ throw err;
+ }
+ res(results.basicFileTransport);
+ });
});
- return out;
};
+/* tslint:enable */
export const logger: {
7: LogFunction;
@@ -339,7 +332,7 @@ export const logger: {
shutdown: LogFunction;
isEnabled: () => boolean;
forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void;
- fetch: (level: LogLevel, params?: FetchParams) => LogItem[];
+ fetch: (level: LogLevel, params?: FetchParams) => Promise<LogItem[]>;
} = {
7: makeLogFunction('7'),
debug: makeLogFunction('debug'),
@@ -378,8 +371,8 @@ export const logger: {
emergency: makeLogFunction('emergency'),
shutdown: makeLogFunction('shutdown'),
isEnabled: (): boolean => !basicFileTransport.silent,
- forward: basicLogger.log,
- fetch: fetchLogs
+ forward: forwardLog,
+ fetch: fetchLogs2
};
export const logQuery: (query: string, duration: string) => void = (
diff --git a/src/matcher/options.ts b/src/matcher/options.ts
index 988d22b..0513eb3 100644
--- a/src/matcher/options.ts
+++ b/src/matcher/options.ts
@@ -18,7 +18,6 @@ const matchNoCurry:
if (types.atom(template)) {
return template === value;
} else if (types.function(template)) {
- //console.log("hi there " + value)
return template(value);
} else if (types.atom(value) || value === undefined) {
return false;
diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts
index ad9b892..1e8bf63 100644
--- a/test/integration/protocol.routes.test.ts
+++ b/test/integration/protocol.routes.test.ts
@@ -82,137 +82,138 @@ const errorResponseTemplate: Template = {
type MochaForEachInput = [ string, string, Template, number ];
-describe('routes : protocol', () => {
- const base: string = '/cs3099group-be-4';
+const base: string = '/cs3099group-be-4';
- /* tslint:disable:align */
+/* tslint:disable:align */
- // Format:
- // <method> <route> <json-response-template> <response-code>
- const completeProtocol: MochaForEachInput[] = [
- ['get', '/_supported_protocols_', {
- supported: array(types.string),
- required: array(types.string)
- }, 200],
- ['get', '/log', array({
- component: types.string,
- level: alternative([
- 'info',
- 'security',
- 'warning',
- 'error',
- 'critical'
- ]),
- value: types.anything,
- username: types.string,
- timestamp: types.string
- }), 200],
- ['post', '/log', [{
- component: 'tesssst',
- level: 'info',
- value: 'sdasdasdasdasdasd'
- }], 200],
- ['get', '/properties', array({
- id: types.string,
- display: optional(match({
- category: types.string,
- group: types.string,
- display_name: types.string,
- description: types.string
- })),
- read_only: types.boolean,
- type: alternative([
- 'string',
- 'integer',
- 'boolean'
- ]),
- value: alternative([
- types.string,
- types.integer,
- types.boolean
- ])
- }), 200],
- ['post', '/properties?action=update', null, 200],
- ['get', '/user_privileges', array({
- privilege: types.string,
- description: types.string,
- internal: types.boolean
- }), 200],
- ['get', '/users', array({
- username: types.string,
- privileges: types.array(types.string),
- projects: types.array({
- project_name: types.string,
- access_level: types.string
- }),
- public_user_metadata: types.anything,
- private_user_metadata: types.anything,
- public_admin_metadata: types.anything,
- private_admin_metadata: types.anything
- }), 200],
- // TODO types.metadata
- ['get', '/users/mock_user', {
- username: types.string,
- privileges: array(types.string),
- projects: array({
- project_name: types.string,
- access_level: types.string
- }),
- public_user_metadata: types.anything,
- private_user_metadata: types.anything,
- public_admin_metadata: types.anything,
- private_admin_metadata: types.anything
- }, 200],
- ['post', '/users/new_user', null, 200],
- ['get', '/users/mock_user/properties', {
- data: optional(types.anything)
- }, 200],
- ['get', '/current_user', {
- username: types.string,
- privileges: types.array(types.string),
- projects: types.array({
- project_name: types.string,
- access_level: types.string
- }),
- public_user_metadata: types.anything,
- private_user_metadata: types.anything,
- public_admin_metadata: types.anything,
- private_admin_metadata: types.anything
- }, 200],
- ['post', '/current_user', null, 200],
- ['get', '/project_roles', array({
- role: types.string,
- description: types.string,
- internal: types.boolean
- }), 200],
- ['get', '/projects', array({
+// Format:
+// <method> <route> <json-response-template> <response-code>
+const completeProtocol: MochaForEachInput[] = [
+ ['get', '/_supported_protocols_', {
+ supported: array(types.string),
+ required: array(types.string)
+ }, 200],
+ ['get', '/log', array({
+ component: types.string,
+ level: alternative([
+ 'info',
+ 'security',
+ 'warning',
+ 'error',
+ 'critical'
+ ]),
+ value: types.anything,
+ username: types.string,
+ timestamp: types.string
+ }), 200],
+ ['post', '/log', [{
+ component: 'tesssst',
+ level: 'info',
+ value: 'sdasdasdasdasdasd'
+ }], 200],
+ ['get', '/properties', array({
+ id: types.string,
+ display: optional(match({
+ category: types.string,
+ group: types.string,
+ display_name: types.string,
+ description: types.string
+ })),
+ read_only: types.boolean,
+ type: alternative([
+ 'string',
+ 'integer',
+ 'boolean'
+ ]),
+ value: alternative([
+ types.string,
+ types.integer,
+ types.boolean
+ ])
+ }), 200],
+ ['post', '/properties?action=update', null, 200],
+ ['get', '/user_privileges', array({
+ privilege: types.string,
+ description: types.string,
+ internal: types.boolean
+ }), 200],
+ ['get', '/users', array({
+ username: types.string,
+ privileges: types.array(types.string),
+ projects: types.array({
+ project_name: types.string,
+ access_level: types.string
+ }),
+ public_user_metadata: types.anything,
+ private_user_metadata: types.anything,
+ public_admin_metadata: types.anything,
+ private_admin_metadata: types.anything
+ }), 200],
+ // TODO types.metadata
+ ['get', '/users/mock_user', {
+ username: types.string,
+ privileges: array(types.string),
+ projects: array({
project_name: types.string,
- users: types.array({
- username: types.string,
- access_level: types.string
- }),
- public_metadata: types.anything,
- private_metadata: optional(types.anything),
- admin_metadata: optional(types.anything)
- }), 200],
- ['get', '/projects/mocky', {
+ access_level: types.string
+ }),
+ public_user_metadata: types.anything,
+ private_user_metadata: types.anything,
+ public_admin_metadata: types.anything,
+ private_admin_metadata: types.anything
+ }, 200],
+ ['post', '/users/new_user', null, 200],
+ ['get', '/users/mock_user/properties', {
+ data: optional(types.anything)
+ }, 200],
+ ['get', '/current_user', {
+ username: types.string,
+ privileges: types.array(types.string),
+ projects: types.array({
project_name: types.string,
- users: array({
- username: types.string,
- access_level: types.string
- }),
- public_metadata: types.anything,
- private_metadata: types.anything,
- admin_metadata: optional(types.anything)
- }, 200],
- ['post', '/projects/mocky', null, 200],
- ['get', '/projects/mocky/properties', null, 200],
- ['get', '/projects/mocky/files/example/path', null, 200],
- ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200],
- ['get', '/projects/mocky/files_by_id/file1', null, 200]
- ];
+ access_level: types.string
+ }),
+ public_user_metadata: types.anything,
+ private_user_metadata: types.anything,
+ public_admin_metadata: types.anything,
+ private_admin_metadata: types.anything
+ }, 200],
+ ['post', '/current_user', null, 200],
+ ['get', '/project_roles', array({
+ role: types.string,
+ description: types.string,
+ internal: types.boolean
+ }), 200],
+ ['get', '/projects', array({
+ project_name: types.string,
+ users: types.array({
+ username: types.string,
+ access_level: types.string
+ }),
+ public_metadata: types.anything,
+ private_metadata: optional(types.anything),
+ admin_metadata: optional(types.anything)
+ }), 200],
+ ['get', '/projects/mocky', {
+ project_name: types.string,
+ users: array({
+ username: types.string,
+ access_level: types.string
+ }),
+ public_metadata: types.anything,
+ private_metadata: types.anything,
+ admin_metadata: optional(types.anything)
+ }, 200],
+ ['post', '/projects/mocky', null, 200],
+ ['get', '/projects/mocky/properties', null, 200],
+ ['get', '/projects/mocky/files/example/path', null, 200],
+ ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200],
+ ['get', '/projects/mocky/files_by_id/file1', null, 200]
+];
- /* tslint:enable:align */
+/* tslint:enable:align */
+
+describe('routes : protocol', () => {
before(initDatabase);
beforeEach(populateDatabase);
@@ -236,7 +237,7 @@ describe('routes : protocol', () => {
(method: string, path: string, temp: Template, resCode: number) => {
const request: any = method === 'get'
? chai.request(app).get(base + path)
- : chai.request(app).post(base + path);
+ : chai.request(app).post(base + path).send(temp);
/*if (path.includes('/projects/mocky/files/some_file')) {
fs.createReadStream('test/mockUI/ui.html').pipe(
request);
@@ -245,7 +246,7 @@ describe('routes : protocol', () => {
request.set('Authorization', `Bearer ${token}`);
return request.then((res: ChaiHttp.Response) => {
if (path.includes('/projects/mocky/files/some_file')) {
- console.log("something")
+ //console.log("something")
}
expect(res).to.have.status(resCode);
});
@@ -255,26 +256,33 @@ describe('routes : protocol', () => {
(method: string, path: string, temp: Template, resCode: number) => {
const request: ChaiHttp.Request = method === 'get'
? chai.request(app).get(base + path)
- : chai.request(app).post(base + path);
+ : chai.request(app).post(base + path).send(temp);;
request.set('Authorization', `Bearer ${token}`);
return request.then((res: ChaiHttp.Response) => {
-
+ if (!(match(responseTemplate)(res.body))) {
+ console.log(`${method} ${path} ******************`);
+ console.log(res.body);
+ console.log("^^^^^^ received || template vvvvvvvv")
+ console.log(responseTemplate);
+ console.log('--------------------------------')
+ }
expect(match(responseTemplate)(res.body)).to.be.true;
});
});
forEach(completeProtocol).it(
- 'the response for %s %s should conform to its specific response protocol',
+ '%s %s should conform to its specific response template',
(method: string, path: string, temp: Template, resCode: number) => {
if (method === 'get' && temp != null) {
return chai.request(app)
.get(base + path)
.set('Authorization', `Bearer ${token}`)
.then((res: ChaiHttp.Response) => {
- if(!match(temp)(res.body.data)){
- console.log("******" + method + " - " + path + "*****8")
- console.log(res.body)
+ if (!(match(temp)(res.body.data))) {
+ console.log(`${method} ${path} ******************`);
+ console.log(res.body.data);
+ console.log("^^^^^^ received || template vvvvvvvv")
console.log(temp);
- console.log("*************************************9")
+ console.log('--------------------------------')
}
expect(match(temp)(res.body.data)).to.be.true;
});
@@ -286,6 +294,9 @@ describe('routes : protocol', () => {
describe('test edge cases', () => {
before(initDatabase);
+ beforeEach(populateDatabase);
+ beforeEach(getToken);
+
describe('GET invalid routes', () => {
// Should invalid routes also possibly be 401?
it.skip('should have response code 404', () => {
@@ -303,5 +314,39 @@ describe('routes : protocol', () => {
});
});
});
+
+ describe('POST invalid routes', () => {
+ // Should invalid routes also possibly be 401?
+ it.skip('should have response code 404', () => {
+ return chai.request(app).post('/invalid/route')
+ .set('Authorization', `Bearer ${token}`)
+ .catch((err) => {
+ expect(err.status).to.equal(404);
+ });
+ });
+ it('should conform to the error protocol', () => {
+ return chai.request(app).post('/invalid/route')
+ .set('Authorization', `Bearer ${token}`)
+ .catch((err) => {
+ expect(match(errorResponseTemplate)(err.response.body)).to.be.true;
+ });
+ });
+ });
+/*
+ describe('access valid routes with invalid parameters', () => {
+ forEach(completeProtocol.filter((item, index, arr) => {
+ return (item[0] == 'post');
+ })).it(
+ '%s %s with null body should throw error',
+ (method: string, path: string, temp: Template, resCode: number) => {
+ const request: any = chai.request(app).post(base + path);
+ request.set('Authorization', `Bearer ${token}`)
+ .then((res: any) => {
+ expect(res).to.have.status(400);
+ }).catch((reason: any) => {
+ expect(reason.response.body).to.eql("errererere");
+ });
+ });
+ });*/
});
});