argos/dmp-admin/src/app/services/auth/auth.service.ts

85 lines
2.8 KiB
TypeScript

import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
//import { HostConfiguration } from '../../app.constants';
import { Principal } from '../../models/login/Principal';
//import { Credential } from '../../models/login/Credential';
import { Observable } from 'rxjs/Rx';
//import { MatSnackBar } from '@angular/material';
import { Router } from '@angular/router';
import { JsonSerializer } from '../../utilities/JsonSerializer';
import { LoginInfo } from '../../models/login/LoginInfo';
import { Credential } from 'app/models/login/Credential';
//import { SnackBarNotificationComponent } from '../../shared/components/notificaiton/snack-bar-notification.component';
@Injectable()
export class AuthService {
private actionUrl: string;
private headers: HttpHeaders;
constructor(
private http: HttpClient,
//public snackBar: MatSnackBar,
public router: Router
) {
this.actionUrl = 'http://192.168.32.67:8080/' + 'auth/';
this.headers = new HttpHeaders();
this.headers = this.headers.set('Content-Type', 'application/json');
this.headers = this.headers.set('Accept', 'application/json');
}
private clear(): void {
localStorage.removeItem('principal');
}
public current(principal?: Principal): Principal {
if (principal) {
localStorage.setItem('principal', JSON.stringify(principal));
return principal;
}
const principalJson = localStorage.getItem('principal');
if (!principalJson) { return null; }
const principalObj = JSON.parse(principalJson) as Principal;
return principalObj;
}
public me(): Observable<Principal> {
const url = this.actionUrl + '/me';
const principal = this.current();
if (!principal) {
this.clear();
return Observable.of<Principal>();
}
let headers = this.headers;
headers = headers.set('AuthToken', principal.token)
return this.http.post(url, null, { headers: headers })
.map((res: any) => {
const princ = this.current(JsonSerializer.fromJSONObject(res.payload, Principal));
return princ;
})
.catch((error: any) => {
console.warn('could not retrieve me info:\n', error);
this.clear();
const princ = this.current();
this.router.navigate(['/login']);
return Observable.of<Principal>(princ);
});
}
public nativeLogin(credentials: Credential): Observable<Principal> { debugger;
const url = this.actionUrl + 'nativelogin';
return this.http.post(url, credentials, { headers: this.headers })
.map((res: any) => {
const principal = this.current(JsonSerializer.fromJSONObject(res.payload, Principal));
//this.loginContextSubject.next(true);
return principal;
})
.catch((error: any) => {
//this.loginContextSubject.next(false);
return Observable.throw(error);
});
}
}