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
|
import * as bodyParser from 'body-parser';
import { cors } from './cors';
import * as ex from 'express';
import * as expressJwt from 'express-jwt';
import * as passport from 'passport';
import { default as authRouter, unauthorisedErr } from './auth';
import { logger } from './logger';
import { errorHandler } from './errors/errorware';
import FileRouter from './FileRouter';
import { default as File } from './db/model/File';
import { default as Project } from './db/model/Project';
import { default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
/**
* Configuration of the Express server app, including installation of
* various middleware functions.
*/
/**
* The Class used to configure the Express app used in the server instance.
*/
class App {
/**
* The Express app used throughout the server.
*/
public express: ex.Express;
/**
* Whether or not logging is enabled on the server.
*/
private readonly logEnabled: boolean = true;
/**
* Constructs an instance of the app, by loading middleware.
*
* @param enableLog Whether or not logging should be enabled on the
* server.
*/
public constructor(enableLog: boolean) {
logger.debug('Constructing router');
this.logEnabled = enableLog;
this.express = ex();
this.express.use(cors());
this.express.use(
(req: ex.Request, res: ex.Response, next: ex.NextFunction): void => {
logger.info(`Connection from ${req.ip} requesting ${req.url}`);
next();
}
);
this.middleware();
this.mountRoutes();
this.express.use(
async(req: ex.Request, res: ex.Response, next: ex.NextFunction):
Promise<void> => {
if (res.locals.function) {
res.locals.function.bind(res)(await res.locals.data);
} else {
res.json({
status: 'success',
data: await res.locals.data
});
}
logger.success(`Responded to ${req.ip}`);
}
);
this.errorware();
}
/**
* Configures regular Express middleware.
*/
private middleware(): void {
logger.debug('Loading basic middleware');
this.express.use(expressJwt({secret: 'Mr Secret'})
.unless({path: [
'/',
'/cs3099group-be-4/oauth/token',
'/cs3099group-be-4/_supported_protocols_'
] })
);
this.express.use((req, res, next) => {
if (req.headers.authorisation) {
(req.headers.authorization as any) = req.headers.authorisation;
}
next();
})
this.express.use(passport.initialize());
this.express.use(async(
req: ex.Request, res: ex.Response, next: ex.NextFunction
): Promise<void> => {
if (req.user != null) {
req.user = await User.findOne({
where: {
username: req.user.object.username
},
include: [
UserGroup
]
});
}
next();
});
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: false }));
}
/**
* Adds the Router routes to the Express app.
*/
private mountRoutes(): void {
const defRouter: ex.Router = ex.Router();
defRouter.get('/', (req: ex.Request, res: ex.Response): void => {
res.json({
message: 'Welcome to the CS3099 BE4 server!',
important: 'Endpoints start from /cs3099group-be-4'
});
});
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 => {
if (Object.keys(res.locals).length === 0) {
res.status(404)
.json({
status: 'error',
error : 'invalid_route',
error_description: 'Endpoints start from /cs3099group-be-4'
});
} else {
next();
}
});
}
/**
* Adds error-handling (4-arity) middleware to the Express app.
*/
private errorware(): void {
this.express.use(unauthorisedErr);
this.express.use(errorHandler);
}
}
export default new App(true).express;
/**
* A version of the app used only for testing.
*/
// tslint:disable-next-line:variable-name
export const TestApp: () => ex.Express = (): ex.Express => {
return new App(true).express;
};
|