74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
|
import { Observable } from 'rxjs/internal/Observable';
|
|
import { catchError, tap } from 'rxjs/operators';
|
|
import { Subject } from 'rxjs/internal/Subject';
|
|
import { ErrorLoggerService } from '../core/error-logger.service';
|
|
import { User } from '../core/user';
|
|
|
|
|
|
const httpOptions = {
|
|
headers: new HttpHeaders({'Content-Type': 'application/json'})
|
|
};
|
|
|
|
const loginUrl = '/v1/login';
|
|
const logoutUrl = '/logout';
|
|
const checkUrl = '/v1/auth';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthService {
|
|
public userObservable = new Subject<User>();
|
|
|
|
constructor(private http: HttpClient, private log: ErrorLoggerService) {
|
|
this.check().subscribe();
|
|
}
|
|
|
|
private _user: User;
|
|
|
|
get user() {
|
|
return this._user;
|
|
}
|
|
|
|
set user(user: User) {
|
|
this._user = user;
|
|
this.log.handleError('AuthService','Set User', user);
|
|
this.userObservable.next(user);
|
|
}
|
|
|
|
login(name: string, password: string, otp?: string, clientName?: string): Observable<any> {
|
|
const data = {name: name, password: password};
|
|
if (otp) {
|
|
data['otp'] = otp;
|
|
}
|
|
|
|
if (clientName) {
|
|
data['clientName'] = clientName;
|
|
}
|
|
|
|
return this.http.post(loginUrl, data, httpOptions)
|
|
.pipe(
|
|
tap((user: User) => this.user = user),
|
|
catchError(this.log.handleError('AuthService', 'login'))
|
|
);
|
|
}
|
|
|
|
logout(): Observable<any> {
|
|
return this.http.post(logoutUrl, {}, httpOptions)
|
|
.pipe(
|
|
tap((user: User) => this.user = user),
|
|
catchError(this.log.handleError('AuthService', 'logout'))
|
|
);
|
|
}
|
|
|
|
check(): Observable<any> {
|
|
return this.http.get(checkUrl, httpOptions)
|
|
.pipe(
|
|
tap((user: User) => this.user = user),
|
|
catchError(this.log.handleError('AuthService', 'check'))
|
|
);
|
|
}
|
|
|
|
}
|