@@ -4,29 +4,15 @@ const token = require('./token')
4
4
const { error, fakeReply, verify } = require ( './utils' )
5
5
const pkg = require ( '../package.json' )
6
6
7
- let manager
8
-
9
7
/**
10
- * @function
11
- * @public
12
- *
13
- * Get user information based on token with help of Keycloak.
14
- * If all validations and requests are successful, save the
15
- * token and its user data in memory cache.
8
+ * @type Object
9
+ * @private
16
10
*
17
- * @param {string } token The token to be validated
18
- * @param {Function } reply The callback handler
11
+ * Internally used properties
19
12
*/
20
- function handleKeycloakUserInfo ( tkn , reply ) {
21
- manager . userInfo ( tkn . get ( ) ) . then ( ( userInfo ) => {
22
- const { scope, expiresIn } = tkn . getData ( )
23
- const userData = { credentials : Object . assign ( { scope } , userInfo ) }
24
-
25
- cache . set ( tkn . get ( ) , userData , expiresIn )
26
- reply . continue ( userData )
27
- } ) . catch ( ( err ) => {
28
- reply ( error ( 'unauthorized' , err ) )
29
- } )
13
+ const internals = {
14
+ manager : undefined ,
15
+ userInfoFields : [ ]
30
16
}
31
17
32
18
/**
@@ -41,8 +27,16 @@ function handleKeycloakUserInfo (tkn, reply) {
41
27
function handleKeycloakValidation ( tkn , reply ) {
42
28
const invalidate = ( err ) => reply ( error ( 'unauthorized' , err , error . msg . invalid ) )
43
29
44
- manager . validateAccessToken ( tkn . get ( ) ) . then ( ( res ) => {
45
- res ? handleKeycloakUserInfo ( tkn , reply ) : invalidate ( )
30
+ internals . manager . validateAccessToken ( tkn . get ( ) ) . then ( ( res ) => {
31
+ if ( ! res ) {
32
+ return invalidate ( )
33
+ }
34
+
35
+ const { expiresIn, ...credentials } = tkn . getData ( internals . userInfoFields )
36
+ const userData = { credentials }
37
+
38
+ cache . set ( tkn . get ( ) , userData , expiresIn )
39
+ return reply . continue ( userData )
46
40
} ) . catch ( invalidate )
47
41
}
48
42
@@ -108,9 +102,11 @@ function strategy (server) {
108
102
*/
109
103
function plugin ( server , opts , next ) {
110
104
opts = verify ( opts )
111
- manager = new GrantManager ( opts )
112
105
cache . init ( server , opts . cache )
113
106
107
+ internals . manager = new GrantManager ( opts . client )
108
+ internals . userInfoFields = opts . userInfo
109
+
114
110
server . auth . scheme ( 'keycloak-jwt' , strategy )
115
111
server . decorate ( 'server' , 'kjwt' , { validate } )
116
112
0 commit comments