1+ import auth0 , { WebAuth } from 'auth0-js'
2+ import router from '../router/'
3+ import EventEmitter from 'EventEmitter'
4+
5+ export default class AuthService {
6+ authenticated = this . isAuthenticated ( )
7+ authNotifier = new EventEmitter ( )
8+ auth0 : WebAuth
9+ constructor ( hostname :string , port :string , protocol :string ) {
10+ this . login = this . login . bind ( this ) ;
11+ this . setSession = this . setSession . bind ( this )
12+ this . logout = this . logout . bind ( this )
13+ this . isAuthenticated = this . isAuthenticated . bind ( this )
14+ var stringBuild = protocol + "//" + hostname ;
15+ if ( port !== "" )
16+ stringBuild += ':' + port
17+ stringBuild += '/callback'
18+ this . auth0 = new auth0 . WebAuth ( {
19+ domain : 'dotnextrussia.eu.auth0.com' ,
20+ clientID : 'g7saZcm47evyY3kWWP26ZxifDpxycl9h' ,
21+ redirectUri : stringBuild ,
22+ audience : 'http://medhelp20171124063439.azurewebsites.net/' ,
23+ responseType : 'token id_token' ,
24+ scope : 'openid profile read:templates'
25+ } ) ;
26+ }
27+
28+
29+
30+
31+ login ( ) {
32+ this . auth0 . authorize ( ) ;
33+ }
34+
35+ handleAuthentication ( ) {
36+ this . auth0 . parseHash ( ( err , authResult ) => {
37+ if ( authResult && authResult . accessToken && authResult . idToken ) {
38+ this . setSession ( authResult )
39+ router . replace ( 'home' )
40+ } else if ( err ) {
41+ router . replace ( 'home' )
42+ console . log ( err )
43+ alert ( `Error: ${ err . error } . Check the console for further details.` )
44+ }
45+ location . reload ( )
46+ } )
47+ }
48+
49+ setSession ( authResult : any ) {
50+ // Set the time that the access token will expire at
51+ let expiresAt = JSON . stringify (
52+ authResult . expiresIn * 1000 + new Date ( ) . getTime ( )
53+ )
54+ localStorage . setItem ( 'access_token' , authResult . accessToken )
55+ localStorage . setItem ( 'id_token' , authResult . idToken )
56+ localStorage . setItem ( 'expires_at' , expiresAt )
57+ this . authNotifier . emit ( 'authChange' , { authenticated : true } )
58+ }
59+
60+ logout ( ) {
61+ // Clear access token and ID token from local storage
62+ localStorage . removeItem ( 'access_token' )
63+ localStorage . removeItem ( 'id_token' )
64+ localStorage . removeItem ( 'expires_at' )
65+ //this.userProfile = null
66+ this . authNotifier . emit ( 'authChange' , false )
67+ // navigate to the home route
68+ router . replace ( 'home' )
69+ location . reload ( )
70+ }
71+
72+ isAuthenticated ( ) {
73+ // Check whether the current time is past the
74+ // access token's expiry time
75+ let expiresAt = JSON . parse ( localStorage . getItem ( 'expires_at' ) || '{}' )
76+ return new Date ( ) . getTime ( ) < expiresAt
77+ }
78+ }
0 commit comments