aboutsummaryrefslogtreecommitdiff
path: root/src/auth.ts
blob: 14e1170038f7e5a348b5fdda506186dfafb9070a (plain) (blame)
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
import { Errorware, RequestError } from './errors/errorware';
import { NextFunction, Request, Response, Router } from 'express';
import { Middleware } from './FileRouter';
import * as jwt from 'jsonwebtoken';
import * as passport from 'passport';
import { Strategy } from 'passport-local';
import { default as Project } from './db/model/Project';
import { default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';

/**
 * The module for system authentication.
 */

/**
 * Used to configure Passport to use the custom authentication strategy.
 */
const configStrategy: () => void = (): 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);
	}));
};

/**
 * 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.
 * @param next The next Express middleware.
 */
const checkErr: Middleware = (
	req: Request, res: Response, next: NextFunction
): void => {
	if (!req.body.grant_type || !req.body.username || !req.body.password) {
		return next(new RequestError(400, 'invalid_request', 'Missing parameters'));
	}

	if (req.body.grant_type !== 'refresh_token'
		&& req.body.grant_type !== 'password') {
		return next(new RequestError(
			400, 'unsupported_grant_type', 'invalid grant type'
		));
	}

	next();
};

/**
 * Middleware used to authenticate the user, using previously-obtained
 * OAuth-like tokens.
 *
 * @param req The Express http request.
 * @param res The Express http response.
 */
const authenticate: Middleware = (
	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();
};

/**
 * 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.
 * @param next The next Express middleware - only used for errors.
 */
const genToken: Middleware = async(
	req: Request, res: Response, next: NextFunction
): 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 next(new RequestError(
			400,
			'invalid_grant',
			'Invalid username'
		));
	}

	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
	});
};

/**
 * 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();
	}

	/**
	 * Function used by the constructor to initialise the authenticator.
	 */
	public init(): void {
		configStrategy();

		this.router.post(
			'/oauth/token',
			checkErr,
			authenticate,
			genToken
		);
		this.router.get(
			'/logout',
			(req: Request, res: Response): void => { req.logout(); }
		);
	}
}

interface UnauthorizedError {
	name: 'UnauthorizedError';
	message: string;
	code: string;
	status: number;
}

const isUnauthorizedError: (item: object) => item is UnauthorizedError = (
	item: object
): item is UnauthorizedError => {
	return (item as Partial<UnauthorizedError>).name === 'UnauthorizedError'
		&& (item as Partial<UnauthorizedError>).message !== undefined
		&& (item as Partial<UnauthorizedError>).code    !== undefined
		&& (item as Partial<UnauthorizedError>).status  !== undefined;
};

/**
 * 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 => {
	if (isUnauthorizedError(err)) {
		return next(new RequestError(
			err.status,
			'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: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
	// tslint:disable-next-line:no-non-null-assertion
	const admin: boolean = req!.user!.object!.userGroups!
		.some((x: UserGroup): boolean => x.name === 'admin');

	if (!admin) {
		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
 */