Skip to content

Instantly share code, notes, and snippets.

@Sampath-Lokuge
Created October 8, 2018 12:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Sampath-Lokuge/e8c57a8cb398a41f5e51ff07efc99ac3 to your computer and use it in GitHub Desktop.
Save Sampath-Lokuge/e8c57a8cb398a41f5e51ff07efc99ac3 to your computer and use it in GitHub Desktop.
authentication.service.ts
import { Observable, Subject, from, throwError } from 'rxjs';
import { map, catchError, tap, switchMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { AuthService } from 'ngx-auth';
import { TokenStorage } from './token-storage.service';
import { UtilsService } from '../services/utils.service';
import { AccessData } from './access-data';
import { Credential } from './credential';
@Injectable()
export class AuthenticationService implements AuthService {
API_URL = 'api';
API_ENDPOINT_LOGIN = '/login';
API_ENDPOINT_REFRESH = '/refresh';
API_ENDPOINT_REGISTER = '/register';
public onCredentialUpdated$: Subject<AccessData>;
constructor(private http: HttpClient, private tokenStorage: TokenStorage, private util: UtilsService) {
this.onCredentialUpdated$ = new Subject();
}
isAuthorized(): Observable<boolean> {
return this.tokenStorage.getAccessToken().pipe(map(token => !!token));
}
getAccessToken(): Observable<string> {
return this.tokenStorage.getAccessToken();
}
getUserRoles(): Observable<any> {
return this.tokenStorage.getUserRoles();
}
refreshToken(): Observable<AccessData> {
return this.tokenStorage.getRefreshToken().pipe(
switchMap((refreshToken: string) => {
return this.http.get<AccessData>(this.API_URL + this.API_ENDPOINT_REFRESH + '?' + this.util.urlParam(refreshToken));
}),
tap(this.saveAccessData.bind(this)),
catchError(err => {
this.logout();
return throwError(err);
})
);
}
refreshShouldHappen(response: HttpErrorResponse): boolean {
return response.status === 401;
}
verifyTokenRequest(url: string): boolean {
return url.endsWith(this.API_ENDPOINT_REFRESH);
}
login(credential: Credential): Observable<any> {
return this.http.get<AccessData>(this.API_URL + this.API_ENDPOINT_LOGIN + '?' + this.util.urlParam(credential)).pipe(
map((result: any) => {
if (result instanceof Array) {
return result.pop();
}
return result;
}),
tap(this.saveAccessData.bind(this)),
catchError(this.handleError('login', []))
);
}
private handleError<T>(operation = 'operation', result?: any) {
return (error: any): Observable<any> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return from(result);
};
}
logout(refresh?: boolean): void {
this.tokenStorage.clear();
if (refresh) {
location.reload(true);
}
}
private saveAccessData(accessData: AccessData) {
if (typeof accessData !== 'undefined') {
this.tokenStorage.setAccessToken(accessData.accessToken)
.setRefreshToken(accessData.refreshToken)
.setUserRoles(accessData.roles);
this.onCredentialUpdated$.next(accessData);
}
}
register(credential: Credential): Observable<any> {
// dummy token creation
credential = Object.assign({}, credential, {
accessToken: 'access-token-' + Math.random(),
refreshToken: 'access-token-' + Math.random(),
roles: ['USER'],
});
return this.http.post(this.API_URL + this.API_ENDPOINT_REGISTER, credential)
.pipe(catchError(this.handleError('register', []))
);
}
requestPassword(credential: Credential): Observable<any> {
return this.http.get(this.API_URL + this.API_ENDPOINT_LOGIN + '?' + this.util.urlParam(credential))
.pipe(catchError(this.handleError('forgot-password', [])));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment