227 lines
7.0 KiB
TypeScript

/** @file
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import { Injectable } from '@angular/core';
import { environment } from 'environments/environment';
import { HTTPMimeType, HTTPRequestModel, HttpWrapperService, ModelResponseHttp } from './http-wrapper';
import { StorageService } from 'common/service/local-storage';
import { SessionService } from './session';
import { SSOService } from './sso';
interface MessageLogIn {
login: string;
method: string;
time: number;
password: string;
}
interface MessageAnswer_USER_CONNECT {
sessionId: string,
login: string,
eMail: string,
role: string,
avatar: string
}
declare function SHA512(param1: any): any;
@Injectable()
export class UserService {
// 0: Not hide password; 1 hide password;
private identificationVersion: number = 1;
private cookiesRememberMe = 'remember-me';
private cookiesToken = 'token';
constructor(
private storageService: StorageService,
private http: HttpWrapperService,
private sessionService: SessionService,
private ssoService: SSOService) {
console.log('Start UserService');
}
/**
* Disconnect the user from the current session ==> this remove the curreent Token
*/
logOut(): void {
this.removeSession();
this.ssoService.requestSignOut("home");
}
removeSession(): void {
this.storageService.remove(this.cookiesRememberMe);
this.storageService.removeSession(this.cookiesToken);
this.sessionService.destroy();
}
private isTokenUpToDate(token: string): boolean {
if (token === null || token === undefined || token.length < 25) {
return false;
}
// Separate the Data:
const elems = token.split('.');
if (elems.length !== 3 ) {
return false;
}
const tokenHeader = decodeURIComponent(escape(window.atob( elems[0] )));
const tokenData = decodeURIComponent(escape(window.atob( elems[1] )));
console.error(`Retreive local token: \nheader=${tokenHeader} \ndata=${tokenData}`);
const parsedData = JSON.parse(tokenData);
console.error(`Retreive exp data=${new Date(parsedData.exp*1000).toISOString()} < ${new Date().toISOString()}`);
const expireIn = new Date(parsedData.exp*1000);
const nowTime = new Date();
// TODO: set a marging of 2 hours...
return expireIn > nowTime;
}
/**
* Check if the system can be connected
*/
checkAutoConnect(): Promise<void> {
let self = this;
return new Promise<void>((resolve, reject) => {
// Need to use the windows global route to prevent the log in cycle ...
// And in the mlain application position, the route does not have curently root the page
let pathName = window.location.pathname;
//console.log("start Path-name: '" + pathName + "'");
//console.log("check with: '" + environment.applName + "/sso/" + "'");
if (pathName.startsWith("/sso/") || pathName.startsWith(environment.applName + "/sso/")) {
console.log(" ==> SSo section");
reject();
return;
}
console.log(" ==> Check if need reconnect?");
let rememberMe = self.storageService.get(self.cookiesRememberMe)==="true";
// TODO: in case of jest reload ==> no need to manage the SSO ==> just keep the token ... it in enought...
let token = self.storageService.getSession(self.cookiesToken);
// TODO: check validity of th eToken:
if (self.isTokenUpToDate(token)) {
// remove in case of fail !!!
this.storageService.removeSession(this.cookiesToken);
self.startSession(token, rememberMe).then(() => {
resolve();
}).catch(() => {
// jump in the sign-in page (automatically of request remember-me)
if(rememberMe) {
// jump to the sso !!! (remove local data to prevent login loop)
this.storageService.remove(this.cookiesRememberMe);
this.storageService.removeSession(this.cookiesToken);
self.ssoService.requestSignIn();
reject();
}
resolve();
});
} else {
console.log(`Get previous connection ... `);
if(rememberMe) {
// jump to the sso !!! (remove local data to prevent login loop)
this.storageService.remove(this.cookiesRememberMe);
this.storageService.removeSession(this.cookiesToken);
self.ssoService.requestSignIn();
reject();
}
resolve();
}
});
}
startSession(token : string, rememberMe: boolean): Promise<string> {
let self = this;
return new Promise((resolve, reject) => {
self.retreiveMe(token).then(
(value2: boolean) => {
if(rememberMe === true) {
self.storageService.set(self.cookiesRememberMe, rememberMe?"true":"false");
}
// transfer the session token property
self.sessionService.setToken(token);
self.storageService.setSession(self.cookiesToken, token);
resolve(self.sessionService.getLogin());
}).catch(() => {
reject('sdfsdfsdf');
});
});
}
retreiveMe(token : string): Promise<boolean> {
console.log(`AuthService.loginWithToken ... '${ token }'`);
let self = this;
return new Promise((resolve, reject) => {
this.http.requestJson({
//server: 'karauth',
endPoint: 'users/me',
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
authorization: `Yota ${token}`, // special case, the token is set after this request...
}).then((response: ModelResponseHttp) =>{
// TODO: check type ...
console.log(`loginWithToken : get some data to check: ${JSON.stringify(response.data)}`)
self.sessionService.create(
response.data.sessionId,
response.data.id,
response.data.login,
response.data.email,
response.data.role,
response.data.avatar);
resolve(true);
}).catch((error:any) => {
reject(`return ERROR ${ JSON.stringify(error, null, 2)}`);
});
});
}
create(login : string, email : string, password : string) {
return this.createSha(login, email, SHA512(password));
}
createSha(login : string, email : string, password : string) {
let data = {
method: 'v?',
login: login,
email: email,
password: password
};
console.log(`call users data=${ JSON.stringify(data, null, 2)}`);
if(this.identificationVersion === 1) {
data.method = 'v1';
}
return new Promise((resolve, reject) => {
this.http.requestJson({
server: 'karauth',
endPoint: 'users',
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
body: data,
}).then((response: ModelResponseHttp) =>{
// TODO: check type ...
console.log(`createSha : get some data to check: ${JSON.stringify(response.data)}`)
resolve(response.data);
}).catch((error:any) => {
reject(`return ERROR ${ JSON.stringify(error, null, 2)}`);
});
});
}
isAuthenticated():boolean {
// return !!Session.userId;
return false;
}
isAuthorized(authorizedRoles: string): boolean {
/*
if (!angular.isArray(_authorizedRoles)) {
authorizedRoles = [_authorizedRoles];
}
return ( authService.isAuthenticated()
&& _authorizedRoles.indexOf(Session.userRole) !== -1
);
*/
return false;
}
}