Created
June 29, 2017 19:12
-
-
Save amcdnl/eae18cf0d6e57b9b39544d07a1b7e104 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Http, Response, Headers } from '@angular/http'; | |
import * as jwt_decode from 'jwt-decode'; | |
export const TOKEN_NAME: string = 'jwt_token'; | |
@Injectable() | |
export class AuthService { | |
private url: string = 'api/auth'; | |
private headers = new Headers({ 'Content-Type': 'application/json' }); | |
constructor(private http: Http) { } | |
getToken(): string { | |
return localStorage.getItem(TOKEN_NAME); | |
} | |
setToken(token: string): void { | |
localStorage.setItem(TOKEN_NAME, token); | |
} | |
getTokenExpirationDate(token: string): Date { | |
const decoded = jwt_decode(token); | |
if (decoded.exp === undefined) return null; | |
const date = new Date(0); | |
date.setUTCSeconds(decoded.exp); | |
return date; | |
} | |
isTokenExpired(token?: string): boolean { | |
if(!token) token = this.getToken(); | |
if(!token) return true; | |
const date = this.getTokenExpirationDate(token); | |
if(date === undefined) return false; | |
return !(date.valueOf() > new Date().valueOf()); | |
} | |
login(user): Promise<string> { | |
return this.http | |
.post(`${this.url}/login`, JSON.stringify(user), { headers: this.headers }) | |
.toPromise() | |
.then(res => res.text()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment