Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable} from '@angular/core';
- import {BehaviorSubject} from 'rxjs/BehaviorSubject';
- import 'rxjs/add/operator/map';
- import {Observable} from 'rxjs/Observable';
- import {CookieService} from 'ngx-cookie';
- import {LoggerService} from './logger.service';
- import {ApiService} from './api.service';
- import {User, LogoutInfo} from '../../model/user';
- @Injectable()
- export class AuthService {
- private currentUserSubject = new BehaviorSubject<User>(new User());
- private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
- private userUrl: string = 'user';
- constructor(
- private cookieService: CookieService,
- private apiService: ApiService,
- private loggerService: LoggerService
- ) {}
- currentUser(): Observable<User> {
- return this.currentUserSubject.asObservable();
- }
- isAuthenticated(): Observable<boolean> {
- return this.isAuthenticatedSubject.asObservable();
- }
- setAuthentication(user: User): void {
- this.currentUserSubject.next(user);
- this.isAuthenticatedSubject.next(true);
- this.loggerService.log(`Session set for ${user.contactName}.`);
- }
- purgeAuthentication(): void {
- this.currentUserSubject.next(new User());
- this.isAuthenticatedSubject.next(false);
- this.loggerService.log('Session removed.');
- }
- populate() {
- return new Promise((resolve, reject) => {
- if (this.cookieService.get('vedrax-index-ui-csrf')) {
- let url = `${this.userUrl}/current`;
- this.apiService.get<User>(url)
- .subscribe(
- res => {
- this.setAuthentication(res);
- resolve();
- },
- err => {
- this.loggerService.logObject(err);
- this.purgeAuthentication();
- resolve();
- });
- } else {
- this.purgeAuthentication();
- resolve();
- }
- });
- }
- login(username: string, password: string): Observable<User> {
- let url = `${this.userUrl}/login`;
- return this.apiService.post<User>(url, {userName: username, password: password})
- .map(data => {
- this.setAuthentication(data);
- return data;
- });
- }
- logout(): Observable<LogoutInfo> {
- let url = `${this.userUrl}/logout`;
- return this.apiService.get<LogoutInfo>(url)
- .map(data => {
- this.purgeAuthentication();
- return data;
- });
- }
- }
Add Comment
Please, Sign In to add comment