[CORD-1504] Handling XOSPermissionDenied errors
Change-Id: Icc1c796505207469d7416457802a3b9090031f72
diff --git a/src/app/datasources/rest/auth.rest.spec.ts b/src/app/datasources/rest/auth.rest.spec.ts
index 35732a3..7a406db 100644
--- a/src/app/datasources/rest/auth.rest.spec.ts
+++ b/src/app/datasources/rest/auth.rest.spec.ts
@@ -87,4 +87,37 @@
// httpBackend.flush();
});
});
+
+ describe('the handleUnauthenticatedRequest method', () => {
+
+ beforeEach(() => {
+ spyOn(service, 'clearUser');
+ });
+
+ it('should logout the user and redirect to login', () => {
+ service.handleUnauthenticatedRequest({
+ error: 'XOSPermissionDenied',
+ fields: {},
+ specific_error: 'test'
+ });
+ expect(service.clearUser).toHaveBeenCalled();
+ });
+
+ it('should catch errors from strings', () => {
+ service.handleUnauthenticatedRequest('{"fields": {}, "specific_error": "failed to authenticate token g09et150o2s25kdzg8t2n9wotvds9jyl", "error": "XOSPermissionDenied"}');
+ expect(service.clearUser).toHaveBeenCalled();
+ });
+
+ it('should not catch other errors', () => {
+ service.handleUnauthenticatedRequest({
+ error: 'XOSProgrammingError',
+ fields: {},
+ specific_error: 'test'
+ });
+ expect(service.clearUser).not.toHaveBeenCalled();
+
+ service.handleUnauthenticatedRequest('some error');
+ expect(service.clearUser).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/app/datasources/rest/auth.rest.ts b/src/app/datasources/rest/auth.rest.ts
index 81c4f7d..82f71b6 100644
--- a/src/app/datasources/rest/auth.rest.ts
+++ b/src/app/datasources/rest/auth.rest.ts
@@ -16,12 +16,19 @@
email: string;
}
+export interface IXosRestError {
+ error: string;
+ specific_error: string;
+ fields: any;
+}
+
export interface IXosAuthService {
login(data: IAuthRequestData): Promise<any>;
logout(): Promise<any>;
getUser(): any; // NOTE how to define return user || false ???
isAuthenticated(): boolean;
clearUser(): void;
+ handleUnauthenticatedRequest(error: IXosRestError | string): void;
}
export class AuthService {
@@ -29,7 +36,8 @@
private $http: angular.IHttpService,
private $q: angular.IQService,
private $cookies: angular.cookies.ICookiesService,
- private AppConfig: IXosAppConfig
+ private AppConfig: IXosAppConfig,
+ private $state: angular.ui.IStateService
) {
}
@@ -84,4 +92,29 @@
const session = this.$cookies.get('sessionid');
return angular.isDefined(session);
}
+
+ public handleUnauthenticatedRequest(res: IXosRestError | string): void {
+ let err;
+ if (angular.isString(res)) {
+ try {
+ err = JSON.parse(res);
+ } catch (e) {
+ // NOTE if it's not JSON it means that is not the error we're handling here
+ return;
+ }
+ }
+
+ if (angular.isObject(res)) {
+ err = res;
+ }
+
+ if (err && err.error) {
+ switch (err.error) {
+ case 'XOSPermissionDenied':
+ this.clearUser();
+ this.$state.go('login');
+ break;
+ }
+ }
+ }
}