Created
July 19, 2016 22:32
-
-
Save MT--/d58383a0dba6c3a21c872a783e4fca5d to your computer and use it in GitHub Desktop.
Session Management Class for Authenticated HTTP Requests with JWT
This file contains hidden or 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 { Observable, Observer } from 'rxjs'; | |
@Injectable() | |
export class SessionService { | |
public isLoggedIn: Observable<any>; | |
private isLoggedInObserver: Observer<any>; | |
private apiUrl: string = 'YOUR_API_ENDPOINT'; | |
private token: string; | |
private headers: Headers; | |
constructor(private http: Http) { | |
this.isLoggedIn = new Observable(observer => { | |
this.isLoggedInObserver = observer; | |
}); | |
this.headers = new Headers(); | |
} | |
/** | |
* start a new session with token or wait for login | |
* | |
*/ | |
public newSession(): void { | |
// check for token | |
if ( this.getToken() ) { | |
this.setXAuth(this.token); | |
this.isLoggedInObserver.next(true); | |
} else { | |
// ask user to log in | |
} // end if | |
} | |
/** | |
* override GET request | |
* | |
*/ | |
public authGet(url: string): Observable<Response> { | |
return this.http.get(url, { headers: this.headers }); | |
} | |
/** | |
* override POST request | |
* | |
*/ | |
public authPost(url: string, data: any): Observable<Response> { | |
return this.http.post(url, data, { headers: this.headers }); | |
} | |
/** | |
* get auth token from API | |
* @param username | |
* @param password | |
* @returns {Subscription} | |
*/ | |
public login(username: string, password: string): void { | |
console.log('Logging in user: ' + username); | |
this.http.post(this.apiUrl, { | |
username: username, | |
password: password | |
}) | |
.map(SessionService.extractResponse) | |
.subscribe( | |
data => { | |
this.token = data[ 'token' ]; | |
this.setXAuth(this.token); | |
this.isLoggedInObserver.next(true); | |
}, | |
err => { | |
SessionService.handleError(err); | |
this.isLoggedInObserver.next(false); | |
} | |
); | |
} | |
/** | |
* remove token and x-auth header | |
* | |
*/ | |
public logout(): void { | |
this.unsetXAuth(); | |
} | |
/** | |
* return token or check localStorage | |
* @returns {string | null} | |
*/ | |
public getToken(): string { | |
if ( !this.token ) { | |
return this.token = window.localStorage.getItem('token'); | |
} else { | |
return this.token; | |
} // end if | |
} | |
/** | |
* add auth token to HTTP verbs and localStorage | |
* | |
*/ | |
private setXAuth(token: string): void { | |
if ( token ) { | |
this.headers.append('x-auth', token); | |
window.localStorage.setItem('token', token); | |
} // end if | |
} | |
/** | |
* remove token from HTTP verbs and localStorage | |
* | |
*/ | |
private unsetXAuth(): void { | |
this.headers.delete('x-auth'); | |
window.localStorage.removeItem('token'); | |
} | |
/** | |
* parse HTTP Response | |
* @param {Response} res | |
* @returns {{}} | |
*/ | |
public static extractResponse(res: Response): any { | |
return res.json(); | |
} | |
/** | |
* parse error from server to console | |
* @param {*} error | |
* @returns {ErrorObservable} | |
*/ | |
public static handleError(error: any): Observable<any> { | |
let errMsg = (error.message) ? error.message : | |
error.status ? `${error.status} - ${error.statusText}` : 'Server Error'; | |
return Observable.throw(errMsg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment