@@ -15,10 +15,16 @@ enum FusionAuthStatusCode {
15
15
export class AuthenticationSession {
16
16
public authToken = '' ;
17
17
18
+ public refreshToken = '' ;
19
+
18
20
public readonly authContext ;
19
21
22
+ private authTokenExpiresAt = 0 ;
23
+
20
24
private readonly fusionAuthClient ;
21
25
26
+ private readonly fusionAuthAppId = process . env . FUSION_AUTH_APP_ID ?? '' ;
27
+
22
28
private twoFactorId = '' ;
23
29
24
30
private twoFactorMethods : TwoFactorMethod [ ] = [ ] ;
@@ -32,6 +38,32 @@ export class AuthenticationSession {
32
38
this . promptForPassword ( ) ;
33
39
}
34
40
41
+ public obtainNewAuthTokenUsingRefreshToken ( ) : void {
42
+ this . fusionAuthClient . exchangeRefreshTokenForAccessToken ( this . refreshToken , '' , '' , '' , '' )
43
+ . then ( ( clientResponse ) => {
44
+ this . authToken = clientResponse . response . access_token ?? '' ;
45
+ } )
46
+ . catch ( ( clientResponse : unknown ) => {
47
+ const message = isPartialClientResponse ( clientResponse )
48
+ ? clientResponse . exception . message
49
+ : '' ;
50
+ logger . warn ( `Error obtaining refresh token : ${ message } ` ) ;
51
+ this . authContext . reject ( ) ;
52
+ } ) ;
53
+ }
54
+
55
+ public tokenExpired ( ) : boolean {
56
+ const expirationDate = new Date ( this . authTokenExpiresAt ) ;
57
+ return expirationDate <= new Date ( ) ;
58
+ }
59
+
60
+ public tokenWouldExpireSoon ( minutes = 5 ) : boolean {
61
+ const expirationDate = new Date ( this . authTokenExpiresAt ) ;
62
+ const currentTime = new Date ( ) ;
63
+ const timeDifferenceMinutes = ( expirationDate . getTime ( ) - currentTime . getTime ( ) ) / ( 1000 * 60 ) ;
64
+ return timeDifferenceMinutes <= minutes ;
65
+ }
66
+
35
67
private promptForPassword ( ) : void {
36
68
this . authContext . prompt (
37
69
{
@@ -46,6 +78,7 @@ export class AuthenticationSession {
46
78
47
79
private processPasswordResponse ( [ password ] : string [ ] ) : void {
48
80
this . fusionAuthClient . login ( {
81
+ applicationId : this . fusionAuthAppId ,
49
82
loginId : this . authContext . username ,
50
83
password,
51
84
} ) . then ( ( clientResponse ) => {
@@ -57,6 +90,8 @@ export class AuthenticationSession {
57
90
username : this . authContext . username ,
58
91
} ) ;
59
92
this . authToken = clientResponse . response . token ;
93
+ this . authTokenExpiresAt = clientResponse . response . tokenExpirationInstant ?? 0 ;
94
+ this . refreshToken = clientResponse . response . refreshToken ?? '' ;
60
95
this . authContext . accept ( ) ;
61
96
return ;
62
97
}
0 commit comments