From c964362481afdd0d853f68f21492e64b361b5a3c Mon Sep 17 00:00:00 2001
From: Chris Hines <chris.hines@monash.edu>
Date: Thu, 28 Jan 2021 13:56:29 +1100
Subject: [PATCH] better detection of cert expiration

---
 src/app/app.component.ts             |  8 +++++++-
 src/app/authorisation.service.ts     | 13 +++++++------
 src/app/browser-window.service.ts    |  6 +-----
 src/app/joblist/joblist.component.ts |  1 -
 src/app/jobs.service.ts              | 12 ++++++++----
 src/app/keygen/keygen.component.ts   |  1 +
 src/app/notifications.service.ts     | 18 ++++++++++--------
 src/app/tes.service.ts               | 21 ++++++++++++++-------
 8 files changed, 48 insertions(+), 32 deletions(-)

diff --git a/src/app/app.component.ts b/src/app/app.component.ts
index 5dae0c5..5d4743b 100644
--- a/src/app/app.component.ts
+++ b/src/app/app.component.ts
@@ -60,13 +60,19 @@ export class AppComponent {
   }
 
 
-  private displayMessage(msg) {
+  private displayMessage(notification: [string,any]) {
+   var msg: string = notification[0]
+   var fn: any = notification[1]
    if (msg === null || msg == "") {
      if (this.snackBarRef != undefined) {
        this.snackBarRef.dismiss()
      }
    } else {
      this.snackBarRef = this.snackBar.open(msg,'Dismiss');
+     if (fn !== null && fn !== undefined) {
+       console.log('adding a subscription',fn);
+       this.snackBarRef.afterDismissed().subscribe(() => { console.log(fn); fn() });
+     }
    }
  }
   setTheme(theme: string)  {
diff --git a/src/app/authorisation.service.ts b/src/app/authorisation.service.ts
index fc69827..03e726f 100644
--- a/src/app/authorisation.service.ts
+++ b/src/app/authorisation.service.ts
@@ -209,12 +209,13 @@ public getKeys(id?: Identity) {
      tap((resp) => { console.log('agent contents',resp) }),
      switchMap((resp) => of(this.addExpiryField(resp))),
      tap((resp) => { 
-       if (this.agentContents.value !== null && this.agentContents.value.length > resp.length) {
-         this.notifications.notify("Your login expired. Please login again");
-       } else {
-         this.notifications.notify("");
-       };
-       this.agentContents.next(resp)
+      //  if (this.agentContents.value !== null && this.agentContents.value.length > resp.length) {
+      //    this.notifications.notify("Your login expired. Please login again");
+      //  } else {
+      //    this.notifications.notify("");
+      //  };
+      this.notifications.notify("");
+      this.agentContents.next(resp)
      }),
      catchError((e) => { console.error('updateAGentContents error',e) ; return of([])})
      //tap((_) => this.notifications.notify(""))
diff --git a/src/app/browser-window.service.ts b/src/app/browser-window.service.ts
index 89b58c9..6ca2f1a 100644
--- a/src/app/browser-window.service.ts
+++ b/src/app/browser-window.service.ts
@@ -64,7 +64,7 @@ export class BrowserWindowService {
      let twshost = this.twsproxy.replace(re,"$1");
      let windowloc = url.replace(/\{twsproxy\}/g,this.twsproxy).replace(/twshost/g,twshost);
      var authwindow = null;
-     console.log('openAppWindow entered');
+
    
      if (basicAuth) {
        let authwindowloc = windowloc.replace(/^https:\/\//,'https://'+appinst.username+':'+appinst.password+'@');
@@ -111,14 +111,10 @@ export class BrowserWindowService {
 
   public logUsage() {
     var app: any;
-    console.log('entered log usage');
-    console.log(this.settingsService.logging);
     if (this.settingsService.logging) {
     this.openapps.forEach( (app,index) => {
-      console.log('probing window',app);
       if (!app.window.closed) {
         if (app.job.state == 'RUNNING') {
-          console.log('log url',environment.logserver+"/"+app.job.identity.site.name+"/"+app.job.identity.username+"/"+app.job.app.name+"/"+app.job.jobid);
           this.http.get<any>(environment.logserver+"/"+app.job.identity.site.name+"/"+app.job.identity.username+"/"+app.job.app.name+"/"+app.job.jobid).pipe( //We're expecting 404 not founds
             catchError((e) => {console.error(e); return of([]);})
           ).subscribe((v) => {console.log('log success',v); return})
diff --git a/src/app/joblist/joblist.component.ts b/src/app/joblist/joblist.component.ts
index 7aa175c..8bec7bb 100644
--- a/src/app/joblist/joblist.component.ts
+++ b/src/app/joblist/joblist.component.ts
@@ -53,7 +53,6 @@ export class JoblistComponent implements OnInit {
      {this.sub = timer(5000).pipe(repeat()).subscribe( () => this.getJobs() )});
  }*/
  updateJoblist(jobquery: Job[], identity: Identity) {
-   console.log('in updateJoblist')
    var joblist: Job[] = []
    var qjobids: any[] = [];
    var cjobids: any[] = [];
diff --git a/src/app/jobs.service.ts b/src/app/jobs.service.ts
index a20b802..f1da484 100644
--- a/src/app/jobs.service.ts
+++ b/src/app/jobs.service.ts
@@ -42,17 +42,21 @@ export class JobsService {
 
   public getJobsError(error,identity: Identity) {
     this.tsub.unsubscribe();
+    if (identity.expiry < Date.now()) {
+      this.notifications.notify("Your login has expired. Please log in again", () => { this.authService.updateAgentContents().subscribe((_) => {return}) } );
+      return;
+    }
+    console.error('getJobsError id', identity);
     if (error.hasOwnProperty("error") && error.error.hasOwnProperty("message")) {
       if (error.error.message.indexOf("Permission denied") != -1) {
-        this.notifications.notify("Your login appears to have expired. Please log in again");
-        //this.authService.updateAgentContents().subscribe((_) => {return});
+        this.notifications.notify("Your login appears to have expired. Please log in again", () => { this.authService.updateAgentContents().subscribe((_) => {return}) } );
         return;
       } 
-      this.notifications.notify("Unable to retrieve a list of running jobs.\nDid your session expire?\nThe error messge was " + error.error.message);
+      this.notifications.notify("Unable to retrieve a list of running jobs.\nThe error messge was " + error.error.message);
       return;
     }
     console.error(error);
-    this.notifications.notify("Unable to retrieve a list of running jobs.\nDid your session expire?");
+    this.notifications.notify("Unable to retrieve a list of running jobs.\nThe error wasn't specified\nPlease report what you were doign via the contact us link", () => { this.authService.updateAgentContents().subscribe((_) => {return}) });
     //this.authService.updateAgentContents().subscribe((_) => {return});
   }
 
diff --git a/src/app/keygen/keygen.component.ts b/src/app/keygen/keygen.component.ts
index bcc0716..73f4230 100644
--- a/src/app/keygen/keygen.component.ts
+++ b/src/app/keygen/keygen.component.ts
@@ -118,6 +118,7 @@ export class KeygenComponent implements OnInit, OnDestroy {
     var now = new Date()
     var end = new Date(now.getTime() + 28*24*60*60*1000); //request a certificate valid for 28 days
                                                           //its expected that the user will terminate the session by closing their browser/sleeping their laptop before this
+    //var end = new Date(now.getTime() + 30*1000); // Uncomment if you want to test certificates expiring
     let data = {'public_key': key.public, 'end': end.toISOString()};
     return this.http.post<any>(token.sshauthzservice.sign,data, options).pipe(
       tap((v) => console.log('in getCert',v)),
diff --git a/src/app/notifications.service.ts b/src/app/notifications.service.ts
index f4bc2f3..cc12ace 100644
--- a/src/app/notifications.service.ts
+++ b/src/app/notifications.service.ts
@@ -6,34 +6,36 @@ import { BehaviorSubject } from 'rxjs';
 })
 export class NotificationsService {
 
-  private msg: BehaviorSubject<string>;
+  private msg: BehaviorSubject<[string,any]>;
+  private afterNotifyFn: BehaviorSubject<any>;
 
   constructor() { 
-    this.msg = new BehaviorSubject<string>(null);
+    this.msg = new BehaviorSubject<[string,any]>([null,null]);
   }
 
   getMsg() {
     return this.msg;
   }
 
-  notify(msg: any) {
+
+  notify(msg: any, afterFn : any = null) {
     if (msg === null || msg === undefined) {
-      this.msg.next("");
+      this.msg.next(["",null]);
       return
     }
     if (msg.hasOwnProperty('error')) {
-      this.notify(msg.error);
+      this.notify(msg.error, afterFn);
       return;
     }
     if (msg.hasOwnProperty('message')) {
-      this.notify(msg.message);
+      this.notify(msg.message, afterFn);
       return;
     }
     if (msg.hasOwnProperty('msg')) {
-      this.notify(msg.msg);
+      this.notify(msg.msg, afterFn);
       return;
     }
-    this.msg.next(msg);
+    this.msg.next([msg, afterFn]);
     console.log(msg);
   }
 
diff --git a/src/app/tes.service.ts b/src/app/tes.service.ts
index 4aaaef5..4e45841 100644
--- a/src/app/tes.service.ts
+++ b/src/app/tes.service.ts
@@ -165,13 +165,17 @@ private addUserHealth(identity,resp) {
  }
 
 
- submissionError(error: any) {
+ submissionError(identity: Identity, error: any) {
+  if (identity.expiry < Date.now()) {
+    this.notifications.notify("Your login has expired. Please log in again",   () => { this.authorisationService.updateAgentContents().subscribe( () => {return} ) }  );
+    return;
+  }
    if (error.status != 0) {
        try {
          this.notifications.notify(error);
          console.error(error);
        } catch {
-         this.notifications.notify('Job Canceling failed');
+         this.notifications.notify('Job Submission failed');
          console.error(error);
        }
    }
@@ -209,7 +213,7 @@ private addUserHealth(identity,resp) {
    let body = {'app': app, 'appparams': appparams, 'keys': keys, 'ids': JSON.stringify(JSON.stringify(ids))}
    this.http.post<any>(this.Base+'/submit'+'?'+paramstr, body, options)
                                           .subscribe(resp => { this.notifications.notify(null) },
-                                                     error => this.submissionError(error));
+                                                     error => this.submissionError(identity, error));
  }
 
 
@@ -309,7 +313,7 @@ private addUserHealth(identity,resp) {
                                             'action':action,'appinst':appinst});
                                       }
                                     job.connectionState=null},
-     (err) => { job.connectionState = 0; this.handleError(err)})
+     (err) => { job.connectionState = 0; this.handleError(job.identity, err)})
  }
 
 
@@ -353,9 +357,13 @@ public getSftpData(id: Identity, path: string, cd: string ) {
 
 }
 
-private handleError(error: HttpErrorResponse) {
+private handleError(identity: Identity, error: HttpErrorResponse) {
   console.error(error);
   console.log('in handle error');
+  if (identity.expiry < Date.now()) {
+    this.notifications.notify("Your login has expired. Please log in again",   () => { this.authorisationService.updateAgentContents().subscribe( () => {return} ) }  );
+    return;
+  }
   if (error.error instanceof ErrorEvent) {
     this.notifications.notify("A networking error occured.")
     return
@@ -368,8 +376,7 @@ private handleError(error: HttpErrorResponse) {
     this.notifications.notify(error);
     return
   }
-  this.notifications.notify("Your login appears to have expired. Please login again");
-  this.authorisationService.updateAgentContents().subscribe((v) => {return});
+  this.notifications.notify(error);
 }
 
 
-- 
GitLab