1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
|
import { ContributorGroupFullInfo, default as ContributorGroup
} from './db/model/ContributorGroup';
import { default as File } from './db/model/File';
import { ProjectFullInfo, default as Project } from './db/model/Project';
import { UserFullInfo, default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
import { NextFunction, Request, Response, Router } from 'express';
import { RequestError } from './errors/errorware';
import { View, files, views } from './files';
import { logger } from './logger';
import { Property, default as serverConfig } from './serverConfig';
import { uuid } from './uuid';
// TODO: figure this out
const BASE_FILE_STORAGE: string = 'TODO: figure this out';
/**
* The type of an Express middleware callback.
*/
export type Middleware =
(req: Request, res: Response, next: NextFunction) => void;
/**
* Returns the supported Protocols
*
* The server's unwrapped response MUST match:
*
* exactly({
* "supported": array(string),
* "required": array(string)
* })
*/
const getProtocols: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Fetching supported protocols');
res.locals.data = {
supported: [],
required: [
'BE01'
]
};
next();
};
/**
* Logging Endpoint for all components:
*
* with a request matching
*
* array({
* "component": string,
* "level": alternative([
* "info",
* "security",
* "warning",
* "error",
* "critical"
* ]),
* "value": anything
* })
*/
const postLog: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Adding forwarded log');
if (!req.user.hasPrivilege('logging')) {
next(new RequestError(401, 'invalid_privilege'));
return;
} else if (!logger.isEnabled()) {
next(new RequestError(501, 'logging_not_enabled'));
return;
}
for (const item of req.body) {
logger.forward(item.level, item.value, {
component: item.component,
user: req.user.username,
external: true
});
}
next();
};
/**
* Clients authorised as a user with the admin privilege can access
*
* http://backend.endpoint/log?before=<datetime>&after=<datetime>&level=<level>
*
* the server response should match
*
* array({
* "component": string,
* "level": alternative([
* "info",
* "security",
* "warning",
* "error",
* "critical"
* ]),
* "value": anything,
* "username": string,
* "timestamp": string
* })
*/
const getLog: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Fetching log');
if (!req.user.hasPrivilege('admin')) {
next(new RequestError(401, 'invalid_privilege'));
}
res.locals.data = logger.fetch(
req.params.level, {
before: new Date(req.params.before),
after: new Date(req.params.after)
}
);
next();
};
/**
* Any authenticated client can access
*
* http://backend.endpoint/properties
*
* the server SHOULD respond with a list of properties,
* with the unwrapped response matching
*
* array({
* "id": string,
* "display": optional({
* "category": string,
* "group": string,
* "display_name": string,
* "description": string
* }),
* "read_only": boolean,
* "type": alternative(["string", "integer", "boolean"]),
* "value": alternative([string, integer, boolean])
* })
*/
const getProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Listing server properties');
res.locals.data = serverConfig;
next();
};
/**
* To update properties the client POSTs to
*
* http://backend.endpoint/properties?action=update
*
* with body
*
* array({
* "id": string,
* "value": alternative([string, integer, boolean])
* })
*/
const postProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Editing server properties');
for (const newProp of req.body) {
const prop: Property | undefined = serverConfig.find(
(p: Property): boolean => p.id === newProp.id
);
if (prop === undefined) {
next(new RequestError(400, 'invalid_property', undefined, newProp.id));
return;
} else if (prop.readOnly) {
next(new RequestError(400, 'invalid_property', undefined, newProp.id));
return;
}
try {
prop.value = newProp.value;
} catch (err) {
// FIXME: Assuming it's a value-type error, but it might not be!
next(new RequestError(400, 'invalid_property_value', undefined, newProp.id));
return;
}
}
next();
};
/**
* Listing available privileges
*
* And the server's response, unwrapped, must match
*
* array({
* "privilege": string,
* "description": string,
* "internal": boolean
* })
*/
const getUserPrivileges: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Listing all user privileges');
const usergroups: UserGroup[] = await UserGroup.findAll();
res.locals.data = usergroups.map(
(ug: UserGroup) => ug.getPrivilege()
);
next();
};
/**
* Listing users
*
* If the client is authorised as a user with the admin privilege
* the server MUST respond with a list of users,
* with the unwrapped response matching
*
* array({
* "username": string,
* "privileges": array(string),
* "projects": array({
* "project_name": string,
* "access_level": string
* }),
* "public_user_metadata": metadata,
* "private_user_metadata": metadata,
* "public_admin_metadata": metadata,
* "private_admin_metadata": metadata
* })
*/
const getUsers: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Listing all registered users');
const users: User[] = await User.findAll({
include: [
UserGroup,
Project
]
});
res.locals.data = users.map((u: User): UserFullInfo => {
const info: UserFullInfo = u.fullInfo;
if (!req.user.hasPrivilege('admin')) {
delete info.private_user_metadata;
delete info.private_admin_metadata;
}
return info;
});
next();
};
/**
* Expose additional configuration options for individual users
*/
const getUserProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Listing additional properties for a user');
if (res.locals.user == null) {
next(new RequestError(404, 'user_not_found'));
return;
}
res.locals.data = res.locals.user.properties;
next();
};
/**
* Listing a particular User
*
* If the client is authorised as a user with the admin privilege
* the server MUST respond with details of the particular user if they exist
* (unwrapped response):
*
* {
* "username": string,
* "privileges": array(string),
* "projects": array({
* "project_name": string,
* "access_level": string
* }),
* "public_user_metadata": metadata,
* "private_user_metadata": metadata,
* "public_admin_metadata": metadata,
* "private_admin_metadata": metadata
* }
*/
const getUsername: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug(`Listing user ${res.locals.user}`);
if (res.locals.user == null) {
next(new RequestError(404, 'user_not_found'));
return;
}
res.locals.data = res.locals.user.fullInfo;
next();
};
const getCurUser: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Listing current user');
res.locals.data = req.user.fullInfo;
next();
};
/**
* Updating the current user
*
* http://backend.endpoint/current_user?action=update
*
* with body matching
*
* {
* "password": optional({
* "old": string,
* "new": string
* }),
* "public_user_metadata": optional(metadata),
* "private_user_metadata": optional(metadata),
* "public_admin_metadata": not_present,
* "private_admin_metadata": not_present
* }
*/
const postCurUser: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Editing current user');
try {
await req.user.updateInfo(req.body);
await req.user.save();
} catch (err) {
next(err);
return;
}
next();
};
/**
* Creating a User/updating a user
*
* http://backend.endpoint/users/<username>?action=create
*
* with body matching
*
* {
* "privileges": array(string),
* "password": string,
* "public_user_metadata": optional(metadata),
* "private_user_metadata": optional(metadata),
* "public_admin_metadata": optional(metadata),
* "private_admin_metadata": optional(metadata)
* }
*/
const postUsername: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
let user: User | null | undefined = res.locals.user;
if (user == null) {
console.log('Adding new user');
user = new User({
username: req.params.username,
password: req.params.password
});
} else {
console.log('Editing user');
user.password = req.params.password;
}
if (req.body) {
user.metadata = req.body;
}
next();
};
/**
* Listing available Roles
*
* The servers response, unwrapped, must match
*
* array({
* "role": string,
* "description": string,
* "internal": boolean
* })
*/
const getProjectRoles: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Listing available project roles');
const roles: ContributorGroup[] = await ContributorGroup.findAll();
res.locals.data = roles.filter(
(cg: ContributorGroup): boolean => !cg.isInternal
).map(
(cg: ContributorGroup): ContributorGroupFullInfo => cg.fullInfo
);
next();
};
/**
* Listing Projects
*
* The server MUST respond with a list of projects,
* with the unwrapped response matching
*
* array({
* "project_name": string,
* "users": array({
* "username": string,
* "access_level": string
* }),
* "public_metadata": metadata,
* "private_metadata": optional(metadata),
* "admin_metadata": optional(metadata)
* })
*/
const getProjects: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Listing all projects');
const projects: Project[] = await Project.findAll({
include: [
User
]
});
res.locals.data = projects.map(
(p: Project): ProjectFullInfo => p.fullInfo
);
next();
};
/**
* Listing a specific Project
*
* The server MUST respond with details of the particular project
* if it exists (unwrapped response):
*
* {
* "project_name": string,
* "users": array({
* "username": string,
* "access_level": string
* }),
* "public_metadata": metadata,
* "private_metadata": metadata,
* "admin_metadata": optional(metadata)
* }
*/
const getProjectName: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug('Getting project properties');
const project: Project | null = res.locals.project;
if (project == null) {
return next(new RequestError(404, 'project_not_found'));
} else {
res.locals.data = project.fullInfo;
next();
}
};
/**
* Creating a Project / updating a project / deleting / Project grants
*
* http://backend.endpoint/projects/<project_name>?action=create
*
* with body matching
*
* {
* "public_metadata": optional(metadata),
* "private_metadata": optional(metadata),
* "admin_metadata": optional(metadata)
* }
*/
const postProjectName: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
let project: Project | null = res.locals.project;
let promise: PromiseLike<File> | null = null;
if (project == null) {
logger.debug('Adding new project');
const file: File = new File({
uuid: uuid.generate(),
mimetype: 'inode/directory'
});
promise = file.save();
project = new Project({
name: req.params.project_name,
rootFolder: file
});
} else {
logger.debug('Updating project properties');
}
project.metadata = req.body;
// tslint:disable-next-line:await-promise
await promise;
await project.save();
next();
};
/**
* additional configuration options for individual projects
*/
const getProjectProperties: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Getting project properties');
if (res.locals.project == null) {
next(new RequestError(404, 'project_not_found'));
} else {
res.locals.data = res.locals.project.properties;
next();
}
};
/**
* GET a File.
*/
const getFile: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
logger.debug(`Getting file in ${req.query.view} view`);
const file: File | null = res.locals.file;
if (file == null) {
return next(new RequestError(404, 'file_not_found'));
}
const project: Project = res.locals.project;
const view: View = views[req.query.view || 'meta'];
res.locals.function = view.getResponseFunction(req, res);
res.locals.data = view.getResponseData(file, project, req.query);
next();
};
/**
* GET a File.
*/
const getFilePath: Middleware = getFile;
/**
* GET a File.
*/
const getFileId: Middleware = getFile;
/**
* Post a File. / delete / move / etc
*/
const postFilePath: Middleware = (
req: Request, res: Response, next: NextFunction
): void => {
logger.debug('Receiving file');
if (res.locals.file != null) {
next(new RequestError(400, 'file_exists'));
}
const file: File = new File({
uuid: uuid.generate(),
name: res.locals.filename,
parentFolder: res.locals.parentFolder
});
req.pipe(files.writableStream(file.uuid, res.locals.project.name));
next();
};
export class FileRouter {
public router: Router;
/**
* Initialize the FileRouter
*/
public constructor() {
this.router = Router();
this.init();
}
/**
* Take each handler, and attach to one of the Express.Router's
* endpoints.
*/
public init(): void {
this.precondition();
// General
this.router.get ('/_supported_protocols_', getProtocols);
this.router.get ('/log', getLog);
this.router.post('/log', postLog);
this.router.get ('/properties', getProperties);
this.router.post('/properties', postProperties);
// Users
this.router.get ('/user_privileges', getUserPrivileges);
this.router.get ('/users', getUsers);
this.router.get ('/users/:username', getUsername);
this.router.post('/users/:username', postUsername);
this.router.get ('/users/:username/properties', getUserProperties);
this.router.get ('/current_user', getCurUser);
this.router.post('/current_user', postCurUser);
// Projects
this.router.get ('/project_roles', getProjectRoles);
this.router.get ('/projects', getProjects);
this.router.get ('/projects/:project_name', getProjectName);
this.router.post('/projects/:project_name', postProjectName);
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.get ('/projects/:project_name/files_by_id/:id', getFileId);
}
/**
* Introduces variable-preconditioning middleware to the Express app.
*
* These middleware functions pre-process Express' matching variables
* in routes (e.g. `:project_name`).
* If an entity cannot be found in the database, the corresponding
* value is set to `null` instead.
*/
private precondition(): void {
logger.debug('Adding parameter preconditioning to router');
// Fetch a user from their name:
this.router.param(
'username',
async(
req: Request, res: Response, next: NextFunction,
name: string
): Promise<void> => {
logger.debug(`Searching for user ${name}`);
const user: User | null = await User.findOne({
include: [{all: true}],
where: {
username: name
}
});
res.locals.user = user;
next();
}
);
// Fetch a project from its name:
this.router.param(
'project_name',
async(
req: Request, res: Response, next: NextFunction,
projectName: string
): Promise<void> => {
res.locals.project = await Project.findOne({
include: [{all: true}],
where: {
name: projectName
}
});
next();
}
);
// Fetch a file from its path:
this.router.param(
'file',
async(
req: Request, res: Response, next: NextFunction,
filename: string
): Promise<void> => {
logger.debug(`Searching for file ${filename}`);
const fileNames: string[] = req.params.path.split('/');
const project: Project | null = res.locals.project;
if (project == null) {
logger.debug('Project was not found: skipping finding file');
return next(new RequestError(404, 'project_not_found'));
}
let file: File = project.rootFolder;
// TODO Rewrite using sub-queries instead of repeated queries.
while (fileNames.length > 2) {
const fileOrNull: File | null = await File.findOne({
where: {
name: fileNames[0],
parentFolder: file
}
});
if (fileOrNull == null) {
return next();
} else {
file = fileOrNull;
}
fileNames.splice(0, 1);
}
const parentFolder: File | null = await File.findOne({
include: [
{ model: File, as: 'containedFiles' }
],
where: {
parentFolder: file,
name: fileNames[0]
}
});
if (parentFolder == null) {
return next();
}
res.locals.parentFolder = parentFolder;
const tFile: File | undefined = parentFolder.containedFiles.find(
(f: File): boolean => f.name === fileNames[1]
);
res.locals.file = tFile;
res.locals.filename = fileNames[1];
next();
}
);
// Fetch a file from its UUID:
this.router.param(
'id',
async(
req: Request, res: Response, next: NextFunction,
fileId: string
): Promise<void> => {
logger.debug(`Searching for file ${fileId}`);
const file: File | null = await File.findOne({
include: [{all: true}],
where: {
uuid: fileId
}
});
if (file == null) {
return next(new RequestError(404, 'file_not_found'));
} else {
res.locals.file = file;
}
next();
}
);
}
}
// Create the FileRouter, and export its configured Express.Router
const fileRoutes: FileRouter = new FileRouter();
export default fileRoutes.router;
|