Skip to content

Instantly share code, notes, and snippets.

@Klowner
Created June 27, 2020 15:55
Show Gist options
  • Save Klowner/c632d62c325b781cf1d6c74f1312c174 to your computer and use it in GitHub Desktop.
Save Klowner/c632d62c325b781cf1d6c74f1312c174 to your computer and use it in GitHub Desktop.
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