import {Injectable} from "@angular/core"; import {Http, Response} from "@angular/http"; import "rxjs/add/operator/map"; import {AppConfig} from "../../app.config"; import {AwardingService} from "../army-management/awarding.service"; import {PromotionService} from "../army-management/promotion.service"; import {CookieService} from "ngx-cookie-service"; @Injectable() export class LoginService { constructor(private http: Http, private config: AppConfig, private cookieService: CookieService, private awardingService: AwardingService, private promotionService: PromotionService) { } login(username: string, password: string) { return this.http.post(this.config.apiAuthenticationPath, {username: username, password: password}) .map((response: Response) => { // login successful if there's a jwt token in the response let user = response.json(); if (user && user.token) { // store user details and jwt token in cookie this.cookieService.set('currentUser', JSON.stringify(user)); if (user.permission >= 2) { const fraction = user.squad.fraction; this.awardingService.checkUnprocessedAwards(fraction); this.promotionService.checkUnconfirmedPromotions(fraction); } } }); } signUp(username: string, password: string, secret: string) { return this.http.post(this.config.apiSignupPath, {username: username, password: password, secret: secret}) .map((response: Response) => { }); } logout() { this.cookieService.delete('currentUser'); } isLoggedIn() { return !!this.cookieService.get('currentUser'); } hasPermission(level: number) { return this.isLoggedIn() && this.getCurrentUser().permission >= level; } getCurrentUser() { return JSON.parse(this.cookieService.get('currentUser')); } hasSquad() { return this.getCurrentUser().squad != null; } }