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
|
import { RequestError } from './errors/errorware';
import { NextFunction, Request, Response, Router } from 'express';
import * as jwt from 'jsonwebtoken';
import * as passport from 'passport';
import { Strategy } from 'passport-local';
import { default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
import { default as Project } from './db/model/Project';
import { Errorware } from './errors/errorware';
/**
* The module for system authentication.
*/
/**
* A class used to configure the authentication of the server.
*/
export class AuthRouter {
/**
* The Express Router this authenticator is built on.
*/
public router: Router;
/**
* A simple constructor that initialises the authenticator.
*/
public constructor() {
this.router = Router();
this.init();
}
/**
* A middleware function that generates an OAuth-like token, used for
* authentication in future interactions with the client.
*
* @param req The Express http request.
* @param res The Express http response.
*/
public async genToken(req: Request, res: Response): Promise<void> {
const user: User | null = await User.findOne({
where: {
username: req.body.username
},
include: [ UserGroup, Project]
});
if (user === null) {
// Whoa, what an error!
return;
}
const token: string = jwt.sign(
{ object: user },
'Mr Secret',
{ expiresIn: 21600 }
);
res.json({
token_type: 'bearer',
access_token: token,
refresh_token: token,
expires_in: 21600
});
}
/**
* Middleware used to authenticate the user, using previously-obtained
* OAuth-like tokens.
*
* @param req The Express http request.
* @param res The Express http response.
*/
private authenticate(req: Request, res: Response, next: NextFunction): void {
passport.authenticate(
'local',
{ session: false },
(err: Error, user: User) => {
// TODO: Implement
if (err) { throw err; }
if (!user) {
next(new RequestError(
400, 'invalid_grant', 'Incorrect authentication details'
));
}
}
);
next();
}
/**
* Middleware that checks the incoming request for missing or
* inaccurate properties, before the authentication process.
*
* @param req The Express http request.
* @param res The Express http response.
*/
public checkErr(req: Request, res: Response, next: NextFunction): void {
if (!req.body.grant_type || !req.body.username || !req.body.password) {
next(new RequestError(400, 'invalid_request', 'Missing parameters'));
}
if (req.body.grant_type !== 'refresh_token'
&& req.body.grant_type !== 'password') {
next(new RequestError(400, 'unsupported_grant_type', 'invalid grant type'));
}
next();
}
/**
* Used to configure Passport to use the custom authentication strategy.
*/
private configStrategy(): void {
// tslint:disable-next-line:typedef
passport.use(new Strategy( async(username, password, done) => {
const user: User | null = await User.findOne({
where: {
username
},
include: [UserGroup, Project]
});
if (!user || user.password !== password) {
return done(null, false);
}
return done(null, user);
}));
}
/**
* Function used by the constructor to initialise the authenticator.
*/
public init(): void {
this.configStrategy();
this.router.post('/oauth/token', this.checkErr, this.authenticate, this.genToken);
this.router.get(
'/logout',
(req: Request, res: Response): void => { req.logout(); }
);
}
}
/**
* Error-handling middleware used to handle authentication errors.
*
* The error is transformed into one that can be handled by later
* error-handling middleware functions.
*
* @param err The Error to handle/transform.
* @param req The Express http request.
* @param res The Express http response.
* @param next The next Express middleware function.
*/
export const unauthorisedErr: Errorware =
(err: Error, req: Request, res: Response, next: NextFunction): void => {
console.log('fffff');
if (err.name === 'UnauthorizedError') {
console.log('efewfwf');
return next(new RequestError(
401, 'not_authorised',
'user does not have correct authorisation for task'
));
}
next(err);
};
/**
* A middleware to check whether or not the currently-authenticated User is
* an admin.
*
* @param req The Express http request.
* @param res The Express http response.
* @param next The next Express middleware function.
*/
export const isAdmin: any =
(req: Request, res: Response, next: NextFunction): void => {
var isAdmin: boolean = req.user.object.userGroups.some((x: UserGroup): boolean => x.name === 'admin');
if (!isAdmin) {
next(new RequestError(
401, 'not_authorised',
'user is not authorised to perform task'
));
return;
}
next();
}
export default new AuthRouter().router;
///////////////////////////////////////////////////
/*
* tasks left:
* refreshing tokens
* connect to db
* revoke tokens/checking validity
* logging out
*/
|