From 868b7ad37bbcb49183c992194556b27715444c35 Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Mon, 25 Jan 2021 15:46:21 +0100 Subject: [PATCH 1/9] 76150: Add a bitstream download page --- docs/Configuration.md | 66 -------- .../bitstream-page-routing.module.ts | 8 + .../full-file-section.component.html | 4 +- .../file-section/file-section.component.html | 2 +- .../data/feature-authorization/feature-id.ts | 1 + .../core/metadata/metadata.service.spec.ts | 8 +- src/app/core/metadata/metadata.service.ts | 10 +- .../detail/process-detail.component.html | 2 +- .../bitstream-download-page.component.html | 3 + .../bitstream-download-page.component.spec.ts | 158 ++++++++++++++++++ .../bitstream-download-page.component.ts | 83 +++++++++ .../file-download-link.component.html | 4 +- .../file-download-link.component.spec.ts | 35 ++-- .../file-download-link.component.ts | 26 ++- src/app/shared/shared.module.ts | 10 ++ src/assets/i18n/en.json5 | 4 + 16 files changed, 308 insertions(+), 116 deletions(-) create mode 100644 src/app/shared/bitstream-download-page/bitstream-download-page.component.html create mode 100644 src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts create mode 100644 src/app/shared/bitstream-download-page/bitstream-download-page.component.ts diff --git a/docs/Configuration.md b/docs/Configuration.md index f918622568..f4fff1166c 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -64,69 +64,3 @@ In order to start using one of these services, select it from the [Angulartics P The Google Analytics script was added in [`main.browser.ts`](https://github.com/DSpace/dspace-angular/blob/ff04760f4af91ac3e7add5e7424a46cb2439e874/src/main.browser.ts#L33) instead of the `` tag in `index.html` to ensure events get sent when the page is shown in a client's browser, and not when it's rendered on the universal server. Likely you'll want to do the same when adding a new service. -## SEO when hosting REST Api and UI on different servers - -Indexers such as Google Scholar require that files are hosted on the same domain as the page that links them. In DSpace 7, Bitstreams are served from the REST server. So if you use different servers for the REST api and the UI you'll want to ensure that Bitstream downloads are proxied through the UI server. - -In order to achieve this we'll need to do two things: -- **Proxy the Bitstream downloads through the UI server.** You'll need to put a webserver such as httpd or nginx in front of the UI server in order to achieve this. [Below](#apache-http-server-config) you'll find a section explaining how to do it in httpd. -- **Update the URLs for Bitstream downloads to match the UI server.** This can be done using a setting in the UI environment file. - -### UI config -If you set the property `rewriteDownloadUrls` to `true` in your `environment.prod.ts` file, the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) of any download URL will be replaced by the origin of the UI. This will also happen for the `citation_pdf_url` `` tag on Item pages. - -The app will determine the UI origin currently in use, so the external UI URL doesn't need to be configured anywhere and rewrites will still work if you host the UI from multiple domains. - -### Apache HTTP Server config - -#### Basics -In order to be able to host bitstreams from the UI Server you'll need to enable mod_proxy and add the following to the httpd config of your UI server: - -``` -ProxyPassMatch "/server/api/core/bitstreams/([^/]+)/content" "http://rest.api/server/api/core/bitstreams/$1/content" -ProxyPassReverse "/server/api/core/bitstreams/([^/]+)/content" "http://rest.api/server/api/core/bitstreams/$1/content" -``` - -Replace http://rest.api in with the correct origin for your REST server. - -The `ProxyPassMatch` line forwards all requests matching the regular expression for a bitstream download URL to the corresponding path on the REST server - -The `ProxyPassReverse` ensures that if the REST server were to return redirect response, httpd would also swap out its hostname for the hostname of the UI before forwarding the response to the client. - -#### Using HTTPS -If your REST server uses https, you'll need to enable mod_ssl and ensure `SSLProxyEngine on` is part of your UI server's httpd config as well - -If the UI hostname doesn't match the CN in the SSL certificate of the REST server (which is likely if they're on different domains), you'll also need to add the following lines - -``` -SSLProxyCheckPeerCN off -SSLProxyCheckPeerName off -``` -These are two names for [the same directive](https://httpd.apache.org/docs/trunk/mod/mod_ssl.html#sslproxycheckpeername) that have been used for various versions of httpd, old versions need the former, then some in-between versions need both, and newer versions only need the latter. Keeping them both doesn't harm anything. - -So the entire config becomes: - -``` -SSLProxyEngine on -SSLProxyCheckPeerCN off -SSLProxyCheckPeerName off -ProxyPassMatch "/server/api/core/bitstreams/([^/]+)/content" "https://rest.api/server/api/core/bitstreams/$1/content" -ProxyPassReverse "/server/api/core/bitstreams/([^/]+)/content" "https://rest.api/server/api/core/bitstreams/$1/content" -``` - -If you don't want httpd to verify the certificate of the REST server, you can also turn all checks off with the following config: - -``` -SSLProxyEngine on -SSLProxyVerify none -SSLProxyCheckPeerCN off -SSLProxyCheckPeerName off -SSLProxyCheckPeerExpire off -ProxyPassMatch "/server/api/core/bitstreams/([^/]+)/content" "https://rest.api/server/api/core/bitstreams/$1/content" -ProxyPassReverse "/server/api/core/bitstreams/([^/]+)/content" "https://rest.api/server/api/core/bitstreams/$1/content" -``` - - - - - diff --git a/src/app/+bitstream-page/bitstream-page-routing.module.ts b/src/app/+bitstream-page/bitstream-page-routing.module.ts index 14d688064c..bbbd65f279 100644 --- a/src/app/+bitstream-page/bitstream-page-routing.module.ts +++ b/src/app/+bitstream-page/bitstream-page-routing.module.ts @@ -3,6 +3,7 @@ import { RouterModule } from '@angular/router'; import { EditBitstreamPageComponent } from './edit-bitstream-page/edit-bitstream-page.component'; import { AuthenticatedGuard } from '../core/auth/authenticated.guard'; import { BitstreamPageResolver } from './bitstream-page.resolver'; +import { BitstreamDownloadPageComponent } from '../shared/bitstream-download-page/bitstream-download-page.component'; const EDIT_BITSTREAM_PATH = ':id/edit'; @@ -12,6 +13,13 @@ const EDIT_BITSTREAM_PATH = ':id/edit'; @NgModule({ imports: [ RouterModule.forChild([ + { + path:':id/download', + component: BitstreamDownloadPageComponent, + resolve: { + bitstream: BitstreamPageResolver + }, + }, { path: EDIT_BITSTREAM_PATH, component: EditBitstreamPageComponent, diff --git a/src/app/+item-page/full/field-components/file-section/full-file-section.component.html b/src/app/+item-page/full/field-components/file-section/full-file-section.component.html index 00218b66d1..a054d58bf5 100644 --- a/src/app/+item-page/full/field-components/file-section/full-file-section.component.html +++ b/src/app/+item-page/full/field-components/file-section/full-file-section.component.html @@ -34,7 +34,7 @@
- + {{"item.page.filesection.download" | translate}}
@@ -76,7 +76,7 @@
- + {{"item.page.filesection.download" | translate}}
diff --git a/src/app/+item-page/simple/field-components/file-section/file-section.component.html b/src/app/+item-page/simple/field-components/file-section/file-section.component.html index 1fdee6dc4d..0fa5daa012 100644 --- a/src/app/+item-page/simple/field-components/file-section/file-section.component.html +++ b/src/app/+item-page/simple/field-components/file-section/file-section.component.html @@ -1,7 +1,7 @@
- + {{file?.name}} ({{(file?.sizeBytes) | dsFileSize }}) diff --git a/src/app/core/data/feature-authorization/feature-id.ts b/src/app/core/data/feature-authorization/feature-id.ts index e3473a895e..dbdd794665 100644 --- a/src/app/core/data/feature-authorization/feature-id.ts +++ b/src/app/core/data/feature-authorization/feature-id.ts @@ -12,4 +12,5 @@ export enum FeatureID { CanManageGroups = 'canManageGroups', IsCollectionAdmin = 'isCollectionAdmin', IsCommunityAdmin = 'isCommunityAdmin', + CanDownload = 'canDownload', } diff --git a/src/app/core/metadata/metadata.service.spec.ts b/src/app/core/metadata/metadata.service.spec.ts index 25165aba79..043bc3cc05 100644 --- a/src/app/core/metadata/metadata.service.spec.ts +++ b/src/app/core/metadata/metadata.service.spec.ts @@ -181,11 +181,7 @@ describe('MetadataService', () => { Meta, Title, // tslint:disable-next-line:no-empty - { provide: ItemDataService, useValue: { findById: () => { } } }, - { - provide: HardRedirectService, - useValue: { rewriteDownloadURL: (a) => a, getRequestOrigin: () => environment.ui.baseUrl } - }, + { provide: ItemDataService, useValue: { findById: () => {} } }, BrowseService, MetadataService ], @@ -225,7 +221,7 @@ describe('MetadataService', () => { tick(); expect(tagStore.get('citation_dissertation_name')[0].content).toEqual('Test PowerPoint Document'); expect(tagStore.get('citation_dissertation_institution')[0].content).toEqual('Mock Publisher'); - expect(tagStore.get('citation_abstract_html_url')[0].content).toEqual(new URLCombiner(environment.ui.baseUrl, router.url).toString()); + expect(tagStore.get('citation_abstract_html_url')[0].content).toEqual([environment.ui.baseUrl, router.url].join('')); expect(tagStore.get('citation_pdf_url')[0].content).toEqual('https://dspace7.4science.it/dspace-spring-rest/api/core/bitstreams/99b00f3c-1cc6-4689-8158-91965bee6b28/content'); })); diff --git a/src/app/core/metadata/metadata.service.ts b/src/app/core/metadata/metadata.service.ts index dac0a787fb..eed4228683 100644 --- a/src/app/core/metadata/metadata.service.ts +++ b/src/app/core/metadata/metadata.service.ts @@ -1,4 +1,4 @@ -import { Injectable } from '@angular/core'; +import { Inject, Injectable } from '@angular/core'; import { Meta, MetaDefinition, Title } from '@angular/platform-browser'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; @@ -20,8 +20,7 @@ import { Bitstream } from '../shared/bitstream.model'; import { DSpaceObject } from '../shared/dspace-object.model'; import { Item } from '../shared/item.model'; import { getFirstSucceededRemoteDataPayload, getFirstSucceededRemoteListPayload } from '../shared/operators'; -import { HardRedirectService } from '../services/hard-redirect.service'; -import { URLCombiner } from '../url-combiner/url-combiner'; +import { environment } from '../../../environments/environment'; import { RootDataService } from '../data/root-data.service'; @Injectable() @@ -262,7 +261,7 @@ export class MetadataService { */ private setCitationAbstractUrlTag(): void { if (this.currentObject.value instanceof Item) { - const value = new URLCombiner(this.redirectService.getRequestOrigin(), this.router.url).toString(); + const value = [environment.ui.baseUrl, this.router.url].join(''); this.addMetaTag('citation_abstract_html_url', value); } } @@ -287,8 +286,7 @@ export class MetadataService { getFirstSucceededRemoteDataPayload() ).subscribe((format: BitstreamFormat) => { if (format.mimetype === 'application/pdf') { - const rewrittenURL= this.redirectService.rewriteDownloadURL(bitstream._links.content.href); - this.addMetaTag('citation_pdf_url', rewrittenURL); + this.addMetaTag('citation_pdf_url', bitstream._links.content.href); } }); } diff --git a/src/app/process-page/detail/process-detail.component.html b/src/app/process-page/detail/process-detail.component.html index d59f93254e..ef099d4f9f 100644 --- a/src/app/process-page/detail/process-detail.component.html +++ b/src/app/process-page/detail/process-detail.component.html @@ -15,7 +15,7 @@
- + {{getFileName(file)}} ({{(file?.sizeBytes) | dsFileSize }}) diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.html b/src/app/shared/bitstream-download-page/bitstream-download-page.component.html new file mode 100644 index 0000000000..183449fc5e --- /dev/null +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.html @@ -0,0 +1,3 @@ +
+

{{'bitstream.download.page' | translate:{bitstream: (bitstream$ | async)?.name} }}

+
diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts b/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts new file mode 100644 index 0000000000..ca5a079faa --- /dev/null +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts @@ -0,0 +1,158 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { AuthService } from '../../core/auth/auth.service'; +import { FileService } from '../../core/shared/file.service'; +import { of as observableOf } from 'rxjs'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { BitstreamDownloadPageComponent } from './bitstream-download-page.component'; +import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { createSuccessfulRemoteDataObject } from '../remote-data.utils'; +import { ActivatedRoute, Router } from '@angular/router'; +import { getForbiddenRoute } from '../../app-routing-paths'; +import { TranslateModule } from '@ngx-translate/core'; +import { CommonModule } from '@angular/common'; + +describe('BitstreamDownloadPageComponent', () => { + let component: BitstreamDownloadPageComponent; + let fixture: ComponentFixture; + + let authService: AuthService; + let fileService: FileService; + let authorizationService: AuthorizationDataService; + let hardRedirectService: HardRedirectService; + let activatedRoute; + let router; + + let bitstream: Bitstream; + + function init() { + authService = jasmine.createSpyObj('authService', { + isAuthenticated: observableOf(true), + setRedirectUrl: {} + }); + authorizationService = jasmine.createSpyObj('authorizationSerivice', { + isAuthorized: observableOf(true) + }); + + fileService = jasmine.createSpyObj('fileService', { + downloadFile: observableOf('content-url-with-headers') + }); + + hardRedirectService = jasmine.createSpyObj('fileService', { + redirect: {} + }); + bitstream = Object.assign(new Bitstream(), { + uuid: 'bitstreamUuid', + _links: { + content: {href: 'bitstream-content-link'}, + self: {href: 'bitstream-self-link'}, + } + }); + + activatedRoute = { + data: observableOf({ + bitstream: createSuccessfulRemoteDataObject( + bitstream + ) + }) + }; + + router = jasmine.createSpyObj('router', ['navigateByUrl']); + } + + function initTestbed() { + TestBed.configureTestingModule({ + imports: [CommonModule, TranslateModule.forRoot()], + declarations: [BitstreamDownloadPageComponent], + providers: [ + {provide: ActivatedRoute, useValue: activatedRoute}, + {provide: Router, useValue: router}, + {provide: AuthorizationDataService, useValue: authorizationService}, + {provide: AuthService, useValue: authService}, + {provide: FileService, useValue: fileService}, + {provide: HardRedirectService, useValue: hardRedirectService}, + ] + }) + .compileComponents(); + } + + describe('init', () => { + beforeEach(async(() => { + init(); + initTestbed(); + })); + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + it('should init the comp', () => { + expect(component).toBeTruthy(); + }); + }); + + describe('bitstream retrieval', () => { + describe('when the user is authorized and not logged in', () => { + beforeEach(async(() => { + init(); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(false)); + + initTestbed(); + })); + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + it('should redirect to the content link', () => { + expect(hardRedirectService.redirect).toHaveBeenCalledWith('bitstream-content-link'); + }); + }); + describe('when the user is authorized and logged in', () => { + beforeEach(async(() => { + init(); + initTestbed(); + })); + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + it('should redirect to an updated content link', () => { + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + }); + }); + describe('when the user is not authorized and logged in', () => { + beforeEach(async(() => { + init(); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(false)); + initTestbed(); + })); + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + it('should navigate to the forbidden route', () => { + expect(router.navigateByUrl).toHaveBeenCalledWith(getForbiddenRoute(), {skipLocationChange: true}); + }); + }); + describe('when the user is not authorized and not logged in', () => { + beforeEach(async(() => { + init(); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(false)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(false)); + initTestbed(); + })); + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + it('should navigate to the login page', () => { + expect(authService.setRedirectUrl).toHaveBeenCalled(); + expect(router.navigateByUrl).toHaveBeenCalledWith('login'); + }); + }); + }); +}); diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts new file mode 100644 index 0000000000..ccaec76751 --- /dev/null +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts @@ -0,0 +1,83 @@ +import { Component, OnDestroy, OnInit } from '@angular/core'; +import { map } from 'rxjs/operators'; +import { ActivatedRoute, Router } from '@angular/router'; +import { Subscription } from 'rxjs/internal/Subscription'; +import { hasValue, isNotEmpty } from '../empty.util'; +import { getRemoteDataPayload, redirectOn4xx } from '../../core/shared/operators'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; +import { FeatureID } from '../../core/data/feature-authorization/feature-id'; +import { AuthService } from '../../core/auth/auth.service'; +import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; +import { FileService } from '../../core/shared/file.service'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { getForbiddenRoute } from '../../app-routing-paths'; +import { RemoteData } from '../../core/data/remote-data'; +import { tap } from 'rxjs/internal/operators/tap'; + +@Component({ + selector: 'ds-bitstream-download-page', + templateUrl: './bitstream-download-page.component.html' +}) +/** + * Page component for downloading a bitstream + */ +export class BitstreamDownloadPageComponent implements OnInit, OnDestroy { + + bitstream$: Observable; + bitstreamRD$: Observable>; + + subs: Subscription[] = []; + + constructor( + private route: ActivatedRoute, + protected router: Router, + private authorizationService: AuthorizationDataService, + private auth: AuthService, + private fileService: FileService, + private hardRedirectService: HardRedirectService, + ) { + + } + + ngOnInit(): void { + + this.bitstreamRD$ = this.route.data.pipe( + map((data) => data.bitstream)); + + this.bitstream$ = this.bitstreamRD$.pipe( + tap((v) => console.log('dfdf', v)), + redirectOn4xx(this.router, this.auth), + getRemoteDataPayload() + ); + + this.subs.push(this.bitstream$.subscribe((bitstream) => { + const isAuthorized$ = this.authorizationService.isAuthorized(FeatureID.CanDownload, isNotEmpty(bitstream) ? bitstream.self : undefined); + const isLoggedIn$ = this.auth.isAuthenticated(); + + this.subs.push(observableCombineLatest(isAuthorized$, isLoggedIn$) + .subscribe(([isAuthorized, isLoggedIn]) => { + if (isAuthorized && isLoggedIn) { + const fileLink$ = this.fileService.downloadFile(bitstream._links.content.href); + this.subs.push(fileLink$.subscribe((fileLink) => { + this.hardRedirectService.redirect(fileLink); + })); + } else if (isAuthorized && !isLoggedIn) { + this.hardRedirectService.redirect(bitstream._links.content.href); + } else if (!isAuthorized && isLoggedIn) { + this.router.navigateByUrl(getForbiddenRoute(), {skipLocationChange: true}); + } else if (!isAuthorized && !isLoggedIn) { + this.auth.setRedirectUrl(this.router.url); + this.router.navigateByUrl('login'); + } + })); + })); + + } + + ngOnDestroy(): void { + this.subs + .filter((subscription) => hasValue(subscription)) + .forEach((subscription) => subscription.unsubscribe()); + } +} diff --git a/src/app/shared/file-download-link/file-download-link.component.html b/src/app/shared/file-download-link/file-download-link.component.html index 06624c8b40..f1843da5c6 100644 --- a/src/app/shared/file-download-link/file-download-link.component.html +++ b/src/app/shared/file-download-link/file-download-link.component.html @@ -1,5 +1,5 @@ - - + + diff --git a/src/app/shared/file-download-link/file-download-link.component.spec.ts b/src/app/shared/file-download-link/file-download-link.component.spec.ts index 4f3c17402f..53f39b104e 100644 --- a/src/app/shared/file-download-link/file-download-link.component.spec.ts +++ b/src/app/shared/file-download-link/file-download-link.component.spec.ts @@ -3,7 +3,10 @@ import { FileDownloadLinkComponent } from './file-download-link.component'; import { AuthService } from '../../core/auth/auth.service'; import { FileService } from '../../core/shared/file.service'; import { of as observableOf } from 'rxjs'; -import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { By } from '@angular/platform-browser'; +import { URLCombiner } from '../../core/url-combiner/url-combiner'; +import { getBitstreamModuleRoute } from '../../app-routing-paths'; describe('FileDownloadLinkComponent', () => { let component: FileDownloadLinkComponent; @@ -11,14 +14,16 @@ describe('FileDownloadLinkComponent', () => { let authService: AuthService; let fileService: FileService; - let href: string; + let bitstream: Bitstream; function init() { authService = jasmine.createSpyObj('authService', { isAuthenticated: observableOf(true) }); fileService = jasmine.createSpyObj('fileService', ['downloadFile']); - href = 'test-download-file-link'; + bitstream = Object.assign(new Bitstream(), { + uuid: 'bitstreamUuid', + }); } beforeEach(waitForAsync(() => { @@ -28,7 +33,6 @@ describe('FileDownloadLinkComponent', () => { providers: [ { provide: AuthService, useValue: authService }, { provide: FileService, useValue: fileService }, - { provide: HardRedirectService, useValue: { rewriteDownloadURL: (a) => a } }, ] }) .compileComponents(); @@ -37,23 +41,22 @@ describe('FileDownloadLinkComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(FileDownloadLinkComponent); component = fixture.componentInstance; - component.href = href; + component.bitstream = bitstream; fixture.detectChanges(); }); - describe('downloadFile', () => { - let result; + describe('init', () => { - beforeEach(() => { - result = component.downloadFile(); - }); + describe('getBitstreamPath', () => { + it('should set the bitstreamPath based on the input bitstream', () => { + expect(component.bitstreamPath).toEqual(new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString()); + }); + }) - it('should call fileService.downloadFile with the provided href', () => { - expect(fileService.downloadFile).toHaveBeenCalledWith(href); - }); + it('should init the component', () => { + const link = fixture.debugElement.query(By.css('a')).nativeElement; + expect(link.href).toContain(new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString()); + }) - it('should return false', () => { - expect(result).toEqual(false); - }); }); }); diff --git a/src/app/shared/file-download-link/file-download-link.component.ts b/src/app/shared/file-download-link/file-download-link.component.ts index f9861cd997..8a1fbd6e0e 100644 --- a/src/app/shared/file-download-link/file-download-link.component.ts +++ b/src/app/shared/file-download-link/file-download-link.component.ts @@ -2,7 +2,9 @@ import { Component, Input, OnInit } from '@angular/core'; import { FileService } from '../../core/shared/file.service'; import { Observable } from 'rxjs'; import { AuthService } from '../../core/auth/auth.service'; -import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { getBitstreamModuleRoute } from '../../app-routing-paths'; +import { URLCombiner } from '../../core/url-combiner/url-combiner'; @Component({ selector: 'ds-file-download-link', @@ -15,15 +17,12 @@ import { HardRedirectService } from '../../core/services/hard-redirect.service'; * ensuring the user is authorized to download the file. */ export class FileDownloadLinkComponent implements OnInit { - /** - * Href to link to - */ - @Input() href: string; /** - * Optional file name for the download + * Optional bitstream instead of href and file name */ - @Input() download: string; + @Input() bitstream: Bitstream; + bitstreamPath: string; /** * Whether or not the current user is authenticated @@ -32,20 +31,15 @@ export class FileDownloadLinkComponent implements OnInit { constructor(private fileService: FileService, private authService: AuthService, - private redirectService: HardRedirectService) { + ) { } ngOnInit() { this.isAuthenticated$ = this.authService.isAuthenticated(); - this.href = this.redirectService.rewriteDownloadURL(this.href); + this.bitstreamPath = this.getBitstreamPath(); } - /** - * Start a download of the file - * Return false to ensure the original href is displayed when the user hovers over the link - */ - downloadFile(): boolean { - this.fileService.downloadFile(this.href); - return false; + getBitstreamPath() { + return new URLCombiner(getBitstreamModuleRoute(), this.bitstream.uuid, 'download').toString(); } } diff --git a/src/app/shared/shared.module.ts b/src/app/shared/shared.module.ts index e9f9d69918..4de0f2901e 100644 --- a/src/app/shared/shared.module.ts +++ b/src/app/shared/shared.module.ts @@ -223,6 +223,7 @@ import { SearchObjects } from './search/search-objects.model'; import { SearchResult } from './search/search-result.model'; import { FacetConfigResponse } from './search/facet-config-response.model'; import { FacetValues } from './search/facet-values.model'; +import { BitstreamDownloadPageComponent } from './bitstream-download-page/bitstream-download-page.component'; import { GenericItemPageFieldComponent } from '../+item-page/simple/field-components/specific-field/generic/generic-item-page-field.component'; import { MetadataRepresentationListComponent } from '../+item-page/simple/metadata-representation-list/metadata-representation-list.component'; import { RelatedItemsComponent } from '../+item-page/simple/related-items/related-items-component'; @@ -432,6 +433,7 @@ const COMPONENTS = [ EpersonSearchBoxComponent, GroupSearchBoxComponent, FileDownloadLinkComponent, + BitstreamDownloadPageComponent, CollectionDropdownComponent, ExportMetadataSelectorComponent, ConfirmationModalComponent, @@ -510,6 +512,14 @@ const ENTRY_COMPONENTS = [ ClaimedTaskActionsRejectComponent, ClaimedTaskActionsReturnToPoolComponent, ClaimedTaskActionsEditMetadataComponent, + CollectionDropdownComponent, + FileDownloadLinkComponent, + BitstreamDownloadPageComponent, + CurationFormComponent, + ExportMetadataSelectorComponent, + ConfirmationModalComponent, + VocabularyTreeviewComponent, + SidebarSearchListElementComponent, PublicationSidebarSearchListElementComponent, CollectionSidebarSearchListElementComponent, CommunitySidebarSearchListElementComponent, diff --git a/src/assets/i18n/en.json5 b/src/assets/i18n/en.json5 index 2924a3a47e..1b9e252922 100644 --- a/src/assets/i18n/en.json5 +++ b/src/assets/i18n/en.json5 @@ -526,6 +526,10 @@ + "bitstream.download.page": "Now downloading {{bitstream}}..." , + + + "bitstream.edit.bitstream": "Bitstream: ", "bitstream.edit.form.description.hint": "Optionally, provide a brief description of the file, for example \"Main article\" or \"Experiment data readings\".", From 3137f3e6c11001b39acca9d0531718ca6b7fd257 Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Fri, 29 Jan 2021 11:05:13 +0100 Subject: [PATCH 2/9] 76150: Implement feedback --- src/app/core/shared/file.service.ts | 14 ++-- .../bitstream-download-page.component.spec.ts | 2 +- .../bitstream-download-page.component.ts | 71 ++++++++++--------- .../item-detail-preview.component.ts | 2 +- .../section-upload-file.component.spec.ts | 4 +- .../file/section-upload-file.component.ts | 2 +- 6 files changed, 48 insertions(+), 47 deletions(-) diff --git a/src/app/core/shared/file.service.ts b/src/app/core/shared/file.service.ts index fcbd86161a..98c468e9a3 100644 --- a/src/app/core/shared/file.service.ts +++ b/src/app/core/shared/file.service.ts @@ -1,10 +1,11 @@ import { Inject, Injectable } from '@angular/core'; import { RawRestResponse } from '../dspace-rest/raw-rest-response.model'; import { AuthService } from '../auth/auth.service'; -import { take } from 'rxjs/operators'; +import { map, take } from 'rxjs/operators'; import { NativeWindowRef, NativeWindowService } from '../services/window.service'; import { URLCombiner } from '../url-combiner/url-combiner'; import { hasValue } from '../../shared/empty.util'; +import { Observable } from 'rxjs/internal/Observable'; /** * Provides utility methods to save files on the client-side. @@ -17,17 +18,16 @@ export class FileService { ) { } /** - * Combines an URL with a short-lived token and sets the current URL to the newly created one + * Combines an URL with a short-lived token and sets the current URL to the newly created one and returns it * * @param url * file url */ - downloadFile(url: string) { - this.authService.getShortlivedToken().pipe(take(1)).subscribe((token) => { - this._window.nativeWindow.location.href = hasValue(token) ? new URLCombiner(url, `?authentication-token=${token}`).toString() : url; - }); + retrieveFileDownloadLink(url: string): Observable { + return this.authService.getShortlivedToken().pipe(take(1), map((token) => + hasValue(token) ? new URLCombiner(url, `?authentication-token=${token}`).toString() : url + )); } - /** * Derives file name from the http response * by looking inside content-disposition diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts b/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts index ca5a079faa..2803a7f789 100644 --- a/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.spec.ts @@ -35,7 +35,7 @@ describe('BitstreamDownloadPageComponent', () => { }); fileService = jasmine.createSpyObj('fileService', { - downloadFile: observableOf('content-url-with-headers') + retrieveFileDownloadLink: observableOf('content-url-with-headers') }); hardRedirectService = jasmine.createSpyObj('fileService', { diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts index ccaec76751..5b82928a64 100644 --- a/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts @@ -1,19 +1,17 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; -import { map } from 'rxjs/operators'; +import { Component, OnInit } from '@angular/core'; +import { filter, map, switchMap, take } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; -import { Subscription } from 'rxjs/internal/Subscription'; import { hasValue, isNotEmpty } from '../empty.util'; import { getRemoteDataPayload, redirectOn4xx } from '../../core/shared/operators'; import { Bitstream } from '../../core/shared/bitstream.model'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { AuthService } from '../../core/auth/auth.service'; -import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; +import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs'; import { FileService } from '../../core/shared/file.service'; import { HardRedirectService } from '../../core/services/hard-redirect.service'; import { getForbiddenRoute } from '../../app-routing-paths'; import { RemoteData } from '../../core/data/remote-data'; -import { tap } from 'rxjs/internal/operators/tap'; @Component({ selector: 'ds-bitstream-download-page', @@ -22,12 +20,11 @@ import { tap } from 'rxjs/internal/operators/tap'; /** * Page component for downloading a bitstream */ -export class BitstreamDownloadPageComponent implements OnInit, OnDestroy { +export class BitstreamDownloadPageComponent implements OnInit { bitstream$: Observable; bitstreamRD$: Observable>; - subs: Subscription[] = []; constructor( private route: ActivatedRoute, @@ -46,38 +43,42 @@ export class BitstreamDownloadPageComponent implements OnInit, OnDestroy { map((data) => data.bitstream)); this.bitstream$ = this.bitstreamRD$.pipe( - tap((v) => console.log('dfdf', v)), redirectOn4xx(this.router, this.auth), getRemoteDataPayload() ); - this.subs.push(this.bitstream$.subscribe((bitstream) => { - const isAuthorized$ = this.authorizationService.isAuthorized(FeatureID.CanDownload, isNotEmpty(bitstream) ? bitstream.self : undefined); - const isLoggedIn$ = this.auth.isAuthenticated(); - - this.subs.push(observableCombineLatest(isAuthorized$, isLoggedIn$) - .subscribe(([isAuthorized, isLoggedIn]) => { - if (isAuthorized && isLoggedIn) { - const fileLink$ = this.fileService.downloadFile(bitstream._links.content.href); - this.subs.push(fileLink$.subscribe((fileLink) => { - this.hardRedirectService.redirect(fileLink); + this.bitstream$.pipe( + switchMap((bitstream: Bitstream) => { + const isAuthorized$ = this.authorizationService.isAuthorized(FeatureID.CanDownload, isNotEmpty(bitstream) ? bitstream.self : undefined); + const isLoggedIn$ = this.auth.isAuthenticated(); + return observableCombineLatest([isAuthorized$, isLoggedIn$, observableOf(bitstream)]); + }), + filter(([isAuthorized, isLoggedIn, bitstream]: [boolean, boolean, Bitstream]) => hasValue(isAuthorized) && hasValue(isLoggedIn)), + take(1), + switchMap(([isAuthorized, isLoggedIn, bitstream]: [boolean, boolean, Bitstream]) => { + if (isAuthorized && isLoggedIn) { + return this.fileService.retrieveFileDownloadLink(bitstream._links.content.href).pipe( + filter((fileLink) => hasValue(fileLink)), + take(1), + map((fileLink) => { + return [isAuthorized, isLoggedIn, bitstream, fileLink]; + // return [isAuthorized, isLoggedIn, bitstream]; })); - } else if (isAuthorized && !isLoggedIn) { - this.hardRedirectService.redirect(bitstream._links.content.href); - } else if (!isAuthorized && isLoggedIn) { - this.router.navigateByUrl(getForbiddenRoute(), {skipLocationChange: true}); - } else if (!isAuthorized && !isLoggedIn) { - this.auth.setRedirectUrl(this.router.url); - this.router.navigateByUrl('login'); - } - })); - })); - - } - - ngOnDestroy(): void { - this.subs - .filter((subscription) => hasValue(subscription)) - .forEach((subscription) => subscription.unsubscribe()); + } else { + return [[isAuthorized, isLoggedIn, bitstream, '']]; + } + }) + ).subscribe(([isAuthorized, isLoggedIn, bitstream, fileLink]: [boolean, boolean, Bitstream, string]) => { + if (isAuthorized && isLoggedIn && isNotEmpty(fileLink)) { + this.hardRedirectService.redirect(fileLink); + } else if (isAuthorized && !isLoggedIn) { + this.hardRedirectService.redirect(bitstream._links.content.href); + } else if (!isAuthorized && isLoggedIn) { + this.router.navigateByUrl(getForbiddenRoute(), {skipLocationChange: true}); + } else if (!isAuthorized && !isLoggedIn) { + this.auth.setRedirectUrl(this.router.url); + this.router.navigateByUrl('login'); + } + }); } } diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts index b7e67ff2ec..a4dc0a1d3d 100644 --- a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts @@ -82,7 +82,7 @@ export class ItemDetailPreviewComponent { first()) .subscribe((url) => { const fileUrl = `${url}/${uuid}/content`; - this.fileService.downloadFile(fileUrl); + this.fileService.retrieveFileDownloadLink(fileUrl); }); } diff --git a/src/app/submission/sections/upload/file/section-upload-file.component.spec.ts b/src/app/submission/sections/upload/file/section-upload-file.component.spec.ts index 730a456faa..ac91e5eb3c 100644 --- a/src/app/submission/sections/upload/file/section-upload-file.component.spec.ts +++ b/src/app/submission/sections/upload/file/section-upload-file.component.spec.ts @@ -41,7 +41,7 @@ import { FormBuilderService } from '../../../../shared/form/builder/form-builder function getMockFileService(): FileService { return jasmine.createSpyObj('FileService', { - downloadFile: jasmine.createSpy('downloadFile'), + retrieveFileDownloadLink: jasmine.createSpy('retrieveFileDownloadLink'), getFileNameFromResponseContentDisposition: jasmine.createSpy('getFileNameFromResponseContentDisposition') }); } @@ -232,7 +232,7 @@ describe('SubmissionSectionUploadFileComponent test suite', () => { tick(); - expect(fileService.downloadFile).toHaveBeenCalled(); + expect(fileService.retrieveFileDownloadLink).toHaveBeenCalled(); })); it('should save Bitstream File data properly when form is valid', fakeAsync(() => { diff --git a/src/app/submission/sections/upload/file/section-upload-file.component.ts b/src/app/submission/sections/upload/file/section-upload-file.component.ts index 80945bc1fd..5a97140a70 100644 --- a/src/app/submission/sections/upload/file/section-upload-file.component.ts +++ b/src/app/submission/sections/upload/file/section-upload-file.component.ts @@ -224,7 +224,7 @@ export class SubmissionSectionUploadFileComponent implements OnChanges, OnInit { first()) .subscribe((url) => { const fileUrl = `${url}/${this.fileData.uuid}/content`; - this.fileService.downloadFile(fileUrl); + this.fileService.retrieveFileDownloadLink(fileUrl); }); } From a1abface1335762f4a23319837162595155402f2 Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Fri, 29 Jan 2021 11:32:56 +0100 Subject: [PATCH 3/9] Fix lint issues --- .../file-download-link/file-download-link.component.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/shared/file-download-link/file-download-link.component.spec.ts b/src/app/shared/file-download-link/file-download-link.component.spec.ts index 53f39b104e..6f7f50e585 100644 --- a/src/app/shared/file-download-link/file-download-link.component.spec.ts +++ b/src/app/shared/file-download-link/file-download-link.component.spec.ts @@ -51,12 +51,12 @@ describe('FileDownloadLinkComponent', () => { it('should set the bitstreamPath based on the input bitstream', () => { expect(component.bitstreamPath).toEqual(new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString()); }); - }) + }); it('should init the component', () => { const link = fixture.debugElement.query(By.css('a')).nativeElement; expect(link.href).toContain(new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString()); - }) + }); }); }); From 69c29407a29b7870edfd6db4cb6221a0227321ef Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Fri, 29 Jan 2021 14:37:14 +0100 Subject: [PATCH 4/9] Remove comment --- .../bitstream-download-page/bitstream-download-page.component.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts index 5b82928a64..a09d7e8b3e 100644 --- a/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts +++ b/src/app/shared/bitstream-download-page/bitstream-download-page.component.ts @@ -62,7 +62,6 @@ export class BitstreamDownloadPageComponent implements OnInit { take(1), map((fileLink) => { return [isAuthorized, isLoggedIn, bitstream, fileLink]; - // return [isAuthorized, isLoggedIn, bitstream]; })); } else { return [[isAuthorized, isLoggedIn, bitstream, '']]; From 99a96451b121ab6ff500ff7fc70976e83e7dc3b3 Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Fri, 12 Feb 2021 10:01:08 +0100 Subject: [PATCH 5/9] Update metadataservice citation tag to refer to new download page --- src/app/app-routing-paths.ts | 5 +++++ .../core/metadata/metadata.service.spec.ts | 2 +- src/app/core/metadata/metadata.service.ts | 6 ++++-- .../file-download-link.component.ts | 19 ++----------------- 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/app/app-routing-paths.ts b/src/app/app-routing-paths.ts index 08f7b9585f..ecd9dc51d4 100644 --- a/src/app/app-routing-paths.ts +++ b/src/app/app-routing-paths.ts @@ -6,6 +6,7 @@ import { getCommunityPageRoute } from './+community-page/community-page-routing- import { getCollectionPageRoute } from './+collection-page/collection-page-routing-paths'; import { getItemPageRoute } from './+item-page/item-page-routing-paths'; import { hasValue } from './shared/empty.util'; +import { URLCombiner } from './core/url-combiner/url-combiner'; export const BITSTREAM_MODULE_PATH = 'bitstreams'; @@ -13,6 +14,10 @@ export function getBitstreamModuleRoute() { return `/${BITSTREAM_MODULE_PATH}`; } +export function getBitstreamDownloadRoute(bitstream) : string{ + return new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString(); +} + export const ADMIN_MODULE_PATH = 'admin'; export function getAdminModuleRoute() { diff --git a/src/app/core/metadata/metadata.service.spec.ts b/src/app/core/metadata/metadata.service.spec.ts index 043bc3cc05..18421dd489 100644 --- a/src/app/core/metadata/metadata.service.spec.ts +++ b/src/app/core/metadata/metadata.service.spec.ts @@ -222,7 +222,7 @@ describe('MetadataService', () => { expect(tagStore.get('citation_dissertation_name')[0].content).toEqual('Test PowerPoint Document'); expect(tagStore.get('citation_dissertation_institution')[0].content).toEqual('Mock Publisher'); expect(tagStore.get('citation_abstract_html_url')[0].content).toEqual([environment.ui.baseUrl, router.url].join('')); - expect(tagStore.get('citation_pdf_url')[0].content).toEqual('https://dspace7.4science.it/dspace-spring-rest/api/core/bitstreams/99b00f3c-1cc6-4689-8158-91965bee6b28/content'); + expect(tagStore.get('citation_pdf_url')[0].content).toEqual('/bitstreams/99b00f3c-1cc6-4689-8158-91965bee6b28/download'); })); it('items page should set meta tags as published Technical Report', fakeAsync(() => { diff --git a/src/app/core/metadata/metadata.service.ts b/src/app/core/metadata/metadata.service.ts index eed4228683..5bbb90ac80 100644 --- a/src/app/core/metadata/metadata.service.ts +++ b/src/app/core/metadata/metadata.service.ts @@ -22,6 +22,8 @@ import { Item } from '../shared/item.model'; import { getFirstSucceededRemoteDataPayload, getFirstSucceededRemoteListPayload } from '../shared/operators'; import { environment } from '../../../environments/environment'; import { RootDataService } from '../data/root-data.service'; +import { URLCombiner } from '../url-combiner/url-combiner'; +import { getBitstreamDownloadRoute, getBitstreamModuleRoute } from '../../app-routing-paths'; @Injectable() export class MetadataService { @@ -40,7 +42,6 @@ export class MetadataService { private dsoNameService: DSONameService, private bitstreamDataService: BitstreamDataService, private bitstreamFormatDataService: BitstreamFormatDataService, - private redirectService: HardRedirectService, private rootService: RootDataService ) { // TODO: determine what open graph meta tags are needed and whether @@ -286,7 +287,8 @@ export class MetadataService { getFirstSucceededRemoteDataPayload() ).subscribe((format: BitstreamFormat) => { if (format.mimetype === 'application/pdf') { - this.addMetaTag('citation_pdf_url', bitstream._links.content.href); + const bitstreamLink = getBitstreamDownloadRoute(bitstream); + this.addMetaTag('citation_pdf_url', bitstreamLink); } }); } diff --git a/src/app/shared/file-download-link/file-download-link.component.ts b/src/app/shared/file-download-link/file-download-link.component.ts index 8a1fbd6e0e..4423b6f5b7 100644 --- a/src/app/shared/file-download-link/file-download-link.component.ts +++ b/src/app/shared/file-download-link/file-download-link.component.ts @@ -1,10 +1,6 @@ import { Component, Input, OnInit } from '@angular/core'; -import { FileService } from '../../core/shared/file.service'; -import { Observable } from 'rxjs'; -import { AuthService } from '../../core/auth/auth.service'; import { Bitstream } from '../../core/shared/bitstream.model'; -import { getBitstreamModuleRoute } from '../../app-routing-paths'; -import { URLCombiner } from '../../core/url-combiner/url-combiner'; +import { getBitstreamDownloadRoute } from '../../app-routing-paths'; @Component({ selector: 'ds-file-download-link', @@ -24,22 +20,11 @@ export class FileDownloadLinkComponent implements OnInit { @Input() bitstream: Bitstream; bitstreamPath: string; - /** - * Whether or not the current user is authenticated - */ - isAuthenticated$: Observable; - - constructor(private fileService: FileService, - private authService: AuthService, - ) { - } - ngOnInit() { - this.isAuthenticated$ = this.authService.isAuthenticated(); this.bitstreamPath = this.getBitstreamPath(); } getBitstreamPath() { - return new URLCombiner(getBitstreamModuleRoute(), this.bitstream.uuid, 'download').toString(); + return getBitstreamDownloadRoute(this.bitstream); } } From 72ca74bdf343baebdf20099f4b5c1f8e85069a8c Mon Sep 17 00:00:00 2001 From: Yana De Pauw Date: Fri, 12 Feb 2021 10:31:17 +0100 Subject: [PATCH 6/9] Fix checkstyle issue --- src/app/app-routing-paths.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/app-routing-paths.ts b/src/app/app-routing-paths.ts index ecd9dc51d4..7dfdbd2c49 100644 --- a/src/app/app-routing-paths.ts +++ b/src/app/app-routing-paths.ts @@ -14,7 +14,7 @@ export function getBitstreamModuleRoute() { return `/${BITSTREAM_MODULE_PATH}`; } -export function getBitstreamDownloadRoute(bitstream) : string{ +export function getBitstreamDownloadRoute(bitstream): string { return new URLCombiner(getBitstreamModuleRoute(), bitstream.uuid, 'download').toString(); } From ff4bd59de0d280121420d5fd4721891ac30f7e6f Mon Sep 17 00:00:00 2001 From: Art Lowel Date: Tue, 6 Apr 2021 16:45:06 +0200 Subject: [PATCH 7/9] use GET for shortlivedtoken requests on the server, POST on the client --- .../core/auth/auth-request.service.spec.ts | 74 +++++++++++++++++++ src/app/core/auth/auth-request.service.ts | 31 +++++--- .../auth/browser-auth-request.service.spec.ts | 29 ++++++++ .../core/auth/browser-auth-request.service.ts | 34 +++++++++ .../auth/server-auth-request.service.spec.ts | 34 +++++++++ .../core/auth/server-auth-request.service.ts | 36 +++++++++ src/app/core/core.module.ts | 2 - src/modules/app/browser-app.module.ts | 6 ++ src/modules/app/server-app.module.ts | 6 ++ 9 files changed, 238 insertions(+), 14 deletions(-) create mode 100644 src/app/core/auth/auth-request.service.spec.ts create mode 100644 src/app/core/auth/browser-auth-request.service.spec.ts create mode 100644 src/app/core/auth/browser-auth-request.service.ts create mode 100644 src/app/core/auth/server-auth-request.service.spec.ts create mode 100644 src/app/core/auth/server-auth-request.service.ts diff --git a/src/app/core/auth/auth-request.service.spec.ts b/src/app/core/auth/auth-request.service.spec.ts new file mode 100644 index 0000000000..707daf9e30 --- /dev/null +++ b/src/app/core/auth/auth-request.service.spec.ts @@ -0,0 +1,74 @@ +import { AuthRequestService } from './auth-request.service'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { RequestService } from '../data/request.service'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { PostRequest } from '../data/request.models'; +import { TestScheduler } from 'rxjs/testing'; +import { createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils'; +import { ShortLivedToken } from './models/short-lived-token.model'; +import { RemoteData } from '../data/remote-data'; + +describe(`AuthRequestService`, () => { + let halService: HALEndpointService; + let endpointURL: string; + let shortLivedToken: ShortLivedToken; + let shortLivedTokenRD: RemoteData; + let requestService: RequestService; + let rdbService: RemoteDataBuildService; + let service: AuthRequestService; + let testScheduler; + + class TestAuthRequestService extends AuthRequestService { + constructor( + hes: HALEndpointService, + rs: RequestService, + rdbs: RemoteDataBuildService + ) { + super(hes, rs, rdbs); + } + + protected createShortLivedTokenRequest(href: string): PostRequest { + return new PostRequest(this.requestService.generateRequestId(), href); + } + } + + const init = (cold: typeof TestScheduler.prototype.createColdObservable) => { + endpointURL = 'https://rest.api/auth'; + shortLivedToken = Object.assign(new ShortLivedToken(), { + value: 'some-token' + }); + shortLivedTokenRD = createSuccessfulRemoteDataObject(shortLivedToken); + + halService = jasmine.createSpyObj('halService', { + 'getEndpoint': cold('a', { a: endpointURL }) + }); + requestService = jasmine.createSpyObj('requestService', { + 'send': null + }); + rdbService = jasmine.createSpyObj('rdbService', { + 'buildFromRequestUUID': cold('a', { a: shortLivedTokenRD }) + }); + + service = new TestAuthRequestService(halService, requestService, rdbService); + }; + + beforeEach(() => { + testScheduler = new TestScheduler((actual, expected) => { + expect(actual).toEqual(expected); + }); + }); + + describe(`getShortlivedToken`, () => { + it(`should call createShortLivedTokenRequest with the url for the endpoint`, () => { + testScheduler.run(({ cold, expectObservable, flush }) => { + init(cold); + spyOn(service as any, 'createShortLivedTokenRequest'); + // expectObservable is needed to let testScheduler know to take it in to account, but since + // we're not testing the outcome in this test, a .toBe(…) isn't necessary + expectObservable(service.getShortlivedToken()); + flush(); + expect((service as any).createShortLivedTokenRequest).toHaveBeenCalledWith(`${endpointURL}/shortlivedtokens`); + }); + }); + }); +}); diff --git a/src/app/core/auth/auth-request.service.ts b/src/app/core/auth/auth-request.service.ts index 4315ddfea8..00a94822d3 100644 --- a/src/app/core/auth/auth-request.service.ts +++ b/src/app/core/auth/auth-request.service.ts @@ -1,14 +1,9 @@ import { Observable } from 'rxjs'; import { distinctUntilChanged, filter, map, mergeMap, switchMap, tap } from 'rxjs/operators'; -import { Injectable } from '@angular/core'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { RequestService } from '../data/request.service'; import { isNotEmpty } from '../../shared/empty.util'; -import { - GetRequest, - PostRequest, - RestRequest, -} from '../data/request.models'; +import { GetRequest, PostRequest, RestRequest, } from '../data/request.models'; import { HttpOptions } from '../dspace-rest/dspace-rest.service'; import { getFirstCompletedRemoteData } from '../shared/operators'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; @@ -17,8 +12,10 @@ import { AuthStatus } from './models/auth-status.model'; import { ShortLivedToken } from './models/short-lived-token.model'; import { URLCombiner } from '../url-combiner/url-combiner'; -@Injectable() -export class AuthRequestService { +/** + * Abstract service to send authentication requests + */ +export abstract class AuthRequestService { protected linkName = 'authn'; protected browseEndpoint = ''; protected shortlivedtokensEndpoint = 'shortlivedtokens'; @@ -62,16 +59,26 @@ export class AuthRequestService { } /** - * Send a POST request to retrieve a short-lived token which provides download access of restricted files + * Factory function to create the request object to send. This needs to be a POST client side and + * a GET server side. Due to CSRF validation, the server isn't allowed to send a POST, so we allow + * only the server IP to send a GET to this endpoint. + * + * @param href The href to send the request to + * @protected + */ + protected abstract createShortLivedTokenRequest(href: string): GetRequest | PostRequest; + + /** + * Send a request to retrieve a short-lived token which provides download access of restricted files */ public getShortlivedToken(): Observable { return this.halService.getEndpoint(this.linkName).pipe( filter((href: string) => isNotEmpty(href)), distinctUntilChanged(), map((href: string) => new URLCombiner(href, this.shortlivedtokensEndpoint).toString()), - map((endpointURL: string) => new PostRequest(this.requestService.generateRequestId(), endpointURL)), - tap((request: PostRequest) => this.requestService.send(request)), - switchMap((request: PostRequest) => this.rdbService.buildFromRequestUUID(request.uuid)), + map((endpointURL: string) => this.createShortLivedTokenRequest(endpointURL)), + tap((request: RestRequest) => this.requestService.send(request)), + switchMap((request: RestRequest) => this.rdbService.buildFromRequestUUID(request.uuid)), getFirstCompletedRemoteData(), map((response: RemoteData) => { if (response.hasSucceeded) { diff --git a/src/app/core/auth/browser-auth-request.service.spec.ts b/src/app/core/auth/browser-auth-request.service.spec.ts new file mode 100644 index 0000000000..18d27340af --- /dev/null +++ b/src/app/core/auth/browser-auth-request.service.spec.ts @@ -0,0 +1,29 @@ +import { AuthRequestService } from './auth-request.service'; +import { RequestService } from '../data/request.service'; +import { BrowserAuthRequestService } from './browser-auth-request.service'; + +describe(`BrowserAuthRequestService`, () => { + let href: string; + let requestService: RequestService; + let service: AuthRequestService; + + beforeEach(() => { + href = 'https://rest.api/auth/shortlivedtokens'; + requestService = jasmine.createSpyObj('requestService', { + 'generateRequestId': '8bb0582d-5013-4337-af9c-763beb25aae2' + }); + service = new BrowserAuthRequestService(null, requestService, null); + }); + + describe(`createShortLivedTokenRequest`, () => { + it(`should return a PostRequest`, () => { + const result = (service as any).createShortLivedTokenRequest(href); + expect(result.constructor.name).toBe('PostRequest'); + }); + + it(`should return a request with the given href`, () => { + const result = (service as any).createShortLivedTokenRequest(href); + expect(result.href).toBe(href) ; + }); + }); +}); diff --git a/src/app/core/auth/browser-auth-request.service.ts b/src/app/core/auth/browser-auth-request.service.ts new file mode 100644 index 0000000000..85d5f54340 --- /dev/null +++ b/src/app/core/auth/browser-auth-request.service.ts @@ -0,0 +1,34 @@ +import { Injectable } from '@angular/core'; +import { AuthRequestService } from './auth-request.service'; +import { PostRequest } from '../data/request.models'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { RequestService } from '../data/request.service'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; + +/** + * Client side version of the service to send authentication requests + */ +@Injectable() +export class BrowserAuthRequestService extends AuthRequestService { + + constructor( + halService: HALEndpointService, + requestService: RequestService, + rdbService: RemoteDataBuildService + ) { + super(halService, requestService, rdbService); + } + + /** + * Factory function to create the request object to send. This needs to be a POST client side and + * a GET server side. Due to CSRF validation, the server isn't allowed to send a POST, so we allow + * only the server IP to send a GET to this endpoint. + * + * @param href The href to send the request to + * @protected + */ + protected createShortLivedTokenRequest(href: string): PostRequest { + return new PostRequest(this.requestService.generateRequestId(), href); + } + +} diff --git a/src/app/core/auth/server-auth-request.service.spec.ts b/src/app/core/auth/server-auth-request.service.spec.ts new file mode 100644 index 0000000000..69053fbb3a --- /dev/null +++ b/src/app/core/auth/server-auth-request.service.spec.ts @@ -0,0 +1,34 @@ +import { AuthRequestService } from './auth-request.service'; +import { RequestService } from '../data/request.service'; +import { ServerAuthRequestService } from './server-auth-request.service'; + +describe(`ServerAuthRequestService`, () => { + let href: string; + let requestService: RequestService; + let service: AuthRequestService; + + beforeEach(() => { + href = 'https://rest.api/auth/shortlivedtokens'; + requestService = jasmine.createSpyObj('requestService', { + 'generateRequestId': '8bb0582d-5013-4337-af9c-763beb25aae2' + }); + service = new ServerAuthRequestService(null, requestService, null); + }); + + describe(`createShortLivedTokenRequest`, () => { + it(`should return a GetRequest`, () => { + const result = (service as any).createShortLivedTokenRequest(href); + expect(result.constructor.name).toBe('GetRequest'); + }); + + it(`should return a request with the given href`, () => { + const result = (service as any).createShortLivedTokenRequest(href); + expect(result.href).toBe(href) ; + }); + + it(`should have a responseMsToLive of 2 seconds`, () => { + const result = (service as any).createShortLivedTokenRequest(href); + expect(result.responseMsToLive).toBe(2 * 1000) ; + }); + }); +}); diff --git a/src/app/core/auth/server-auth-request.service.ts b/src/app/core/auth/server-auth-request.service.ts new file mode 100644 index 0000000000..751389f71d --- /dev/null +++ b/src/app/core/auth/server-auth-request.service.ts @@ -0,0 +1,36 @@ +import { Injectable } from '@angular/core'; +import { AuthRequestService } from './auth-request.service'; +import { GetRequest } from '../data/request.models'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { RequestService } from '../data/request.service'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; + +/** + * Server side version of the service to send authentication requests + */ +@Injectable() +export class ServerAuthRequestService extends AuthRequestService { + + constructor( + halService: HALEndpointService, + requestService: RequestService, + rdbService: RemoteDataBuildService + ) { + super(halService, requestService, rdbService); + } + + /** + * Factory function to create the request object to send. This needs to be a POST client side and + * a GET server side. Due to CSRF validation, the server isn't allowed to send a POST, so we allow + * only the server IP to send a GET to this endpoint. + * + * @param href The href to send the request to + * @protected + */ + protected createShortLivedTokenRequest(href: string): GetRequest { + return Object.assign(new GetRequest(this.requestService.generateRequestId(), href), { + responseMsToLive: 2 * 1000 // A short lived token is only valid for 2 seconds. + }); + } + +} diff --git a/src/app/core/core.module.ts b/src/app/core/core.module.ts index f73bfd0bdf..619a7dbadc 100644 --- a/src/app/core/core.module.ts +++ b/src/app/core/core.module.ts @@ -31,7 +31,6 @@ import { CSSVariableService } from '../shared/sass-helper/sass-helper.service'; import { SidebarService } from '../shared/sidebar/sidebar.service'; import { UploaderService } from '../shared/uploader/uploader.service'; import { SectionFormOperationsService } from '../submission/sections/form/section-form-operations.service'; -import { AuthRequestService } from './auth/auth-request.service'; import { AuthenticatedGuard } from './auth/authenticated.guard'; import { AuthStatus } from './auth/models/auth-status.model'; import { BrowseService } from './browse/browse.service'; @@ -188,7 +187,6 @@ const EXPORTS = []; const PROVIDERS = [ ApiService, AuthenticatedGuard, - AuthRequestService, CommunityDataService, CollectionDataService, SiteDataService, diff --git a/src/modules/app/browser-app.module.ts b/src/modules/app/browser-app.module.ts index 4b6c5c813e..070d530dfe 100644 --- a/src/modules/app/browser-app.module.ts +++ b/src/modules/app/browser-app.module.ts @@ -31,6 +31,8 @@ import { import { LocaleService } from '../../app/core/locale/locale.service'; import { GoogleAnalyticsService } from '../../app/statistics/google-analytics.service'; import { RouterModule, NoPreloading } from '@angular/router'; +import { AuthRequestService } from '../../app/core/auth/auth-request.service'; +import { BrowserAuthRequestService } from '../../app/core/auth/browser-auth-request.service'; export const REQ_KEY = makeStateKey('req'); @@ -104,6 +106,10 @@ export function getRequest(transferState: TransferState): any { provide: GoogleAnalyticsService, useClass: GoogleAnalyticsService, }, + { + provide: AuthRequestService, + useClass: BrowserAuthRequestService, + }, { provide: LocationToken, useFactory: locationProvider, diff --git a/src/modules/app/server-app.module.ts b/src/modules/app/server-app.module.ts index 906d4c5f35..dad3a60d5c 100644 --- a/src/modules/app/server-app.module.ts +++ b/src/modules/app/server-app.module.ts @@ -31,6 +31,8 @@ import { ServerHardRedirectService } from '../../app/core/services/server-hard-r import { Angulartics2 } from 'angulartics2'; import { Angulartics2Mock } from '../../app/shared/mocks/angulartics2.service.mock'; import { RouterModule } from '@angular/router'; +import { AuthRequestService } from '../../app/core/auth/auth-request.service'; +import { ServerAuthRequestService } from '../../app/core/auth/server-auth-request.service'; export function createTranslateLoader() { return new TranslateJson5UniversalLoader('dist/server/assets/i18n/', '.json5'); @@ -82,6 +84,10 @@ export function createTranslateLoader() { provide: SubmissionService, useClass: ServerSubmissionService }, + { + provide: AuthRequestService, + useClass: ServerAuthRequestService, + }, { provide: LocaleService, useClass: ServerLocaleService From 3c93777e845d27860e6d648c6bd078d17f188821 Mon Sep 17 00:00:00 2001 From: Art Lowel Date: Tue, 6 Apr 2021 16:45:35 +0200 Subject: [PATCH 8/9] don't use CSR fallback when the headers are changed after the response is sent --- server.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/server.ts b/server.ts index ada6c9f040..73b88cd0c6 100644 --- a/server.ts +++ b/server.ts @@ -160,6 +160,11 @@ function ngApp(req, res) { }, (err, data) => { if (hasNoValue(err) && hasValue(data)) { res.send(data); + } else if (hasValue(err) && err.code === 'ERR_HTTP_HEADERS_SENT') { + // When this error occurs we can't fall back to CSR because the response has already been + // sent. These errors occur for various reasons in universal, not all of which are in our + // control to solve. + console.warn('Warning [ERR_HTTP_HEADERS_SENT]: Tried to set headers after they were sent to the client'); } else { console.warn('Error in SSR, serving for direct CSR.'); if (hasValue(err)) { From 425f530f087eba079e12223109b23d9d1a55187d Mon Sep 17 00:00:00 2001 From: Art Lowel Date: Tue, 6 Apr 2021 16:58:37 +0200 Subject: [PATCH 9/9] fix LGTM warnings --- src/app/core/metadata/metadata.service.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/app/core/metadata/metadata.service.ts b/src/app/core/metadata/metadata.service.ts index 5bbb90ac80..807f7a42ab 100644 --- a/src/app/core/metadata/metadata.service.ts +++ b/src/app/core/metadata/metadata.service.ts @@ -1,4 +1,4 @@ -import { Inject, Injectable } from '@angular/core'; +import { Injectable } from '@angular/core'; import { Meta, MetaDefinition, Title } from '@angular/platform-browser'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; @@ -19,11 +19,13 @@ import { BitstreamFormat } from '../shared/bitstream-format.model'; import { Bitstream } from '../shared/bitstream.model'; import { DSpaceObject } from '../shared/dspace-object.model'; import { Item } from '../shared/item.model'; -import { getFirstSucceededRemoteDataPayload, getFirstSucceededRemoteListPayload } from '../shared/operators'; +import { + getFirstSucceededRemoteDataPayload, + getFirstSucceededRemoteListPayload +} from '../shared/operators'; import { environment } from '../../../environments/environment'; import { RootDataService } from '../data/root-data.service'; -import { URLCombiner } from '../url-combiner/url-combiner'; -import { getBitstreamDownloadRoute, getBitstreamModuleRoute } from '../../app-routing-paths'; +import { getBitstreamDownloadRoute } from '../../app-routing-paths'; @Injectable() export class MetadataService {