Created
June 27, 2020 15:55
-
-
Save Klowner/c632d62c325b781cf1d6c74f1312c174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class AuthService { | |
private readonly createRequest: AjaxCreationMethod = this.config.createRequest; | |
private readonly refreshToken$ = this.refreshToken(); | |
constructor(private readonly config: AuthServiceConfig) {} | |
authenticate(username: string, password: string): Observable<AjaxResponse> { | |
return this.createRequest({ | |
url: '/account/login', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: { | |
username, | |
password, | |
}, | |
}); | |
} | |
refreshToken(): Observable<boolean> { | |
return this.createRequest({ | |
url: '/account/refresh_token', | |
method: 'POST', | |
}).pipe( | |
catchError(() => of(false)), // refresh failed | |
mapTo(true), // refresh success! | |
share(), // merge subscribers and share results | |
); | |
} | |
attemptTokenRefreshOn401() { | |
return <T>(source: Observable<T>): Observable<T> => | |
source.pipe( | |
catchError((err, caught) => { | |
if (err.status === 401) { | |
return this.refreshToken$.pipe(mergeMap(() => caught)); // refresh then retry | |
} | |
return caught; // retry | |
}), | |
); | |
} | |
// Like regular ajax(), but attempts an auth refresh on | |
// 401 and then sets the authStatus subject appropriately | |
ajax(params: AjaxRequest): Observable<AjaxResponse> { | |
const ajax$ = this.createRequest(params); | |
const ajaxWithReauth$ = ajax$.pipe(this.addAutoReauth()); | |
return ajaxWithReauth$; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment