#103 moved auth service to core library

This commit is contained in:
Denys Vuika
2016-05-27 12:55:39 +01:00
parent 48fe2264d3
commit cdb7a0a359
9 changed files with 22 additions and 33 deletions

View File

@@ -0,0 +1,118 @@
/*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { it, describe, beforeEach } from 'angular2/testing';
import { provide, Injector } from 'angular2/core';
import { Http, HTTP_PROVIDERS, XHRBackend, Response, ResponseOptions } from 'angular2/http';
import { MockBackend } from 'angular2/http/testing';
import { AlfrescoAuthenticationService } from './alfresco-authentication.service';
describe('AlfrescoAuthentication', () => {
let injector,
backend,
mockBackend,
httpService,
service;
beforeEach(() => {
injector = Injector.resolveAndCreate([
HTTP_PROVIDERS,
MockBackend,
provide(XHRBackend, {useClass: MockBackend}),
AlfrescoAuthenticationService
]);
let store = {};
spyOn(localStorage, 'getItem').and.callFake(function (key) {
return store[key];
});
spyOn(localStorage, 'setItem').and.callFake(function (key, value) {
return store[key] = value + '';
});
spyOn(localStorage, 'clear').and.callFake(function () {
store = {};
});
spyOn(localStorage, 'removeItem').and.callFake(function (key) {
delete store[key];
});
spyOn(localStorage, 'key').and.callFake(function (i) {
let keys = Object.keys(store);
return keys[i] || null;
});
mockBackend = injector.get(MockBackend);
backend = injector.get(XHRBackend);
httpService = injector.get(Http);
service = injector.get(AlfrescoAuthenticationService);
});
it('should return true and token if the user is logged in', () => {
service.saveJwt('fake-local-token');
expect(service.isLoggedIn()).toBe(true);
expect(localStorage.getItem('token')).toBeDefined();
expect(localStorage.getItem('token')).toEqual('fake-local-token');
});
it('should return false and token undefined if the user is not logged in', () => {
expect(service.isLoggedIn()).toEqual(false);
expect(localStorage.getItem('token')).not.toBeDefined();
});
it('should return true and token on sign in', () => {
backend.connections.subscribe(connection => {
connection.mockRespond(new Response(new ResponseOptions({body: {data: {ticket: 'fake-post-token'}}})));
});
service.token = '';
service.login('POST', 'fakeUser', 'fakePassword')
.subscribe(() => {
expect(service.isLoggedIn()).toBe(true);
expect(service.token).toEqual('fake-post-token');
expect(localStorage.getItem('token')).toBeDefined();
expect(localStorage.getItem('token')).toEqual('fake-post-token');
}
);
});
it('should return false and token undefined on log out', () => {
service.token = 'fake-token';
localStorage.setItem('token', 'fake-token');
service.logout()
.subscribe(() => {
expect(service.isLoggedIn()).toBe(false);
expect(service.token).not.toBeDefined();
expect(localStorage.getItem('token')).not.toBeDefined();
}
);
});
it('should return no error if method value is GET', () => {
expect(service.login('GET', 'fakeUser', 'fakePassword').hasErrored).toBe(false);
});
it('should return no error if method value is POST', () => {
expect(service.login('POST', 'fakeUser', 'fakePassword').hasErrored).toBe(false);
});
it('should throw an exception if method value is different from GET or POST', () => {
expect(service.login('PUT', 'fakeUser', 'fakePassword').error).toEqual('Invalid method name the value should be GET or POST');
});
});

View File

@@ -0,0 +1,136 @@
/*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Rx';
import { Http, Headers, Response } from 'angular2/http';
/**
* The AlfrescoAuthenticationService provide the login service and store the token in the localStorage
*/
@Injectable()
export class AlfrescoAuthenticationService {
token: string;
private _host: string = 'http://192.168.99.100:8080';
private _baseUrl: string = this._host + '/alfresco/api/-default-/public/authentication/versions/1';
/**
* Constructor
* @param http
*/
constructor(public http: Http) {
this.token = localStorage.getItem('token');
}
/**
* The method return tru if the user is logged in
* @returns {boolean}
*/
isLoggedIn() {
return !!localStorage.getItem('token');
}
/**
* Method to delegate to POST login
* @param username
* @param password
* @returns {Observable<R>|Observable<T>}
*/
login(username: string, password: string) {
return this.loginPost(username, password);
}
/**
* The method provide the login with POST Request
* @param username
* @param password
* @returns {Observable<R>|Observable<T>}
*/
loginPost(username: string, password: string) {
let credentials = '{ "userId": "' + username + '", "password": "' + password + '" }';
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return this.http.post(this._baseUrl + '/tickets', credentials, {
headers: headers
})
.map((res: any) => {
let response = res.json();
this.token = response.entry.id;
this.saveJwt(this.token);
})
.catch(this.handleError);
}
/**
* Delete the current login ticket from the server
*
* @returns {Observable<R>|Observable<T>}
*/
loginDelete() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Basic ' + btoa(this.token));
return this.http.delete(this._baseUrl + '/tickets/-me-', {
headers: headers
})
.map((res: any) => {
this.removeJwt();
this.token = undefined;
})
.catch(this.handleError);
}
/**
* The method save the toke in the localStorage
* @param jwt
*/
saveJwt(jwt) {
if (jwt) {
localStorage.setItem('token', jwt);
}
}
/**
* Remove the login token from localStorage
*/
removeJwt() {
localStorage.removeItem('token');
}
/**
* The method remove the token from the local storage
* @returns {Observable<T>}
*/
logout() {
return this.loginDelete();
}
/**
* The method write the error in the console browser
* @param error
* @returns {ErrorObservable}
*/
private handleError(error: Response) {
console.error('Error when logging in', error);
return Observable.throw(error.json().message || 'Server error');
}
}