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
132 changes: 125 additions & 7 deletions src/app/services/sessionService.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { TestBed, tick, fakeAsync } from '@angular/core/testing';
import { SessionService } from '../../assets/wise5/services/sessionService';
import { ConfigService } from '../../assets/wise5/services/configService';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { of, throwError } from 'rxjs';
import { HttpClient, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
let service: SessionService;
let configService: ConfigService;

Expand All @@ -23,6 +23,8 @@ describe('SessionService', () => {
checkMouseevent();
checkForLogout();
renewSession();
serverAnswers();
leaveClosedSite();
});

function calculateIntervals() {
Expand Down Expand Up @@ -94,15 +96,15 @@ function checkForLogout() {
describe('checkForLogout()', () => {
it('should force logout when user is inactive for long enough', () => {
spyOn(service, 'isInactiveLongEnoughToForceLogout').and.returnValue(true);
spyOn(service, 'checkIfSessionIsActive').and.returnValue(of(false));
spyOn(service, 'checkSession').and.returnValue(of('ended'));
const forceLogOutSpy = spyOn(service, 'forceLogOut');
service.checkForLogout();
expect(forceLogOutSpy).toHaveBeenCalled();
});

it('should not force logout when user is inactive for long enough but session is active', () => {
spyOn(service, 'isInactiveLongEnoughToForceLogout').and.returnValue(true);
spyOn(service, 'checkIfSessionIsActive').and.returnValue(of(true));
spyOn(service, 'checkSession').and.returnValue(of('active'));
const forceLogOutSpy = spyOn(service, 'forceLogOut');
service.checkForLogout();
expect(forceLogOutSpy).not.toHaveBeenCalled();
Expand All @@ -122,19 +124,135 @@ function checkForLogout() {
function renewSession() {
describe('renewSession()', () => {
it('should renew the session', fakeAsync(() => {
spyOn(service, 'checkIfSessionIsActive').and.returnValue(of(true));
spyOn(service, 'checkSession').and.returnValue(of('active'));
const logOutSpy = spyOn(service, 'logOut');
service.renewSession();
tick();
expect(logOutSpy).not.toHaveBeenCalled();
}));

it('should log the user out when renew session fails', fakeAsync(() => {
spyOn(service, 'checkIfSessionIsActive').and.returnValue(of(false));
spyOn(service, 'checkSession').and.returnValue(of('ended'));
const logOutSpy = spyOn(service, 'logOut');
service.renewSession();
tick();
expect(logOutSpy).toHaveBeenCalled();
}));
});
}

function serverAnswers() {
describe('the answer to a session renewal', () => {
let http: HttpTestingController;
let navigateSpy: jasmine.Spy;

beforeEach(() => {
spyOn(configService, 'getConfigParam').and.returnValue('/api/session/renew');
spyOn(configService, 'getSessionLogOutURL').and.returnValue('/api/logout');
http = TestBed.inject(HttpTestingController);
navigateSpy = jasmine.createSpy('navigateTo');
(service as any).navigateTo = navigateSpy;
});

it('should sign out when the session has ended', fakeAsync(() => {
const logOutSpy = spyOn(service, 'logOut');
service.renewSession();
http.expectOne('/api/session/renew').flush('false');
tick();
expect(logOutSpy).toHaveBeenCalled();
}));

it('should sign out to the sign-in page when sign-in has been disabled', fakeAsync(() => {
service.renewSession();
http.expectOne('/api/session/renew').flush('requestLogout');
tick();
http.expectOne('/api/logout').flush({});
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should keep the user signed in when the answer is empty', fakeAsync(() => {
const logOutSpy = spyOn(service, 'logOut');
service.renewSession();
http.expectOne('/api/session/renew').flush('');
tick();
expect(logOutSpy).not.toHaveBeenCalled();
http.verify();
}));
});
}

function leaveClosedSite() {
describe('when sign-in has been closed', () => {
let navigateSpy: jasmine.Spy;
let logOutRequest: jasmine.Spy;

beforeEach(() => {
spyOn(service, 'checkSession').and.returnValue(of('closed'));
spyOn(configService, 'getSessionLogOutURL').and.returnValue('/api/logout');
logOutRequest = spyOn(TestBed.inject(HttpClient), 'get').and.returnValue(of({}));
navigateSpy = spyOn<any>(service, 'navigateTo');
});

it('should save unsaved work before signing out', fakeAsync(() => {
let finishSave: () => void;
service.registerExitSaver(() => new Promise<void>((resolve) => (finishSave = resolve)));
service.renewSession();
tick();
expect(logOutRequest).not.toHaveBeenCalled();
finishSave();
tick();
expect(logOutRequest).toHaveBeenCalledWith('/api/logout');
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should sign out anyway when a save never answers', fakeAsync(() => {
service.registerExitSaver(() => new Promise<void>(() => {}));
service.renewSession();
tick(9999);
expect(navigateSpy).not.toHaveBeenCalled();
tick(1);
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should not save work whose component has gone', fakeAsync(() => {
const save = jasmine.createSpy('save').and.returnValue(Promise.resolve());
const unregister = service.registerExitSaver(save);
unregister();
service.renewSession();
tick();
expect(save).not.toHaveBeenCalled();
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should sign out even when a save throws before it starts', fakeAsync(() => {
service.registerExitSaver(() => {
throw new TypeError('no node status');
});
service.renewSession();
tick();
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should try again at the next renewal when signing out fails', fakeAsync(() => {
logOutRequest.and.returnValues(
throwError(() => new Error('network')),
of({})
);
service.renewSession();
tick();
expect(navigateSpy).not.toHaveBeenCalled();
service.renewSession();
tick();
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));

it('should leave an idle session the same way', fakeAsync(() => {
spyOn(service, 'isInactiveLongEnoughToForceLogout').and.returnValue(true);
const forceLogOutSpy = spyOn(service, 'forceLogOut');
service.checkForLogout();
tick();
expect(forceLogOutSpy).not.toHaveBeenCalled();
expect(navigateSpy).toHaveBeenCalledWith('/login?loginDisabled=true');
}));
});
}
80 changes: 73 additions & 7 deletions src/assets/wise5/services/sessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { HttpClient } from '@angular/common/http';
import { ConfigService } from './configService';
import { map, Observable, Subject } from 'rxjs';

export type SessionState = 'active' | 'ended' | 'closed' | 'unknown';

const EXIT_SAVE_TIMEOUT_MILLISECONDS = 10000;

@Injectable()
export class SessionService {
private warningVisible: boolean = false;
Expand All @@ -20,6 +24,8 @@ export class SessionService {
private logOutSource: Subject<void> = new Subject<void>();
public logOut$ = this.logOutSource.asObservable();
private sessionActive: boolean = true;
private exitSavers = new Set<() => Promise<unknown>>();
private leavingClosedSite: boolean = false;

constructor(
protected http: HttpClient,
Expand Down Expand Up @@ -118,9 +124,13 @@ export class SessionService {

checkForLogout(): void {
if (this.isInactiveLongEnoughToForceLogout()) {
this.checkIfSessionIsActive().subscribe((isSessionActive) => {
this.sessionActive = isSessionActive;
if (!isSessionActive) {
this.checkSession().subscribe((state) => {
if (state === 'closed') {
this.leaveClosedSite();
return;
}
this.sessionActive = state !== 'ended';
if (state === 'ended') {
this.forceLogOut();
}
});
Expand Down Expand Up @@ -175,15 +185,71 @@ export class SessionService {
this.renewSession();
}

checkIfSessionIsActive(): Observable<boolean> {
return this.http.get<boolean>(this.configService.getConfigParam('renewSessionURL'));
checkSession(): Observable<SessionState> {
return this.http
.get(this.configService.getConfigParam('renewSessionURL'), { responseType: 'text' })
.pipe(
map((answer: string): SessionState => {
switch ((answer ?? '').trim()) {
case 'true':
return 'active';
case 'false':
return 'ended';
case 'requestLogout':
return 'closed';
default:
return 'unknown';
}
})
);
}

renewSession(): void {
this.checkIfSessionIsActive().subscribe((isSessionActive) => {
if (!isSessionActive) {
this.checkSession().subscribe((state) => {
if (state === 'closed') {
this.leaveClosedSite();
} else if (state === 'ended') {
this.logOut();
}
});
}

/**
* Registers work to save before the user is signed out because sign-in has been disabled.
* @return a function that unregisters it
*/
registerExitSaver(save: () => Promise<unknown>): () => void {
this.exitSavers.add(save);
return () => this.exitSavers.delete(save);
}

/**
* The session is still valid when sign-in is disabled, so unsaved work can be saved before
* signing out. If signing out fails, the next renewal tries again, because the sign-in page would
* send a user whose session is still valid back to where they were.
*/
private leaveClosedSite(): void {
if (this.leavingClosedSite) {
return;
}
this.leavingClosedSite = true;
const saves = Promise.allSettled(
[...this.exitSavers].map((save) => Promise.resolve().then(save))
);
let timer: ReturnType<typeof setTimeout>;
const timeout = new Promise(
(resolve) => (timer = setTimeout(resolve, EXIT_SAVE_TIMEOUT_MILLISECONDS))
);
Promise.race([saves, timeout]).then(() => {
clearTimeout(timer);
this.logOutWithoutHomeRedirect().subscribe({
next: () => this.navigateTo('/login?loginDisabled=true'),
error: () => (this.leavingClosedSite = false)
});
});
}

protected navigateTo(url: string): void {
window.location.href = url;
}
}
8 changes: 8 additions & 0 deletions src/assets/wise5/vle/node/node.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,14 @@ export class NodeComponent implements OnInit {
this.stopAutoSaveInterval();
})
);
this.subscriptions.add(
this.sessionService.registerExitSaver(() => {
this.stopAutoSaveInterval();
return this.dirtyComponentIds.length
? this.createAndSaveComponentData(true)
: Promise.resolve();
})
);
}

protected saveComponentState($event: any): Promise<any> {
Expand Down
Loading