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