@@ -8,6 +8,7 @@ const jwt = require('jsonwebtoken');
8
8
const NullStateStore = require ( './state/null' ) ;
9
9
const SessionStateStore = require ( './state/session' ) ;
10
10
const AuthorizationError = require ( './errors/authorizationerror' ) ;
11
+ const TokenError = require ( './errors/tokenerror' ) ;
11
12
const InternalOAuthError = require ( './errors/internaloautherror' ) ;
12
13
13
14
class AppleStrategy extends passport . Strategy {
@@ -87,7 +88,7 @@ class AppleStrategy extends passport.Strategy {
87
88
const oauth2 = this . _getOAuth2Client ( ) ;
88
89
89
90
oauth2 . getOAuthAccessToken ( code , params , ( err , accessToken , refreshToken , params ) => {
90
- if ( err ) return this . error ( new InternalOAuthError ( 'Failed to obtain access token' , err ) ) ;
91
+ if ( err ) return this . error ( this . _createOAuthError ( 'Failed to obtain access token' , err ) ) ;
91
92
92
93
const idToken = params [ 'id_token' ] ;
93
94
if ( ! idToken ) return this . error ( new Error ( 'ID Token not present in token response' ) ) ;
@@ -179,6 +180,21 @@ class AppleStrategy extends passport.Strategy {
179
180
}
180
181
}
181
182
183
+ /**
184
+ * @param {string } body
185
+ * @returns {Error }
186
+ */
187
+ parseErrorResponse ( body ) {
188
+ const json = JSON . parse ( body ) ;
189
+ if ( json . error ) {
190
+ return new TokenError ( json . error_description , json . error , json . error_uri ) ;
191
+ }
192
+ return null ;
193
+ }
194
+
195
+ /**
196
+ * @returns {oauth2.OAuth2 }
197
+ */
182
198
_getOAuth2Client ( ) {
183
199
const clientSecret = jwt . sign ( { } , this . _key , {
184
200
algorithm : 'ES256' ,
@@ -191,6 +207,24 @@ class AppleStrategy extends passport.Strategy {
191
207
192
208
return new OAuth2 ( this . _clientID , clientSecret , '' , this . _authorizationURL , this . _tokenURL ) ;
193
209
}
210
+
211
+ /**
212
+ * @param {string } message
213
+ * @param {object|Error } err
214
+ * @returns {Error }
215
+ */
216
+ _createOAuthError ( message , err ) {
217
+ let e ;
218
+ if ( err . statusCode && err . data ) {
219
+ try {
220
+ e = this . parseErrorResponse ( err . data ) ;
221
+ } catch ( _ ) {
222
+ // ignore
223
+ }
224
+ }
225
+ if ( ! e ) e = new InternalOAuthError ( message , err ) ;
226
+ return e ;
227
+ }
194
228
}
195
229
196
230
module . exports = AppleStrategy ;
0 commit comments