11import { Injectable } from '@angular/core' ;
2- import { Http } from '@angular/http' ;
2+ import { Http , Headers } from '@angular/http' ;
33import { Store } from '@ngrx/store' ;
44import { RootState } from '../index' ;
55import { Observable } from 'rxjs/Observable' ;
6+ import { LogoutAction , ProcessTokenAction , AuthErrorAction } from './auth.actions' ;
67
78
89@Injectable ( )
910export class AuthService {
1011
1112 private authenticated$ : Observable < boolean > ;
1213
14+ public static decodeAccessToken ( access_token : string ) {
15+ return JSON . parse ( window . atob ( access_token . split ( '.' ) [ 1 ] ) ) ;
16+ }
17+
1318 constructor ( public http : Http , private store : Store < RootState > ) {
1419 this . authenticated$ = store . select ( s => s . auth . authenticated ) ;
1520 }
@@ -18,4 +23,45 @@ export class AuthService {
1823 return this . authenticated$ ;
1924 }
2025
26+ public authenticate ( username : string , password : string ) : void {
27+
28+ console . log ( 'Authentication pending...' ) ;
29+
30+ if ( ! username . trim ( ) ) {
31+ this . store . dispatch ( new AuthErrorAction ( 'Username cannot be blank' ) ) ;
32+ return ;
33+ }
34+ if ( ! password . trim ( ) ) {
35+ this . store . dispatch ( new AuthErrorAction ( 'Password cannot be blank' ) ) ;
36+ return ;
37+ }
38+
39+ const headers = new Headers ( ) ;
40+ headers . append ( 'Content-Type' , `application/x-www-form-urlencoded` ) ;
41+
42+ const payload = 'username=' + encodeURIComponent ( username ) + '&password=' + encodeURIComponent ( password ) ;
43+
44+ this . http
45+ . post ( '/api/authentication' , payload , { headers : headers } )
46+ . subscribe (
47+ data => {
48+ const jwtToken = data . text ( ) ;
49+ localStorage . setItem ( 'tokenData' , jwtToken ) ;
50+ this . store . dispatch ( new ProcessTokenAction ( jwtToken ) ) ;
51+ } ,
52+ err => {
53+ console . log ( err ) ;
54+ this . store . dispatch ( new AuthErrorAction ( 'Username and password doesn\'t match' ) ) ;
55+ return ;
56+ }
57+ ) ;
58+
59+ }
60+
61+ public logout ( ) : void {
62+ localStorage . removeItem ( 'tokenData' ) ;
63+ this . store . dispatch ( new LogoutAction ( ) ) ;
64+ }
65+
66+
2167}
0 commit comments