import {Injectable} from "@angular/core"; import {Http, Response} from "@angular/http"; import "rxjs/add/operator/map"; import {AppConfig} from "../../app.config"; import {AppUser} from "../../models/model-interfaces"; import {AwardingService} from "../awarding-service/awarding.service"; import {PromotionService} from "../promotion-service/promotion.service"; @Injectable() export class LoginService { constructor(private http: Http, private config: AppConfig, 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 local storage to keep user logged in between page refreshes localStorage.setItem('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() { // remove user from local storage localStorage.removeItem('currentUser'); } isLoggedIn() { if (localStorage.getItem('currentUser')) { return true; } return false } hasPermission(level: number) { let currentUser = JSON.parse(localStorage.getItem('currentUser')); return this.isLoggedIn() && currentUser.permission >= level; } getCurrentUser(): AppUser { return JSON.parse(localStorage.getItem('currentUser')); } hasSquad() { let currentUser = JSON.parse(localStorage.getItem('currentUser')); return currentUser.squad != null; } }