Skip to content

SciCat Dataset widget #427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scilog/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@ typings/

# Cache used by TypeScript's incremental build
*.tsbuildinfo

.vscode
13 changes: 13 additions & 0 deletions scilog/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions scilog/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"@angular-devkit/build-angular": "^15.2.11",
"@angular/cli": "^15.2.11",
"@angular/compiler-cli": "^15.2.10",
"@scicatproject/scicat-sdk-ts-fetch": "^4.13.0",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
Expand Down
13 changes: 12 additions & 1 deletion scilog/src/app/app-config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@ export interface Oauth2Endpoint {
displayImage?: string,
tooltipText?: string,
}
export interface ScicatSettings {
scicatWidgetEnabled: boolean;
lbBaseURL: string;
frontendBaseURL: string;
}

export interface AppConfig {
lbBaseURL?: string;
oAuth2Endpoint?: Oauth2Endpoint;
help?: string;
scicat?: ScicatSettings;
}

@Injectable()
Expand All @@ -24,11 +31,15 @@ export class AppConfigService {
try {
this.appConfig = await this.http.get("/assets/config.json").toPromise();
} catch (err) {
console.error("No config provided, applying defaults");
console.error("No config provided, applying defaults", err);
}
}

getConfig(): AppConfig {
return this.appConfig as AppConfig;
}

getScicatSettings(): ScicatSettings | undefined {
return (this.appConfig as AppConfig).scicat;
}
}
2 changes: 2 additions & 0 deletions scilog/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import { ViewSettingsComponent } from '@shared/settings/view-settings/view-setti
import { ProfileSettingsComponent } from '@shared/settings/profile-settings/profile-settings.component';
import { DownloadComponent } from '@shared/download/download.component';
import { NavigationGuardService } from './logbook/core/navigation-guard-service';
import { AuthCallbackComponent } from './auth-callback/auth-callback.component';

const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'auth-callback', component: AuthCallbackComponent },
{ path: 'overview', component: OverviewComponent },
{ path: 'download/:fileId', component: DownloadComponent },
{ path: 'logbooks/:logbookId', component: LogbookComponent,
Expand Down
6 changes: 5 additions & 1 deletion scilog/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { OverviewScrollComponent } from './overview/overview-scroll/overview-scroll.component';
import { ActionsMenuComponent } from './overview/actions-menu/actions-menu.component';
import { ScicatViewerComponent } from './logbook/widgets/scicat-viewer/scicat-viewer.component';
import { AuthCallbackComponent } from './auth-callback/auth-callback.component';

const appConfigInitializerFn = (appConfig: AppConfigService) => {
return () => appConfig.loadAppConfig();
Expand Down Expand Up @@ -135,7 +137,9 @@ const appConfigInitializerFn = (appConfig: AppConfigService) => {
ResizedDirective,
OverviewTableComponent,
OverviewScrollComponent,
ActionsMenuComponent
ActionsMenuComponent,
ScicatViewerComponent,
AuthCallbackComponent
],
imports: [
BrowserModule,
Expand Down
Empty file.
1 change: 1 addition & 0 deletions scilog/src/app/auth-callback/auth-callback.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>auth-callback works!</p>
52 changes: 52 additions & 0 deletions scilog/src/app/auth-callback/auth-callback.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthCallbackComponent } from './auth-callback.component';
import { provideRouter, Router } from '@angular/router';
import { Component } from '@angular/core';

@Component({})
class DummyComponent {}

describe('AuthCallbackComponent', () => {
let component: AuthCallbackComponent;
let fixture: ComponentFixture<AuthCallbackComponent>;
let router: Router;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AuthCallbackComponent],
providers: [
provideRouter([
{ path: 'overview', component: DummyComponent },
{ path: 'auth-callback', component: AuthCallbackComponent },
{ path: 'dashboard', component: DummyComponent },
]),
],
}).compileComponents();

fixture = TestBed.createComponent(AuthCallbackComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router);
});

it('should create', () => {
expect(component).toBeTruthy();
});

it('should set scicat token and redirect to returnUrl', async () => {
const routerSpy = spyOn(router, 'navigateByUrl').and.callThrough();
await router.navigateByUrl(
'/auth-callback?access-token=123&returnUrl=/dashboard'
);
fixture.detectChanges();
expect(localStorage.getItem('scicat_token')).toEqual('123');
expect(routerSpy).toHaveBeenCalledWith('/dashboard');
localStorage.removeItem('scicat_token');
});

it('should should redirect to overview if no returnUrl', async () => {
const routerSpy = spyOn(router, 'navigate').and.callThrough();
await router.navigateByUrl('/auth-callback?access-token=123');
fixture.detectChanges();
expect(routerSpy).toHaveBeenCalledWith(['/overview']);
});
});
36 changes: 36 additions & 0 deletions scilog/src/app/auth-callback/auth-callback.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-auth-callback',
template: '',
styles: [],
})
export class AuthCallbackComponent implements OnInit, OnDestroy {
constructor(private route: ActivatedRoute, private router: Router) {}

subscriptions: Subscription[] = [];

ngOnInit(): void {
const sub = this.route.queryParams.subscribe((params) => {
const token = params['access-token'];
const returnUrl = params['returnUrl'];

if (token) {
localStorage.setItem('scicat_token', token);
}

if (returnUrl) {
this.router.navigateByUrl(returnUrl);
} else {
this.router.navigate(['/overview']);
}
});
this.subscriptions.push(sub);
}

ngOnDestroy(): void {
this.subscriptions.forEach((sub) => sub.unsubscribe());
}
}
57 changes: 52 additions & 5 deletions scilog/src/app/core/auth-services/auth.interceptor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,63 @@
import { TestBed } from '@angular/core/testing';

import { AuthInterceptor } from './auth.interceptor';
import { ServerSettingsService } from '@shared/config/server-settings.service';
import { HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { of } from 'rxjs';

describe('AuthInterceptor', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
AuthInterceptor
]
}));
const serverSettingsService = jasmine.createSpyObj('ServerSettingsService', [
'getSciCatServerAddress',
]);
serverSettingsService.getSciCatServerAddress.and.returnValue(
'https://scicat-backend.psi.ch'
);
beforeEach(() =>
TestBed.configureTestingModule({
providers: [
AuthInterceptor,
{ provide: ServerSettingsService, useValue: serverSettingsService },
],
})
);

it('should be created', () => {
const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
expect(interceptor).toBeTruthy();
});

it('should append scicat token if request to scicat backend', (done: DoneFn) => {
localStorage.setItem('scicat_token', 'test_scicat_token');
const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
const req = new HttpRequest("GET", 'https://scicat-backend.psi.ch/api/v3/datasets');
const next = jasmine.createSpyObj<HttpHandler>('HttpHandler', ['handle']);
next.handle.and.returnValue(of({} as HttpEvent<any>));
interceptor.intercept(req, next).subscribe({
next: (_httpEvent: HttpEvent<any>) => {
const reqArg = next.handle.calls.mostRecent().args[0];
expect(reqArg.headers.get('Authorization')).toBe('Bearer test_scicat_token');
localStorage.clear();
done();
},
error: done.fail,
});
});

it('should append scilog token if request is not to scicat backend', (done: DoneFn) => {
localStorage.setItem('id_token', 'test_scilog_token');
const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
const req = new HttpRequest("GET", 'https://scilog-backend.psi.ch/api/v1');
const next = jasmine.createSpyObj<HttpHandler>('HttpHandler', ['handle']);
next.handle.and.returnValue(of({} as HttpEvent<any>));
interceptor.intercept(req, next).subscribe({
next: (_httpEvent: HttpEvent<any>) => {
const reqArg = next.handle.calls.mostRecent().args[0];
expect(reqArg.headers.get('Authorization')).toBe('Bearer test_scilog_token');
localStorage.clear();
done();
},
error: done.fail,
});
});
});

87 changes: 57 additions & 30 deletions scilog/src/app/core/auth-services/auth.interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,84 @@
import { Injectable } from '@angular/core';
import { inject, Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse
HttpErrorResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ServerSettingsService } from '@shared/config/server-settings.service';

function logout() {
localStorage.removeItem("id_token");
localStorage.removeItem('id_token');
localStorage.removeItem('id_session');
localStorage.removeItem('scicat_token');
sessionStorage.removeItem('scilog-auto-selection-logbook');
location.href = '/login';
};

function handle_request(handler: HttpHandler, req: HttpRequest<any>) {
return handler.handle(req).pipe(tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// console.log(cloned);
// console.log("Service Response thr Interceptor");
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
console.log("err.status", err);
if (err.status === 401) {
logout();
}
}
}));
}

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private serverSettingsService = inject(ServerSettingsService);

intercept(req: HttpRequest<any>,
next: HttpHandler): Observable<HttpEvent<any>> {
private isRequestToSciCatBackend(req_url: string): boolean {
try {
const origin = new URL(req_url).origin;
return (
origin ===
new URL(this.serverSettingsService.getSciCatServerAddress()).origin
);
} catch (err) {
// new URL(...) fails for request to static assets (e.g. /assets/config.json)
return false;
}
}

const idToken = localStorage.getItem("id_token");
private handle_request(handler: HttpHandler, req: HttpRequest<any>) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not super convinced the login to scicat should be part of the interceptor, rather than invoked at component creation of the scicat widget

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed offline, the interceptor handles the case of SciCat session timing out, and re-logging in the user. As this logic is needed in the interceptor anyway, we let the interceptor also handle the initial login.

return handler.handle(req).pipe(
tap({
next: (event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// console.log(cloned);
// console.log("Service Response thr Interceptor");
}
},
error: (err: any) => {
if (err instanceof HttpErrorResponse) {
console.log('err.status', err);
if (err.status === 401) {
if (!this.isRequestToSciCatBackend(err.url)) {
logout();
} else {
const returnURL = window.location.pathname + window.location.search;
window.location.href = this.serverSettingsService.getScicatLoginUrl(returnURL);
}
}
}
},
})
);
}

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let idToken = '';
if (this.isRequestToSciCatBackend(req.url)) {
idToken = localStorage.getItem('scicat_token');
} else {
idToken = localStorage.getItem('id_token');
}
if (idToken) {
const cloned = req.clone({
headers: req.headers.set("Authorization",
"Bearer " + idToken)
headers: req.headers.set('Authorization', 'Bearer ' + idToken),
});

return handle_request(next, cloned);

}
else {
return handle_request(next, req);
return this.handle_request(next, cloned);
} else {
return this.handle_request(next, req);
}
}
}
1 change: 1 addition & 0 deletions scilog/src/app/core/auth-services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export class AuthService {
logout() {
localStorage.removeItem("id_token");
localStorage.removeItem('id_session');
localStorage.removeItem('scicat_token');
sessionStorage.removeItem('scilog-auto-selection-logbook');
this.forceReload=true;
}
Expand Down
Loading