Initial commit for the Angular part. We are nowhere yet.
This commit is contained in:
73
bookie/src/app/auth/auth.service.ts
Normal file
73
bookie/src/app/auth/auth.service.ts
Normal file
@ -0,0 +1,73 @@
|
||||
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 '../user/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'))
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user