1+ import * as request from 'request' ;
12import { my } from 'my-express' ;
23import { Log } from '../../core/log' ;
34
@@ -6,14 +7,56 @@ const log = new Log('api:middleware.authenticate');
67/**
78 * authenticate middleware
89 * -----------------------
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.
1111 *
1212 * @param req
1313 * @param res
1414 * @param next
1515 */
1616export const authenticate = ( req : my . Request , res : my . Response , next : my . NextFunction ) => {
17- log . info ( 'authenticate' ) ;
18- next ( ) ;
17+ const token = getToken ( req ) ;
18+
19+ if ( token === null ) {
20+ log . warn ( 'No token given' ) ;
21+ return res . failed ( 403 , 'You are not allowed to request this resource!' ) ;
22+ }
23+ log . debug ( 'Token is provided' ) ;
24+
25+ // Request user info at auth0 with the provided token
26+ request . post ( {
27+ url : `${ process . env . AUTH0_HOST } /tokeninfo` ,
28+ form : {
29+ id_token : token
30+ }
31+ } , ( error : any , response : request . RequestResponse , body : any ) => {
32+
33+ // Verify if the requests was successful and append user
34+ // information to our extended express request object
35+ if ( ! error && response . statusCode === 200 ) {
36+ req . tokeninfo = JSON . parse ( body ) ;
37+ log . info ( `Retrieved user ${ req . tokeninfo . email } ` ) ;
38+ return next ( ) ;
39+ }
40+
41+ // Catch auth0 exception and return it as it is
42+ log . warn ( `Could not retrieve the user, because of` , body ) ;
43+ res . failed ( response . statusCode || 401 , body ) ;
44+
45+ } ) ;
46+
47+ } ;
48+
49+ /**
50+ * Returns the access token of the given request header
51+ */
52+ const getToken = ( req : my . Request ) : string | null => {
53+ const authorization = req . headers . authorization ;
54+
55+ // Retrieve the token form the Authorization header
56+ if ( authorization && authorization . split ( ' ' ) [ 0 ] === 'Bearer' ) {
57+ return authorization . split ( ' ' ) [ 1 ] ;
58+ }
59+
60+ // No token was provided by the client
61+ return null ;
1962} ;
0 commit comments