Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created June 29, 2017 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcdnl/eae18cf0d6e57b9b39544d07a1b7e104 to your computer and use it in GitHub Desktop.
Save amcdnl/eae18cf0d6e57b9b39544d07a1b7e104 to your computer and use it in GitHub Desktop.
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