1- import { NotAuthenticated } from '@feathersjs/errors' ;
1+ import { NotAuthenticated , FeathersError } from '@feathersjs/errors' ;
22import { Application } from '@feathersjs/feathers' ;
33import { AuthenticationRequest , AuthenticationResult } from '@feathersjs/authentication' ;
44import { Storage , StorageWrapper } from './storage' ;
@@ -118,6 +118,16 @@ export class AuthenticationClient {
118118 return Promise . resolve ( null ) ;
119119 }
120120
121+ handleError ( error : FeathersError , type : 'authenticate' | 'logout' ) {
122+ if ( error . code === 401 || error . code === 403 ) {
123+ const promise = this . removeAccessToken ( ) . then ( ( ) => this . reset ( ) ) ;
124+
125+ return type === 'logout' ? promise : promise . then ( ( ) => Promise . reject ( error ) ) ;
126+ }
127+
128+ return Promise . reject ( error ) ;
129+ }
130+
121131 reAuthenticate ( force : boolean = false ) : Promise < AuthenticationResult > {
122132 // Either returns the authentication state or
123133 // tries to re-authenticate with the stored JWT and strategy
@@ -133,9 +143,7 @@ export class AuthenticationClient {
133143 strategy : this . options . jwtStrategy ,
134144 accessToken
135145 } ) ;
136- } ) . catch ( ( error : Error ) =>
137- this . removeAccessToken ( ) . then ( ( ) => Promise . reject ( error ) )
138- ) ;
146+ } ) ;
139147 }
140148
141149 return authPromise ;
@@ -155,8 +163,8 @@ export class AuthenticationClient {
155163 this . app . emit ( 'authenticated' , authResult ) ;
156164
157165 return this . setAccessToken ( accessToken ) . then ( ( ) => authResult ) ;
158- } ) . catch ( ( error : Error ) =>
159- this . reset ( ) . then ( ( ) => Promise . reject ( error ) )
166+ } ) . catch ( ( error : FeathersError ) =>
167+ this . handleError ( error , 'authenticate' )
160168 ) ;
161169
162170 this . app . set ( 'authentication' , promise ) ;
@@ -166,20 +174,17 @@ export class AuthenticationClient {
166174
167175 logout ( ) {
168176 return Promise . resolve ( this . app . get ( 'authentication' ) )
169- . then ( auth => {
170- if ( ! auth ) {
171- return null ;
172- }
173-
174- return this . service . remove ( null )
175- . then ( ( authResult : AuthenticationResult ) => this . removeAccessToken ( )
176- . then ( ( ) => this . reset ( ) )
177- . then ( ( ) => {
178- this . app . emit ( 'logout' , authResult ) ;
179-
180- return authResult ;
181- } )
182- ) ;
183- } ) ;
177+ . then ( ( ) => this . service . remove ( null )
178+ . then ( ( authResult : AuthenticationResult ) => this . removeAccessToken ( )
179+ . then ( ( ) => this . reset ( ) )
180+ . then ( ( ) => {
181+ this . app . emit ( 'logout' , authResult ) ;
182+
183+ return authResult ;
184+ } )
185+ ) )
186+ . catch ( ( error : FeathersError ) =>
187+ this . handleError ( error , 'logout' )
188+ ) ;
184189 }
185190}
0 commit comments