diff --git a/src/app/restricted-access/restricted-access.component.spec.ts b/src/app/restricted-access/restricted-access.component.spec.ts new file mode 100644 index 00000000000..3a364767439 --- /dev/null +++ b/src/app/restricted-access/restricted-access.component.spec.ts @@ -0,0 +1,316 @@ +import { + DatePipe, + Location, +} from '@angular/common'; +import { + ComponentFixture, + TestBed, + waitForAsync, +} from '@angular/core/testing'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { TranslateModule } from '@ngx-translate/core'; +import { of as observableOf } from 'rxjs'; + +import { AuthService } from '../core/auth/auth.service'; +import { AuthorizationDataService } from '../core/data/feature-authorization/authorization-data.service'; +import { HardRedirectService } from '../core/services/hard-redirect.service'; +import { ServerResponseService } from '../core/services/server-response.service'; +import { Bitstream } from '../core/shared/bitstream.model'; +import { FileService } from '../core/shared/file.service'; +import { createSuccessfulRemoteDataObject } from '../shared/remote-data.utils'; +import { RestrictedAccessComponent } from './restricted-access.component'; + +describe('RestrictedAccessComponent', () => { + let component: RestrictedAccessComponent; + let fixture: ComponentFixture; + + let authService: jasmine.SpyObj; + let authorizationService: jasmine.SpyObj; + let fileService: jasmine.SpyObj; + let hardRedirectService: jasmine.SpyObj; + let serverResponseService: jasmine.SpyObj; + let router: jasmine.SpyObj; + let location: jasmine.SpyObj; + let activatedRoute; + + let bitstream: Bitstream; + + function initBitstream(overrides: Partial = {}): Bitstream { + return Object.assign(new Bitstream(), { + uuid: 'test-bitstream-uuid', + metadata: { + 'dc.title': [{ value: 'test-file.pdf', language: null, authority: null, confidence: -1, place: 0 }], + }, + _links: { + content: { href: 'bitstream-content-link' }, + self: { href: 'bitstream-self-link' }, + }, + // Default in tests to "FOREVER" embargo + embargoRestriction: 'FOREVER', + ...overrides, + }); + } + + function init(bitstreamOverrides: Partial = {}) { + bitstream = initBitstream(bitstreamOverrides); + + authService = jasmine.createSpyObj('AuthService', { + isAuthenticated: observableOf(false), + setRedirectUrl: {}, + }); + + authorizationService = jasmine.createSpyObj('AuthorizationDataService', { + isAuthorized: observableOf(false), + }); + + fileService = jasmine.createSpyObj('FileService', { + retrieveFileDownloadLink: observableOf('content-url-with-headers'), + }); + + hardRedirectService = jasmine.createSpyObj('HardRedirectService', { + redirect: {}, + }); + + serverResponseService = jasmine.createSpyObj('ServerResponseService', { + setUnauthorized: {}, + setForbidden: {}, + setNotFound: {}, + setStatus: {}, + }); + + router = jasmine.createSpyObj('Router', ['navigateByUrl']); + // Provide a url property for redirectOn4xx + (router as any).url = '/restricted-access/test-bitstream-uuid'; + + location = jasmine.createSpyObj('Location', ['back']); + + activatedRoute = { + data: observableOf({ + bitstream: createSuccessfulRemoteDataObject(bitstream), + }), + }; + } + + function initTestBed() { + void TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot(), + RestrictedAccessComponent, + ], + 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 }, + { provide: ServerResponseService, useValue: serverResponseService }, + { provide: Location, useValue: location }, + DatePipe, + ], + }).compileComponents(); + } + + // Helper function for setting up anonymous tests with a specific embargo + // restriction + function setupAnonymous(bitstreamOverrides: Partial) { + beforeEach(waitForAsync(() => { + init(bitstreamOverrides); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(false)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(false)); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + } + + // Helper function verifying that a HTTP 401 Unauthorized status code is + // set, and that a redirect to the bitstream is not performed. + function verify401StatusCodeAndNoRedirectToDownload() { + it('should set 401 Unauthorized and not redirect to the file', () => { + expect(serverResponseService.setUnauthorized).toHaveBeenCalled(); + expect(serverResponseService.setForbidden).not.toHaveBeenCalled(); + expect(hardRedirectService.redirect).not.toHaveBeenCalled(); + }); + } + + describe('when the user is anonymous (not logged in)', () => { + describe('when embargoRestriction is FOREVER', () => { + setupAnonymous({ embargoRestriction: 'FOREVER' }); + + verify401StatusCodeAndNoRedirectToDownload(); + + it('should set the restrictedAccessMessage indicating the file is embargoed forever', () => { + expect(component.restrictedAccessMessage.value).toBe('bitstream.restricted-access.embargo.forever.message'); + }); + }); + + describe('when there is an embargo end date', () => { + setupAnonymous({ embargoRestriction: '2199-04-08' }); + + verify401StatusCodeAndNoRedirectToDownload(); + + it('should set the restrictedAccessMessage indicating an end date', () => { + expect(component.restrictedAccessMessage.value).toBe( + 'bitstream.restricted-access.embargo.restricted-until.message'); + }); + }); + + describe('when embargoRestriction is NONE (embargo over, but file is restricted for another reason)', () => { + setupAnonymous({ embargoRestriction: 'NONE' }); + + verify401StatusCodeAndNoRedirectToDownload(); + + it('should set the restrictedAccessMessage to a simple "forbidden" message', () => { + expect(component.restrictedAccessMessage.value).toBe('bitstream.restricted-access.anonymous.forbidden.message'); + }); + }); + + describe('when file is restricted for non-embargo reasons (such as Campus IP restriction)', () => { + setupAnonymous({ embargoRestriction:null }); + + verify401StatusCodeAndNoRedirectToDownload(); + + it('should set the restrictedAccessMessage to a simple "forbidden" message', () => { + expect(component.restrictedAccessMessage.value).toBe('bitstream.restricted-access.anonymous.forbidden.message'); + }); + }); + + describe('but the user is authorized (even if there is an embargo)', () => { + beforeEach(waitForAsync(() => { + init(); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(false)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(true)); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should redirect to the content link', () => { + expect(hardRedirectService.redirect).toHaveBeenCalled(); + }); + + it('should NOT call setUnauthorized', () => { + expect(serverResponseService.setUnauthorized).not.toHaveBeenCalled(); + }); + + it('should NOT call setForbidden', () => { + expect(serverResponseService.setForbidden).not.toHaveBeenCalled(); + }); + }); + }); + + describe('when the user is logged in', () => { + describe('returns 403 Forbidden when the user is not authorized to access the file', () => { + beforeEach(waitForAsync(() => { + init(); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(true)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(false)); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should call setForbidden on ServerResponseService', () => { + expect(serverResponseService.setForbidden).toHaveBeenCalled(); + }); + + it('should NOT call setUnauthorized on ServerResponseService', () => { + expect(serverResponseService.setUnauthorized).not.toHaveBeenCalled(); + }); + + it('should NOT redirect to a download', () => { + expect(hardRedirectService.redirect).not.toHaveBeenCalled(); + }); + + it('should set the restrictedAccessHeader', () => { + expect(component.restrictedAccessHeader.value).toBe('bitstream.restricted-access.user.forbidden.header'); + }); + + it('should set the restrictedAccessMessage', () => { + expect(component.restrictedAccessMessage.value).toBe( + 'bitstream.restricted-access.user.forbidden.with_file.message'); + }); + }); + + describe('returns 403 Forbidden with a generic message when a filename is not provided', () => { + beforeEach(waitForAsync(() => { + init({ metadata: {} }); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(true)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(false)); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should set the generic forbidden message', () => { + expect(component.restrictedAccessMessage.value).toBe( + 'bitstream.restricted-access.user.forbidden.generic.message'); + }); + }); + + describe('allows access to the file when the user is authorized', () => { + beforeEach(waitForAsync(() => { + init(); + (authService.isAuthenticated as jasmine.Spy).and.returnValue(observableOf(true)); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(observableOf(true)); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should NOT call setUnauthorized', () => { + expect(serverResponseService.setUnauthorized).not.toHaveBeenCalled(); + }); + + it('should NOT call setForbidden', () => { + expect(serverResponseService.setForbidden).not.toHaveBeenCalled(); + }); + + it('should redirect to the file download link', () => { + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + }); + }); + }); + + describe('back()', () => { + beforeEach(waitForAsync(() => { + init(); + initTestBed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RestrictedAccessComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should call location.back()', () => { + component.back(); + expect(location.back).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/app/restricted-access/restricted-access.component.ts b/src/app/restricted-access/restricted-access.component.ts index 908b5b6f7fb..3b193ddbad6 100644 --- a/src/app/restricted-access/restricted-access.component.ts +++ b/src/app/restricted-access/restricted-access.component.ts @@ -5,8 +5,11 @@ import { } from '@angular/common'; import { Component, + DestroyRef, + inject, OnInit, } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router, @@ -18,6 +21,7 @@ import { import { BehaviorSubject, combineLatest as observableCombineLatest, + EMPTY, filter, map, Observable, @@ -32,6 +36,7 @@ import { AuthorizationDataService } from '../core/data/feature-authorization/aut import { FeatureID } from '../core/data/feature-authorization/feature-id'; import { RemoteData } from '../core/data/remote-data'; import { HardRedirectService } from '../core/services/hard-redirect.service'; +import { ServerResponseService } from '../core/services/server-response.service'; import { redirectOn4xx } from '../core/shared/authorized.operators'; import { Bitstream } from '../core/shared/bitstream.model'; import { FileService } from '../core/shared/file.service'; @@ -42,7 +47,7 @@ import { } from '../shared/empty.util'; /** - * This component representing the `Restricted Access` DSpace page. + * This component represents the `Restricted Access` DSpace page. */ @Component({ selector: 'ds-restricted-access', @@ -67,6 +72,8 @@ export class RestrictedAccessComponent implements OnInit { bitstreamRD$: Observable>; bitstream$: Observable; + private destroyRef = inject(DestroyRef); + constructor( private route: ActivatedRoute, protected router: Router, @@ -77,6 +84,7 @@ export class RestrictedAccessComponent implements OnInit { private translateService: TranslateService, private datePipe: DatePipe, private location: Location, + private responseService: ServerResponseService, ) { } @@ -110,23 +118,27 @@ export class RestrictedAccessComponent implements OnInit { return [isAuthorized, isLoggedIn, bitstream, fileLink]; })); } else { - return [[isAuthorized, isLoggedIn, bitstream, '']]; + return observableOf([isAuthorized, isLoggedIn, bitstream, ''] as [boolean, boolean, Bitstream, string]); } }), - ).subscribe(([isAuthorized, isLoggedIn, bitstream, fileLink]: [boolean, boolean, Bitstream, string]) => { - if (isAuthorized && isNotEmpty(fileLink)) { - // This shouldn't happen, as the download is authorized, and the file link is available, so just redirect to - // actual download page. - this.hardRedirectService.redirect(fileLink); - } else { + switchMap(([isAuthorized, isLoggedIn, bitstream, fileLink]: [boolean, boolean, Bitstream, string]) => { + if (isAuthorized && isNotEmpty(fileLink)) { + // This shouldn't happen, as the download is authorized, and the file link is available, so just redirect to + // actual download page. + this.hardRedirectService.redirect(fileLink); + return EMPTY; + } + let header$: Observable; let message$: Observable; if (isLoggedIn) { // This is a logged in user + // Set 403 Forbidden response status code for logged-in users without download permission + this.responseService.setForbidden(); header$ = this.translateService.get('bitstream.restricted-access.user.forbidden.header', {}); - if (bitstream && bitstream.metadata['dc.title'] && bitstream.metadata['dc.title'][0] && bitstream.metadata['dc.title'][0].value) { + if (bitstream && bitstream.metadata['dc.title'] && bitstream.metadata['dc.title'][0] && bitstream.metadata['dc.title'][0].value) { const filename = bitstream.metadata['dc.title'][0].value; message$ = this.translateService.get( 'bitstream.restricted-access.user.forbidden.with_file.message', { 'filename': filename }); @@ -136,14 +148,17 @@ export class RestrictedAccessComponent implements OnInit { } } else { // This is an anonymous user + // Set 401 Unauthorized response status code for anonymous users + this.responseService.setUnauthorized(); [header$, message$] = this.configureAnonymous(bitstream); } - zip(header$, message$).subscribe(([header, message]) => { - this.restrictedAccessHeader.next(header); - this.restrictedAccessMessage.next(message); - }); - } + return zip(header$, message$); + }), + takeUntilDestroyed(this.destroyRef), + ).subscribe(([header, message]: [string, string]) => { + this.restrictedAccessHeader.next(header); + this.restrictedAccessMessage.next(message); }); } @@ -164,7 +179,7 @@ export class RestrictedAccessComponent implements OnInit { ); } else { // Reach this branch when embargoRestriction is "NONE", but there is some - // other restriction, such as a "Campus" IP address group restiction. + // other restriction, such as a "Campus" IP address group restriction. message$ = this.translateService.get('bitstream.restricted-access.anonymous.forbidden.message', {}); } @@ -172,10 +187,10 @@ export class RestrictedAccessComponent implements OnInit { } /** - * Returns true if the given String represents a valid date, false otherise. + * Returns true if the given String represents a valid date, false otherwise. * * @param str the String to check. - * @true if the given String represents a valid date, false otherise. + * @returns true if the given String represents a valid date, false otherwise. */ private isValidDate(str: string): boolean { // Expected date is in yyyy-MM-dd format.