|
| 1 | +import { RequestAPI, RequiredUriUrl, Options, Request, RequestResponse } from 'request'; |
1 | 2 | import { my } from 'my-express'; |
2 | 3 | import { Log } from '../../core/log'; |
3 | 4 |
|
4 | | -const log = new Log('api:middleware.authenticate'); |
| 5 | +// const log = new Log('api:middleware.authenticate'); |
5 | 6 |
|
6 | 7 | /** |
7 | 8 | * authenticate middleware |
8 | 9 | * ----------------------- |
9 | | - * This middleware can be used to check if all credentials are given and |
10 | | - * verify them. |
| 10 | + * This middleware secures your resources with the auth0 authentication. |
11 | 11 | * |
12 | 12 | * @param req |
13 | 13 | * @param res |
14 | 14 | * @param next |
15 | 15 | */ |
16 | | -export const authenticate = (req: my.Request, res: my.Response, next: my.NextFunction) => { |
17 | | - log.info('authenticate'); |
18 | | - next(); |
| 16 | +export const authenticate = (request: RequestAPI<Request, Options, RequiredUriUrl>, log: Log) => |
| 17 | + (req: my.Request, res: my.Response, next: my.NextFunction) => { |
| 18 | + const token = getToken(req); |
| 19 | + |
| 20 | + if (token === null) { |
| 21 | + log.warn('No token given'); |
| 22 | + return res.failed(403, 'You are not allowed to request this resource!'); |
| 23 | + } |
| 24 | + log.debug('Token is provided'); |
| 25 | + |
| 26 | + // Request user info at auth0 with the provided token |
| 27 | + request({ |
| 28 | + method: 'POST', |
| 29 | + url: `${process.env.AUTH0_HOST}/tokeninfo`, |
| 30 | + form: { |
| 31 | + id_token: token |
| 32 | + } |
| 33 | + }, (error: any, response: RequestResponse, body: any) => { |
| 34 | + // Verify if the requests was successful and append user |
| 35 | + // information to our extended express request object |
| 36 | + if (!error && response.statusCode === 200) { |
| 37 | + req.tokeninfo = JSON.parse(body); |
| 38 | + log.info(`Retrieved user ${req.tokeninfo.email}`); |
| 39 | + return next(); |
| 40 | + } |
| 41 | + |
| 42 | + // Catch auth0 exception and return it as it is |
| 43 | + log.warn(`Could not retrieve the user, because of`, body); |
| 44 | + let statusCode = 401; |
| 45 | + if (response && response.statusCode) { |
| 46 | + statusCode = response.statusCode; |
| 47 | + } else { |
| 48 | + log.warn('It seems your oauth server is down!'); |
| 49 | + } |
| 50 | + res.failed(statusCode, body); |
| 51 | + |
| 52 | + }); |
| 53 | + |
| 54 | + }; |
| 55 | + |
| 56 | +/** |
| 57 | + * Returns the access token of the given request header |
| 58 | + */ |
| 59 | +const getToken = (req: my.Request): string | null => { |
| 60 | + const authorization = req.headers.authorization; |
| 61 | + |
| 62 | + // Retrieve the token form the Authorization header |
| 63 | + if (authorization && authorization.split(' ')[0] === 'Bearer') { |
| 64 | + return authorization.split(' ')[1]; |
| 65 | + } |
| 66 | + |
| 67 | + // No token was provided by the client |
| 68 | + return null; |
19 | 69 | }; |
0 commit comments