import { Observable } from "rxjs/Observable" ; import { Subject } from "rxjs/Subject" ; import { Injectable } from "@angular/core" ; import { Response } from "@angular/http" ; import { JsonHttp } from "./" ; import { User } from "../domains" ; const jwtDecode = require ( 'jwt-decode' ) ; @ Injectable ( ) export class AuthService { private authEvents : Subject < AuthEvent > ; constructor ( private http ) { this . authEvents = new Subject < AuthEvent > ( ) ; } login ( email , password ) { const body = { email : email , password : password , } ; return this . http . post ( '/api/auth' , body ) . do ( ( resp ) => { localStorage . setItem ( 'jwt' , resp . json ( ) . token ) ; this . authEvents . next ( new DidLogin ( ) ) ; } ) ; } logout ( ) { localStorage . removeItem ( 'jwt' ) ; this . authEvents . next ( new DidLogout ( ) ) ; } isSignedIn ( ) { return localStorage . getItem ( 'jwt' ) !== null ; } isMyself ( user ) { if ( ! this . isSignedIn ( ) ) return null ; const decoded = jwtDecode ( localStorage . getItem ( 'jwt' ) ) ; return user . id + '' === decoded . sub ; } get events ( ) : Observable < AuthEvent > { return this . authEvents ; } } export class DidLogin { } export class DidLogout { } export type AuthEvent = DidLogin | DidLogout ;