Skip to content
Open
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
5 changes: 4 additions & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@
{
"glob": "**/*",
"input": "src/aai",
"output": "/aai"
"output": "/aai",
"ignore": [
"**/*.spec.ts"
]
}
],
"styles": [
Expand Down
45 changes: 36 additions & 9 deletions src/aai/aai.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
var targetUrl = '';
var opts = jQuery.extend({}, this.defaults, options),
defaultCallback = function(e) {
targetUrl = opts.target + '?redirectUrl=';
// E.g. Redirect to Item page
var redirectUrl = window.location.href;

Expand All @@ -49,15 +48,10 @@

if (redirectUrlFromLogin != null && redirectUrlFromLogin !== '') {
// Redirect from the login page with retrieved redirect URL
var baseUrl = window.location.origin + formatNamespace(namespace);
var redirectPath = ensureLeadingSlash(redirectUrlFromLogin);

redirectUrl = baseUrl + redirectPath;
redirectUrl = shibbolethReturnUrl(redirectUrlFromLogin);
}

// Encode the redirect URL
targetUrl += window.encodeURIComponent(redirectUrl);
window.location = opts.host + opts.port + '/Shibboleth.sso/Login?SAMLDS=1&target=' + targetUrl + '&entityID=' + window.encodeURIComponent(e.entityID);
window.location = shibbolethLoginUrl(opts, redirectUrl, e.entityID);
};
//console.log(opts);
if(!opts.target){
Expand Down Expand Up @@ -111,7 +105,7 @@
// jQuery('input#login').focus();
// Use cookie to toggle discojuice popup.
setCookie('SHOW_DISCOJUICE_POPUP', false, 1)
window.location = window.location.origin + (namespace === '' ? namespace : '/' + namespace) + "/login?redirectUrl=" + window.location.href;
window.location = localLoginUrl(window.location.href);
break;
//case 'saml':
default:
Expand All @@ -135,6 +129,39 @@
} //if jQuery(selector)
};

// Exposed for tests.
this.localLoginUrl = localLoginUrl;
this.shibbolethReturnUrl = shibbolethReturnUrl;
this.shibbolethLoginUrl = shibbolethLoginUrl;

/**
* Login page URL that returns to `pageUrl` after a local login. Encoded, so the query string of `pageUrl` stays in it.
*/
function localLoginUrl(pageUrl) {
return window.location.origin + formatNamespace(namespace) + '/login?redirectUrl=' + window.encodeURIComponent(pageUrl);
}

/**
* Page to return to after a Shibboleth login, from the `redirectUrl` of the login page.
* A URL of this site (local login puts one there) is kept as it is, anything else is taken as a path in the app.
*/
function shibbolethReturnUrl(redirectUrlFromLogin) {
if (redirectUrlFromLogin.startsWith(window.location.origin + '/')) {
return redirectUrlFromLogin;
}
return window.location.origin + formatNamespace(namespace) + ensureLeadingSlash(redirectUrlFromLogin);
}

/**
* Shibboleth login URL whose `target` (the backend) returns to `redirectUrl`.
* `redirectUrl` is encoded inside `target` and then `target` as a whole, so the query string of `redirectUrl` reaches the backend.
*/
function shibbolethLoginUrl(opts, redirectUrl, entityID) {
var target = opts.target + '?redirectUrl=' + window.encodeURIComponent(redirectUrl);
return opts.host + opts.port + '/Shibboleth.sso/Login?SAMLDS=1&target=' + window.encodeURIComponent(target) +
'&entityID=' + window.encodeURIComponent(entityID);
}

// Set a cookie
function setCookie(name, value, daysToExpire) {
var expirationDate = new Date();
Expand Down
59 changes: 59 additions & 0 deletions src/aai/aai.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import './aai.js';

import { DefaultUrlSerializer } from '@angular/router';

describe('aai.js', () => {
const aai = (window as any).aai;

describe('localLoginUrl', () => {
const redirectUrlOf = (loginUrl: string): string => {
const url = new URL(loginUrl);
return new DefaultUrlSerializer().parse(url.pathname + url.search).queryParams.redirectUrl;
};

it('keeps the query string of the page the user came from', () => {
const page = 'http://localhost:4000/search?query=test&page=2';

expect(redirectUrlOf(aai.localLoginUrl(page))).toBe(page);
});

it('keeps the page stored by the auth guard when local login starts on the login page', () => {
const page = 'http://localhost:4000/login?redirectUrl=%2Fmydspace%3Fconfiguration%3Dworkflow';

expect(redirectUrlOf(aai.localLoginUrl(page))).toBe(page);
});
});

describe('shibbolethReturnUrl', () => {
it('keeps a URL of this site, as local login puts it into the login URL', () => {
const page = window.location.origin + '/items/1?query=test';

expect(aai.shibbolethReturnUrl(page)).toBe(page);
});

it('turns a path into a URL of this site', () => {
// The karma page has <base href="/">, so no namespace goes in front of the path.
expect(aai.shibbolethReturnUrl('/mydspace')).toBe(window.location.origin + '/mydspace');
});

it('keeps the return on this site when the URL is of another site', () => {
expect(aai.shibbolethReturnUrl('https://example.org/items/1').startsWith(window.location.origin + '/')).toBeTrue();
});
});

describe('shibbolethLoginUrl', () => {
const opts = { host: 'https://ui.example', port: '', target: 'https://ui.example/server/api/authn/shibboleth' };

it('gives the backend the whole redirectUrl, with its own query string', () => {
const page = 'https://ui.example/search?query=corpus&page=2';

const loginUrl = new URL(aai.shibbolethLoginUrl(opts, page, 'https://idp.example/idp'));
// The SP decodes `target` once and sends the user there; the backend then reads `redirectUrl` from it.
const target = new URL(loginUrl.searchParams.get('target'));

expect(target.origin + target.pathname).toBe(opts.target);
expect(target.searchParams.get('redirectUrl')).toBe(page);
expect(loginUrl.searchParams.get('entityID')).toBe('https://idp.example/idp');
});
});
});
10 changes: 10 additions & 0 deletions src/app/core/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,16 @@ describe('AuthService test', () => {
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$')));
});

it('should send an expired session to the login page under the base href', () => {
const browserLocation = { href: '' };
(authService as any)._window = { nativeWindow: { location: browserLocation } };

authService.redirectToLoginWhenTokenExpired();

// The browser resolves the new href against <base href>, e.g. /repository/
expect(new URL(browserLocation.href, 'http://localhost:4000/repository/').href).toBe('http://localhost:4000/repository/login?expired=true');
});

describe('impersonate', () => {
const userId = 'testUserId';

Expand Down
3 changes: 2 additions & 1 deletion src/app/core/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,8 @@ export class AuthService {
const redirectUrl = LOGIN_ROUTE + '?expired=true';
if (this._window.nativeWindow.location) {
// Hard redirect to login page, so that all state is definitely lost
this._window.nativeWindow.location.href = redirectUrl;
// Relative to <base href>, like the `reload/` URL in navigateToRedirectUrl.
this._window.nativeWindow.location.href = '.' + redirectUrl;
} else {
this.router.navigateByUrl(redirectUrl);
}
Expand Down
28 changes: 28 additions & 0 deletions src/app/core/auth/server-auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { of } from 'rxjs';

import { AppConfig } from '../../../config/app-config.interface';
import { ServerAuthService } from './server-auth.service';

describe('ServerAuthService', () => {
let response: { redirect: jasmine.Spy };

const createService = (nameSpace: string): ServerAuthService => {
response = { redirect: jasmine.createSpy('redirect') };
const appConfig = { ui: { nameSpace } } as AppConfig;
// On the server there is no browser location, so the expired-session redirect is a 302.
const nativeWindowRef = { nativeWindow: {} } as any;
return new ServerAuthService({}, response, nativeWindowRef, null, null, null, null, null, of({}) as any, null, null, null, appConfig);
};

it('should send an expired session to the login page under the UI namespace', () => {
createService('/repository').redirectToLoginWhenTokenExpired();

expect(response.redirect).toHaveBeenCalledWith(302, '/repository/login?expired=true');
});

it('should send an expired session to /login when the UI runs at the root', () => {
createService('/').redirectToLoginWhenTokenExpired();

expect(response.redirect).toHaveBeenCalledWith(302, '/login?expired=true');
});
});
8 changes: 7 additions & 1 deletion src/app/core/auth/server-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import {
APP_CONFIG,
AppConfig,
} from '../../../config/app-config.interface';
import {
REQUEST,
RESPONSE,
Expand Down Expand Up @@ -57,6 +61,7 @@ export class ServerAuthService extends AuthService {
protected hardRedirectService: HardRedirectService,
protected notificationService: NotificationsService,
protected translateService: TranslateService,
@Inject(APP_CONFIG) protected appConfig: AppConfig,
) {
super(
_window,
Expand Down Expand Up @@ -123,7 +128,8 @@ export class ServerAuthService extends AuthService {
this._window.nativeWindow.location.href = redirectUrl;
} else if (this.response) {
if (!this.response._headerSent) {
this.response.redirect(302, redirectUrl);
// The browser resolves a 302 Location against the request path, not <base href>, so add the UI namespace.
this.response.redirect(302, this.appConfig.ui.nameSpace.replace(/\/$/, '') + redirectUrl);
}
} else {
this.router.navigateByUrl(redirectUrl);
Expand Down
57 changes: 55 additions & 2 deletions src/app/login-page/login-page.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import {
ActivatedRoute,
Params,
Router,
} from '@angular/router';
import { Store } from '@ngrx/store';
import { provideMockStore } from '@ngrx/store/testing';
import { TranslateModule } from '@ngx-translate/core';
Expand All @@ -16,12 +20,14 @@ import { XSRFService } from '../core/xsrf/xsrf.service';
import { AuthServiceMock } from '../shared/mocks/auth.service.mock';
import { ActivatedRouteStub } from '../shared/testing/active-router.stub';
import { EPersonMock } from '../shared/testing/eperson.mock';
import { RouterStub } from '../shared/testing/router.stub';
import { LoginPageComponent } from './login-page.component';

describe('LoginPageComponent', () => {
let comp: LoginPageComponent;
let fixture: ComponentFixture<LoginPageComponent>;
let authService: any;
let router: RouterStub;

const mockUser = EPersonMock;
const activatedRouteStub = Object.assign(new ActivatedRouteStub(), {
Expand All @@ -39,7 +45,9 @@ describe('LoginPageComponent', () => {
authService = Object.assign(new AuthServiceMock(), {
isAuthenticated: jasmine.createSpy('isAuthenticated').and.returnValue(of(false)),
getAuthenticatedUserFromStore: jasmine.createSpy('getAuthenticatedUserFromStore').and.returnValue(of(mockUser)),
getRedirectUrl: jasmine.createSpy('getRedirectUrl').and.returnValue(of(undefined)),
});
router = new RouterStub();

TestBed.configureTestingModule({
imports: [
Expand All @@ -49,9 +57,10 @@ describe('LoginPageComponent', () => {
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: AuthService, useValue: authService },
{ provide: Router, useValue: router },
{ provide: XSRFService, useValue: {} },
{ provide: APP_DATA_SERVICES_MAP, useValue: {} },
provideMockStore({}),
provideMockStore({ initialState: { core: { auth: { authenticated: false } } } }),
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
Expand Down Expand Up @@ -95,4 +104,48 @@ describe('LoginPageComponent', () => {
expect(comp.authenticatedUser).toBeNull();
});
});

// aai.js (DiscoJuice) takes the post-login target only from the `redirectUrl` query param of the page.
describe('redirectUrl query param', () => {
const initWith = (storedRedirectUrl: string, queryParams: Params = {}) => {
authService.getRedirectUrl.and.returnValue(of(storedRedirectUrl));
(comp as any).route = { queryParams: of(queryParams), snapshot: { queryParams } };
comp.ngOnInit();
};

it('puts the page stored by the auth guard into the login URL', () => {
initWith('/mydspace');

expect(router.navigate).toHaveBeenCalledWith(['/login'], {
queryParams: { redirectUrl: '/mydspace' },
queryParamsHandling: 'merge',
replaceUrl: true,
});
});

it('keeps a redirectUrl that is already in the URL', () => {
initWith('/mydspace', { redirectUrl: 'http://localhost:4000/login?redirectUrl=/mydspace' });

expect(router.navigate).not.toHaveBeenCalled();
});

it('keeps a stored URL with an access token out of the login URL', () => {
initWith('/bitstreams/123/download?accessToken=abc');

expect(router.navigate).not.toHaveBeenCalled();
});

it('leaves the URL alone when no page is stored', () => {
initWith(undefined);

expect(router.navigate).not.toHaveBeenCalled();
});

it('does not navigate on the server', () => {
(comp as any).platformId = 'server';
initWith('/mydspace');

expect(router.navigate).not.toHaveBeenCalled();
});
});
});
Loading
Loading