[DEV] rework to manage secure connection

This commit is contained in:
Edouard DUPIN 2022-05-21 00:57:55 +02:00
parent 0aefa81c1d
commit f71b88a459
18 changed files with 3822 additions and 3838 deletions

View File

@ -4,6 +4,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karideo.ConfigVariable;
import org.kar.karideo.GenericContext;
import org.kar.karideo.Secured;
import org.kar.karideo.WebLauncher;
import org.kar.karideo.db.DBEntry;
import org.kar.karideo.model.Data;
@ -324,6 +325,7 @@ public class DataResource {
return null;
}
@Secured
@POST
@Path("/upload/")
@Consumes({MediaType.MULTIPART_FORM_DATA})
@ -346,7 +348,7 @@ public class DataResource {
//return null;
}
//@Secured
@Secured
@GET
@Path("{id}")
@RolesAllowed("USER")
@ -365,7 +367,7 @@ public class DataResource {
}
return buildStream(ConfigVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
}
//@Secured
@Secured
@GET
@Path("thumbnail/{id}")
@RolesAllowed("USER")
@ -412,7 +414,7 @@ public class DataResource {
}
return buildStream(filePathName, range, value.mimeType);
}
//@Secured
@Secured
@GET
@Path("{id}/{name}")
@RolesAllowed("USER")

View File

@ -15,9 +15,21 @@ CREATE TABLE `node` (
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MediaSmall {
public class MediaStreamProperty {
public Long id;
public Long timeSecond;
public Long width;
public Long height;
public Map<String, Long> videos = new HashMap<>();
public Map<String, Long> audios = new HashMap<>();
public Map<String, Long> subtitles = new HashMap<>();
}
public Long id;
public String name;
public String description;
@ -31,6 +43,7 @@ public class MediaSmall {
public Integer time;
public String ageLimit;
public List<Long> covers = new ArrayList<>();
public MediaStreamProperty media;
public MediaSmall(ResultSet rs) {
int iii = 1;

6646
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ import { AppRoutingModule } from './app-routing.module';
import { UploadFileComponent } from './component/upload-file/upload-file';
import { TopMenuComponent } from './component/top-menu/top-menu';
import { ElementDataImageComponent } from './component/data-image/data-image';
import { ElementTypeComponent } from './component/element-type/element-type';
import { ElementSeriesComponent } from './component/element-series/element-series';
import { ElementSeasonComponent } from './component/element-season/element-season';
@ -45,7 +46,7 @@ import { AuthService } from './service/auth';
import { ArianeService } from './service/ariane';
import { CookiesService } from './service/cookies';
import { HttpWrapperService } from './service/http-wrapper';
import { HttpOAuthWrapperService } from './service/http-oauth-wrapper';
//import { HttpOAuthWrapperService } from './service/http-oauth-wrapper';
import { UserService } from './service/user';
import { UniverseService } from './service/universe';
import { SeriesService } from './service/series';
@ -64,6 +65,7 @@ import { AppComponent } from './app.component';
AppComponent,
TopMenuComponent,
UploadFileComponent,
ElementDataImageComponent,
ElementTypeComponent,
ElementSeriesComponent,
ElementSeasonComponent,
@ -103,7 +105,7 @@ import { AppComponent } from './app.component';
providers: [
PopInService,
HttpWrapperService,
HttpOAuthWrapperService,
//HttpOAuthWrapperService,
BddService,
AuthService,
SessionService,

View File

@ -0,0 +1,3 @@
<div>
<canvas width="200" height="250" style="border:1px solid #d3d3d3;" id="imageCanvas" #imageCanvas></canvas>
</div>

View File

@ -0,0 +1,52 @@
.count-base {
height: 0px;
width: 100%;
right: 0px;
z-index: 12;
//position:flex;
text-align: right;
.count {
height: 30px;
//width: 30px;
font-size: 17px;
line-height: 30px;
overflow:hidden;
position:relative;
z-index: 12;
right: 2px;
top: 4px;
text-align: right;
padding: 5px 10px;
color: rgba(0, 0, 0, 1.0);
background: rgba(256, 256, 256, 0.3);
border: 1px solid;
border-color: rgba(256, 256, 256, 0.8);
border-radius: 15px;
}
}
.imgContainer-small {
text-align: center;
margin: 15px 0 0 0;
}
img.miniature-small {
width: 80px;
height: 80px;
//border-radius: 50%;
}
.title-small {
height: 60px;
font-size: 24px;
overflow:hidden;
vertical-align: middle;
}
.description-small {
height: 30px;
font-size: 12px;
overflow:hidden;
vertical-align: middle;
}

View File

@ -0,0 +1,47 @@
/** @file
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import { Injectable, Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { DataService } from '../../service/data';
@Component({
selector: 'data-image',
templateUrl: './data-image.html',
styleUrls: [ './data-image.less' ]
})
@Injectable()
export class ElementDataImageComponent implements OnInit {
// input parameters
@Input() id:number = -1;
imageCanvas:any;
@ViewChild('imageCanvas')
set mainDivEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.imageCanvas = el.nativeElement;
}
}
constructor(private dataService: DataService) {
}
ngOnInit() {
/*
let canvas = this.imageCanvas.nativeElement;
let ctx = canvas.getContext("2d");
*/
console.log(`Request thumnail for ---> ${this.id}`);
this.dataService.getImageThumbnail(this.id)
.then((result) => {
console.log(`plop ---> ${result.status}`);
}).catch(()=>{
console.log("plop ---> ");
});
//let img = new Image();
//img.src = "../../assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
//ctx.drawImage(img, 10, 10, 250, 250);
}
}

View File

@ -1,7 +1,7 @@
<div class="imgContainer-small">
<div *ngIf="cover">
<img src="{{cover}}"/>
<data-image id="{{cover}}"></data-image>
</div>
<div *ngIf="!cover" class="noImage">

View File

@ -40,7 +40,7 @@ export class ElementSeasonComponent implements OnInit {
self.cover = null;
// self.covers = [];
} else {
self.cover = self.seasonService.getCoverThumbnailUrl(response.covers[0]);
self.cover = response.covers[0];//self.seasonService.getCoverThumbnailUrl(response.covers[0]);
for(let iii = 0; iii < response.covers.length; iii++) {
self.covers.push(self.seasonService.getCoverThumbnailUrl(response.covers[iii]));
}

View File

@ -6,7 +6,7 @@
</div>
<div class="imgContainer-small">
<div *ngIf="cover">
<img src="{{cover}}"/>
<data-image id="{{cover}}"></data-image>
</div>
<div *ngIf="!cover" class="noImage">

View File

@ -43,9 +43,9 @@ export class ElementSeriesComponent implements OnInit {
self.cover = null;
// self.covers = [];
} else {
self.cover = self.seriesService.getCoverThumbnailUrl(response.covers[0]);
self.cover = response.covers[0];//self.seriesService.getCoverThumbnailUrl(response.covers[0]);
for(let iii = 0; iii < response.covers.length; iii++) {
self.covers.push(self.seriesService.getCoverThumbnailUrl(response.covers[iii]));
self.covers.push(response.covers[iii]);//self.seriesService.getCoverThumbnailUrl(response.covers[iii]));
}
}
}).catch((response) => {

View File

@ -1,7 +1,8 @@
<div>
<div class="videoImgContainer">
<div *ngIf="cover">
<img src="{{cover}}"/>
<data-image id="{{cover}}"></data-image>
<!--<img src="{{cover}}"/>-->
</div>
<div *ngIf="!cover" class="noImage">

View File

@ -64,7 +64,7 @@
</button>
</div>
<button class="item"
*ngIf="login == null"
*ngIf="login === null"
style="float:right;"
(click)="onSignIn($event)"
(auxclick)="onSignIn($event)">

View File

@ -108,6 +108,7 @@ export class BddService {
}
// brut force update of the BDD : TODO optimise it later ...
console.log(`Update BDD (${ name })`);
self.http.getSpecific(name)
.then((response) => {
console.log(`end download DB: ==> ${ name } ${ response.length}`);

View File

@ -6,14 +6,11 @@
import { Injectable } from '@angular/core';
import { HttpWrapperService } from './http-wrapper';
import { DataInterface } from './dataInterface';
import { HTTPMimeType, HTTPRequestModel, HttpWrapperService, ModelResponseHttp } from './http-wrapper';
@Injectable()
export class DataService {
// 0: Not hide password; 1 hide password;
private identificationVersion: number = 1;
private bdd: DataInterface = null;
private serviceName:string = 'data';
constructor(private http: HttpWrapperService) {
@ -37,5 +34,23 @@ export class DataService {
// return this.http.uploadFileMultipart(this.serviceName, null, _file);
return this.http.uploadMultipart(`${this.serviceName }/upload/`, _form, _progress);
}
getImage(_id:number) : Promise<ModelResponseHttp> {
return this.http.requestImage({
endPoint: this.serviceName,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.IMAGE,
contentType: HTTPMimeType.JSON,
});
}
getImageThumbnail(_id:number) : Promise<ModelResponseHttp> {
return this.http.requestImage({
endPoint: this.serviceName + "/thumbnail/" + _id,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.IMAGE,
contentType: HTTPMimeType.JSON,
});
}
}

View File

@ -1,430 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
@Injectable()
export class HttpOAuthWrapperService {
private displayReturn:boolean = false;
constructor(private http: HttpClient) {
}
createRESTCall(api:string, inputOptions?: any) {
let basePage = environment.apiOAuthUrl;
let addressServerRest = `${basePage }/`;
let options = inputOptions;
if(typeof options === 'undefined') {
options = [];
}
let out = addressServerRest + api;
let first = true;
for(let iii = 0; iii < options.length; iii++) {
if(first === false) {
out = `${out }&`;
} else {
out = `${out }?`;
first = false;
}
out = out + options[iii];
}
return out;
}
get(uriRest:string, headerOption:any, params:any) {
let connectionAdresse = this.createRESTCall(uriRest, {});
let config = {
params: params,
headers: new HttpHeaders(headerOption)
};
return new Promise((resolve, reject) => {
if(this.displayReturn === true) {
console.log(`call GET ${ connectionAdresse } params=${ JSON.stringify(params, null, 2)}`);
}
let request = this.http.get<any>(connectionAdresse, config);
let self = this;
request.subscribe((res: any) => {
if(self.displayReturn === true) {
console.log(`!! data ${ JSON.stringify(res, null, 2)}`);
}
if(res) {
if(res.httpCode) {
resolve({ status:res.httpCode, data:res });
} else {
resolve({ status:200, data:res });
}
} else {
resolve({ status:200, data:'' });
}
},
(error) => {
if(self.displayReturn === true) {
console.log(`an error occured status: ${ error.status}`);
console.log(`answer: ${ JSON.stringify(error, null, 2)}`);
}
reject({ status:error.status, data:error.error });
});
});
}
post(uriRest:string, headerOption:any, data:any) {
let connectionAdresse = this.createRESTCall(uriRest, {});
const httpOption = {
headers: new HttpHeaders(headerOption)
};
return new Promise((resolve, reject) => {
if(this.displayReturn === true) {
console.log(`call POST ${ connectionAdresse } data=${ JSON.stringify(data, null, 2)}`);
}
let request = this.http.post<any>(connectionAdresse, data, httpOption);
let self = this;
request.subscribe((res: any) => {
if(self.displayReturn === true) {
console.log(`!! data ${ JSON.stringify(res, null, 2)}`);
}
if(res) {
if(res.httpCode) {
resolve({ status:res.httpCode, data:res });
} else {
resolve({ status:200, data:res });
}
} else {
resolve({ status:200, data:'' });
}
},
(error) => {
if(self.displayReturn === true) {
console.log(`an error occured status: ${ error.status}`);
console.log(`answer: ${ JSON.stringify(error, null, 2)}`);
}
reject({ status:error.status, data:error.error });
});
});
}
put(uriRest:string, headerOption:any, data:any) {
let connectionAdresse = this.createRESTCall(uriRest, {});
const httpOption = {
headers: new HttpHeaders(headerOption)
};
return new Promise((resolve, reject) => {
if(this.displayReturn === true) {
console.log(`call POST ${ connectionAdresse } data=${ JSON.stringify(data, null, 2)}`);
}
let request = this.http.put<any>(connectionAdresse, data, httpOption);
let self = this;
request.subscribe((res: any) => {
if(self.displayReturn === true) {
console.log(`!! data ${ JSON.stringify(res, null, 2)}`);
}
if(res) {
if(res.httpCode) {
resolve({ status:res.httpCode, data:res });
} else {
resolve({ status:200, data:res });
}
} else {
resolve({ status:200, data:'' });
}
},
(error) => {
if(self.displayReturn === true) {
console.log(`an error occured status: ${ error.status}`);
console.log(`answer: ${ JSON.stringify(error, null, 2)}`);
}
reject({ status:error.status, data:error.error });
});
});
}
delete(uriRest:string, headerOption:any) {
let connectionAdresse = this.createRESTCall(uriRest, {});
const httpOption = {
headers: new HttpHeaders(headerOption)
};
return new Promise((resolve, reject) => {
if(this.displayReturn === true) {
console.log(`call POST ${ connectionAdresse}`);
}
let request = this.http.delete<any>(connectionAdresse, httpOption);
let self = this;
request.subscribe((res: any) => {
if(self.displayReturn === true) {
console.log(`!! data ${ JSON.stringify(res, null, 2)}`);
}
if(res) {
if(res.httpCode) {
resolve({ status:res.httpCode, data:res });
} else {
resolve({ status:200, data:res });
}
} else {
resolve({ status:200, data:'' });
}
},
(error) => {
if(self.displayReturn === true) {
console.log(`an error occured status: ${ error.status}`);
console.log(`answer: ${ JSON.stringify(error, null, 2)}`);
}
reject({ status:error.status, data:error.error });
});
});
}
uploadFileMultipart(base:string, id:number, file:File): any {
console.log(`Upload file to ${ base}`);
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
let formData = new FormData();
formData.append('upload', file);
let headers = new Headers();
console.log(`upload filename : ${ file.name}`);
let extention = file.name.split('.').pop();
if(extention === 'jpg') {
headers.append('Content-Type', 'image/jpeg');
} else if(extention === 'png') {
headers.append('Content-Type', 'image/png');
} else {
return null;
}
headers.append('filename', file.name);
const httpOption = {
headers: headers,
reportProgress: true,
};
return new Promise((resolve, reject) => {
this.post(url, httpOption, formData)
.then((response: any) => {
console.log(`URL: ${ url }\nRespond(${ response.status }): ${ JSON.stringify(response.data, null, 2)}`);
if(response.status === 200) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
});
});
}
/*
uploadFileBase64(base:string, id:number, file:File): any {
console.log(`Upload file to ${ base}`);
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
let self = this;
let reader = new FileReader();
reader.readAsArrayBuffer(file);
return new Promise((resolve, reject) => {
reader.onload = () => {
let headers = {};// new Headers();
console.log(`upload filename : ${ file.name}`);
let extention = file.name.split('.').pop();
if(extention === 'jpg') {
// headers.append('Content-Type', "image/jpeg");
headers['Content-Type'] = 'image/jpeg';
headers['mime-type'] = 'image/jpeg';
} else if(extention === 'jpeg') {
// headers.append('Content-Type', "image/jpeg");
headers['Content-Type'] = 'image/jpeg';
headers['mime-type'] = 'image/jpeg';
} else if(extention === 'webp') {
// headers.append('Content-Type', "image/webp");
headers['Content-Type'] = 'image/webp';
headers['mime-type'] = 'image/webp';
} else if(extention === 'png') {
// headers.append('Content-Type', "image/png");
headers['Content-Type'] = 'image/png';
headers['mime-type'] = 'image/png';
} else {
return null;
}
// headers.append('filename', _file.name);
headers.filename = file.name;
self.post(url, headers, reader.result)
.then((response: any) => {
console.log(`URL: ${ url }\nRespond(${ response.status }): ${ JSON.stringify(response.data, null, 2)}`);
if(response.status === 200) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject('return ERROR ...');// + JSON.stringify(response, null, 2));
}
});
};
});
}
*/
// Complex wrapper to simplify interaction:
getSpecific(base:string, id:number = null, subElement:string = '', select:Array<string> = []):any {
console.log(`Get All data from ${ base}`);
const httpOption = { 'Content-Type': 'application/json' };
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
if(subElement !== '') {
url = `${url }/${ subElement}`;
}
if(select.length !== 0) {
let out = '';
for(let iii = 0; iii < select.length; iii++) {
if(select.length !== 0) {
out = `${out }&`;
}
out = `${out }select=${ select[iii]}`;
}
url = `${url }?${ out}`;
}
// console.log("call GET " + url);
return new Promise((resolve, reject) => {
this.get(url, httpOption, {})
.then((response: any) => {
// console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
if(response.status === 200) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
});
});
}
// Complex wrapper to simplify interaction:
deleteSpecific(base:string, id:number, subElement:string = ''):any {
// console.log("delete data to " + _base);
const httpOption = { 'Content-Type': 'application/json' };
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
if(subElement !== '') {
url = `${url }/${ subElement}`;
}
// console.log("call DELETE: " + url);
// console.log(" data: " + JSON.stringify(_data, null, 2));
return new Promise((resolve, reject) => {
this.delete(url, httpOption)
.then((response: any) => {
// console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
if(response.status === 200) {
resolve(response.data);
return;
}
if(response.status === 201) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
});
});
}
// Complex wrapper to simplify interaction:
putSpecific(base:string, id:number, data:any, subElement:string = ''):any {
// console.log("put data to " + _base);
const httpOption = { 'Content-Type': 'application/json' };
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
if(subElement !== '') {
url = `${url }/${ subElement}`;
}
// console.log("call PUT: " + url);
// console.log(" data: " + JSON.stringify(_data, null, 2));
return new Promise((resolve, reject) => {
this.put(url, httpOption, data)
.then((response: any) => {
// console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
if(response.status === 200) {
resolve(response.data);
return;
}
if(response.status === 201) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
});
});
}
// Complex wrapper to simplify interaction:
postSpecific(base:string, id:number, data:any, subElement:string = ''):any {
// console.log("put data to " + _base);
const httpOption = { 'Content-Type': 'application/json' };
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
}
if(subElement !== '') {
url = `${url }/${ subElement}`;
}
// console.log("call PUT: " + url);
// console.log(" data: " + JSON.stringify(_data, null, 2));
return new Promise((resolve, reject) => {
this.post(url, httpOption, data)
.then((response: any) => {
// console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
if(response.status === 200) {
resolve(response.data);
return;
}
if(response.status === 201) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
});
});
}
}

View File

@ -11,6 +11,51 @@ import { environment } from '../../environments/environment';
import { SessionService } from './session';
export enum HTTPRequestModel {
POST = "POST",
GET = "GET",
PUT = "PUT",
DELETE = "DELETE",
PATCH = "PATCH",
}
export enum HTTPMimeType {
ALL = "*/*",
JSON = "application/json",
OCTET_STREAM = "application/octet-stream",
IMAGE = "image/*",
IMAGE_JPEG = "image/jpeg",
IMAGE_PNG = "image/png",
}
export interface HTTPRequest {
server?: string;
endPoint: string;
requestType: HTTPRequestModel ;
accept: HTTPMimeType;
contentType: HTTPMimeType;
params?: any;
body?: any;
authorization?: string; // c'est un hook de merde ...
disableTocken?:boolean;
}
/*
{
endPoint: ,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.ALL,
contentType: HTTPMimeType.JSON,
params?: ,
body?: ,
}
*/
export interface ModelResponseHttp{
status: number,
data: any,
}
/**
* This service permit to add some data like tocken and authorisation.. ir automatically get the token if needed and retake it if expired...
*/
@Injectable()
export class HttpWrapperService {
private displayReturn:boolean = false;
@ -19,6 +64,125 @@ export class HttpWrapperService {
}
addTokenIfNeeded(headerOption:any): any {
if(this.session.sessionData !== null) {
if(headerOption.authorization === undefined) {
headerOption.authorization = `Yota ${ this.session.sessionData.userId }:${ this.session.sessionData.token}`;
}
}
return headerOption;
}
request(properties: HTTPRequest) : Promise<Response> {
//uriRest:string, headerOption:any, params:any): Promise<{status:number, data:any}> {
console.log(`-------------------------------------------------------\nHTTP-wrapper GET '${ properties.endPoint }'\n\t\tparams=${ JSON.stringify(properties, null, 2)}`);
let connectionAdresse = this.createRESTCall2({
server: properties.server,
api: properties.endPoint
});
let headers: any = {
'Accept': properties.accept,
'Content-Type': properties.contentType,
'authorization': properties.authorization,
}
console.log(`disble tocken : ${JSON.stringify(properties)} properties.disableTocken=${properties.disableTocken}`);
if (properties.disableTocken === undefined || properties.disableTocken === null || properties.disableTocken === true) {
headers = this.addTokenIfNeeded(headers);
}
console.log(`header: ${JSON.stringify(headers)}`);
let body = properties.body;
if (properties.contentType === HTTPMimeType.JSON) {
body = JSON.stringify(properties.body);
}
const result = fetch(connectionAdresse, {
method: properties.requestType,
headers,
body
})
return result;
};
requestJson(properties: HTTPRequest) : Promise<ModelResponseHttp> {
return new Promise((resolve, reject) => {
this.request(properties).then((response: Response) => {
if(response.status >= 200 && response.status <= 299) {
const contentType = response.headers.get('Content-Type');
if (contentType === HTTPMimeType.JSON) {
response.json().then((value:any) => {
//console.log(`REICEIVE ==> ${response.status}=${ JSON.stringify(value, null, 2)}`);
resolve({ status:response.status, data:value });
}).catch((reason:any)=> {
reject({ status:999, data:reason });
});
} else {
console.error(`content Type is not Json: ${contentType}`)
reject({ status:999, data:`content Type is not Json: ${contentType}` });
}
} else {
console.error(`wring correct status: ${response.status}`)
reject({ status:900, data: response });
}
}).catch((error: any) => {
reject({ status:error.status, data:error.error });
});
});
};
requestImage(properties: HTTPRequest) : Promise<ModelResponseHttp> {
return new Promise((resolve, reject) => {
this.request(properties).then((response: Response) => {
if(response.status >= 200 && response.status <= 299) {
const contentType = response.headers.get('Content-Type');
//console.log(`REICEIVE ==> ${response.status}`);
resolve({ status:900, data: response });
/*
resolve({ status:response.status, data:value });
}).catch((reason:any)=> {
reject({ status:999, data:reason });
});
} else {
console.error(`content Type is not Json: ${contentType}`)
reject({ status:999, data:`content Type is not Json: ${contentType}` });
}
*/
} else {
console.error(`wring correct status: ${response.status}`)
resolve({ status:900, data: response });
}
}).catch((error: any) => {
reject({ status:error.status, data:error.error });
});
});
}
createRESTCall2({ api, server, inputOptions }: { server?: string; api: string; inputOptions?: any[]; }) {
let basePage = environment.apiUrl;
if (server === "karauth") {
basePage = environment.apiOAuthUrl;
}
let addressServerRest = `${basePage }/`;
let options = inputOptions;
if(options === undefined) {
options = [];
}
let out = addressServerRest + api;
let first = true;
for(let iii = 0; iii < options.length; iii++) {
if(first === false) {
out = `${out }&`;
} else {
out = `${out }?`;
first = false;
}
out = out + options[iii];
}
return out;
}
createRESTCall(api: string, inputOptions?: any) {
let basePage = environment.apiUrl;
let addressServerRest = `${basePage }/`;
@ -40,53 +204,35 @@ export class HttpWrapperService {
return out;
}
addTokenIfNeeded(headerOption:any): any {
if(this.session.sessionData !== null) {
if(headerOption.authorization === undefined) {
headerOption.authorization = `Yota ${ this.session.sessionData.userId }:${ this.session.sessionData.token}`;
}
}
return headerOption;
}
get(uriRest:string, headerOption:any, params:any) {
this.addTokenIfNeeded(headerOption);
get(uriRest:string, headerOption:any, params:any): Promise<{status:number, data:any}> {
console.log(`-------------------------------------------------------\nHTTP-wrapper GET '${ uriRest }'\n\t\theaderOption=${ JSON.stringify(headerOption, null, 2)}\n\t\tparams=${ JSON.stringify(params, null, 2)}`);
let connectionAdresse = this.createRESTCall(uriRest, {});
let config = {
params: params,
headers: new HttpHeaders(headerOption)
};
const headers = this.addTokenIfNeeded(headerOption);
let self = this;
return new Promise((resolve, reject) => {
if(this.displayReturn === true) {
console.log(`call GET ${ connectionAdresse } params=${ JSON.stringify(params, null, 2)}`);
}
let request = this.http.get<any>(connectionAdresse, config);
let self = this;
request.subscribe((res: any) => {
if(self.displayReturn === true) {
console.log(`!! data ${ JSON.stringify(res, null, 2)}`);
}
if(res) {
if(res.httpCode) {
resolve({ status:res.httpCode, data:res });
} else {
resolve({ status:200, data:res });
}
fetch(connectionAdresse, {
method: "GET",
headers,
}).then((response: Response) => {
if(response.status === 200) {
response.json().then((value:any) => {
//console.log(`REICEIVE ==> ${response.status}=${ JSON.stringify(value, null, 2)}`);
resolve({ status:response.status, data:response.body });
}).catch((reason:any)=> {
reject({ status:999, data:reason });
});
} else {
resolve({ status:200, data:'' });
}
},
(error) => {
if(self.displayReturn === true) {
console.log(`an error occured status: ${ error.status}`);
console.log(`answer: ${ JSON.stringify(error, null, 2)}`);
resolve({ status:900, data:'' });
}
}).catch((error: any) => {
reject({ status:error.status, data:error.error });
});
});
}
post(uriRest:string, headerOption:any, data:any, progress:any = null) {
console.log(`-------------------------------------------------------\nHTTP-wrapper POST '${ uriRest }'\n\t\theaderOption=${ JSON.stringify(headerOption, null, 2)}\n\t\tdata=${ JSON.stringify(data, null, 2)}`);
this.addTokenIfNeeded(headerOption);
let connectionAdresse = this.createRESTCall(uriRest, {});
@ -160,6 +306,7 @@ export class HttpWrapperService {
});
}
put(uriRest:string, headerOption:any, data:any) {
console.log(`-------------------------------------------------------\nHTTP-wrapper PUT '${ uriRest }'\n\t\theaderOption=${ JSON.stringify(headerOption, null, 2)}\n\t\tdata=${ JSON.stringify(data, null, 2)}`);
this.addTokenIfNeeded(headerOption);
let connectionAdresse = this.createRESTCall(uriRest, {});
const httpOption = {
@ -424,42 +571,15 @@ export class HttpWrapperService {
});
}
/*
public upload(base:string, id:number, file:File): any {
data, userId) {
}
let uploadURL = `${this.SERVER_URL}/auth/${userId}/avatar`;
return this.http.post<any>(uploadURL, data, {
reportProgress: true,
observe: 'events'
}).pipe(map((event) => {
switch (event.type) {
case HttpEventType.UploadProgress:
const progress = Math.round(100 * event.loaded / event.total);
return { status: 'progress', message: progress };
case HttpEventType.Response:
return event.body;
default:
return `Unhandled event: ${event.type}`;
}
})
);
}
*/
// Complex wrapper to simplify interaction:
getSpecific(base:string, id:number = null, subElement:string = '', select:string[] = []):any {
console.log(`Get All data from ${ base}`);
const httpOption = { 'Content-Type': 'application/json' };
//console.log(`Get All data from ${ base}`);
let url = base;
if(id !== null) {
url = `${url }/${ id}`;
url = `${url}/${id}`;
}
if(subElement !== '') {
url = `${url }/${ subElement}`;
url = `${url}/${subElement}`;
}
if(select.length !== 0) {
let newValue = '';
@ -471,18 +591,23 @@ export class HttpWrapperService {
}
url = `${url}?${newValue}`;
}
// console.log("call GET " + url);
//console.log("call GET " + url);
return new Promise((resolve, reject) => {
this.get(url, httpOption, {})
.then((response: any) => {
// console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
this.requestJson({
endPoint: url,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
})
.then((response: ModelResponseHttp) => {
//console.log("URL: " + url + "\nRespond(" + response.status + "): " + JSON.stringify(response.data, null, 2));
if(response.status === 200) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
}, (response: ModelResponseHttp) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {

View File

@ -6,8 +6,7 @@
import { Injectable } from '@angular/core';
import { HttpOAuthWrapperService } from './http-oauth-wrapper';
import { HttpWrapperService } from './http-wrapper';
import { HTTPMimeType, HTTPRequestModel, HttpWrapperService, ModelResponseHttp } from './http-wrapper';
interface MessageLogIn {
login: string;
@ -32,8 +31,7 @@ export class UserService {
// 0: Not hide password; 1 hide password;
private identificationVersion: number = 1;
constructor(private httpOAuth: HttpOAuthWrapperService,
private http: HttpWrapperService) {
constructor(private http: HttpWrapperService) {
console.log('Start UserService');
}
@ -65,7 +63,7 @@ export class UserService {
});
}
getTocken(login : string, password : string) {
getTocken(login : string, password : string) : Promise<any> {
console.log(`AuthService.getToken ... '${ login }':'${ password }'`);
let currentDate:number = dateFormat(new Date(), 'm-d-Y h:i:s ms');
let data:MessageLogIn;
@ -82,53 +80,47 @@ export class UserService {
console.log('AuthService.login ... Wrong method ...');
}
const httpOption = { 'Content-Type': 'application/json' };
console.log(`call users/connect data=${ JSON.stringify(data, null, 2)}`);
return new Promise((resolve, reject) => {
this.httpOAuth.post('users/get_token', httpOption, data)
.then((response: any) => {
console.log(`response status=${ response.status}`);
if(response.status >= 200 && response.status <= 299) {
console.log(`Data token: id=${ response.data.id}`);
console.log(`Data token: userId=${ response.data.userId}`);
console.log(`Data token: token=${ response.data.token}`);
console.log(`Data token: createTime=${ response.data.createTime}`);
console.log(`Data token: endValidityTime=${ response.data.endValidityTime}`);
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(typeof response.data === 'undefined') {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
this.http.requestJson({
server: 'karauth',
endPoint: 'users/get_token',
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
body: data,
disableTocken: true,
}).then((response: ModelResponseHttp) =>{
console.log(`Data token: id=${ response.data.id}`);
console.log(`Data token: userId=${ response.data.userId}`);
console.log(`Data token: token=${ response.data.token}`);
console.log(`Data token: createTime=${ response.data.createTime}`);
console.log(`Data token: endValidityTime=${ response.data.endValidityTime}`);
resolve(response.data);
}).catch((error:any) => {
reject(`return ERROR ${ JSON.stringify(error, null, 2)}`);
});
});
});
}
loginWithToken(userId : string, token : string) {
console.log(`AuthService.loginWithToken ... '${ userId }':'${ token }'`);
let headers = {
authorization: `Yota ${userId}:${token}`
};
return new Promise((resolve, reject) => {
this.http.get('users/me', headers, {})
.then((response: any) => {
if(response.status === 200) {
resolve(response.data);
return;
}
reject('An error occured');
}, (response: any) => {
if(response.data === undefined) {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
this.http.requestJson({
//server: 'karauth',
endPoint: 'users/me',
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
authorization: `Yota ${userId}:${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)}`)
resolve(response.data);
}).catch((error:any) => {
reject(`return ERROR ${ JSON.stringify(error, null, 2)}`);
});
});
});
/*
console.log("AuthService.login ... '" + _login + "':'" + _password + "'");
@ -179,7 +171,6 @@ export class UserService {
email: email,
password: password
};
const httpOption = { 'Content-Type': 'application/json' };
console.log(`call users data=${ JSON.stringify(data, null, 2)}`);
if(this.identificationVersion === 1) {
@ -187,20 +178,21 @@ export class UserService {
}
return new Promise((resolve, reject) => {
this.httpOAuth.post('users', httpOption, data)
.then((response: any) => {
if(response.status === 200) {
resolve(response.data);
}
reject('An error occured');
}, (response: any) => {
if(response.data === undefined) {
reject('return ERROR undefined');
} else {
reject(`return ERROR ${ JSON.stringify(response.data, null, 2)}`);
}
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 {
@ -224,14 +216,22 @@ export class UserService {
login: login
};
return new Promise((resolve, reject) => {
this.httpOAuth.get('users/check_login', {}, params).then(
(res: Response) => {
resolve('valid');
},
(error) => {
reject(error.status);
this.http.requestJson({
server: 'karauth',
endPoint: 'users/check_login',
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
params,
}).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)}`);
});
});
});
}
checkEMail(email: string) {
@ -239,14 +239,21 @@ export class UserService {
email: email
};
return new Promise((resolve, reject) => {
this.httpOAuth.get('users/check_email', {}, params).then(
(res: Response) => {
resolve('valid');
},
(error) => {
reject(error.status);
this.http.requestJson({
server: 'karauth',
endPoint: 'users/check_email',
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
params,
}).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)}`);
});
});
});
}
}