Base of right ready (no add only on bdd)

This commit is contained in:
Edouard DUPIN 2023-05-25 23:17:50 +02:00
parent 9ec2f4f336
commit 7c75c737d7
8 changed files with 119 additions and 89 deletions

View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.kar</groupId> <groupId>org.kar</groupId>
<artifactId>karso</artifactId> <artifactId>karso</artifactId>
<version>0.4.1</version> <version>0.4.2</version>
<properties> <properties>
<!-- <!--
<jaxb.version>2.3.1</jaxb.version> <jaxb.version>2.3.1</jaxb.version>
@ -24,7 +24,7 @@
<dependency> <dependency>
<groupId>kangaroo-and-rabbit</groupId> <groupId>kangaroo-and-rabbit</groupId>
<artifactId>archidata</artifactId> <artifactId>archidata</artifactId>
<version>0.3.5</version> <version>0.3.6</version>
</dependency> </dependency>
<!-- testing --> <!-- testing -->
<dependency> <dependency>

View File

@ -24,7 +24,7 @@ public class WebLauncherLocal extends WebLauncher {
ConfigBaseVariable.apiAdress = "http://0.0.0.0:15080/karso/api/"; ConfigBaseVariable.apiAdress = "http://0.0.0.0:15080/karso/api/";
ConfigBaseVariable.dbPort = "3306"; ConfigBaseVariable.dbPort = "3306";
// create a unique key for test ==> not retrieve the token every load... // create a unique key for test ==> not retrieve the token every load...
ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf,nmQLSDKNFMQLKSdjmlKQJSDMLQKSndmLQKZNERMAL"; ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf88QJSDMLQKSndmLQKZNERMAL";
//ConfigBaseVariable.dbType = "sqlite"; //ConfigBaseVariable.dbType = "sqlite";
//ConfigBaseVariable.dbHost = "./bdd_base.sqlite"; //ConfigBaseVariable.dbHost = "./bdd_base.sqlite";

View File

@ -4,8 +4,13 @@ import org.kar.archidata.SqlWrapper;
import org.kar.archidata.WhereCondition; import org.kar.archidata.WhereCondition;
import org.kar.karso.model.Right; import org.kar.karso.model.Right;
import org.kar.karso.model.RightDescription; import org.kar.karso.model.RightDescription;
import org.kar.karso.util.Transform;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.kar.archidata.annotation.SQLComment;
import org.kar.archidata.annotation.SQLForeignKey;
import org.kar.archidata.annotation.SQLLimitSize;
import org.kar.archidata.annotation.SQLNotNull;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.annotation.security.RolesAllowed;
import jakarta.ws.rs.*; import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
@ -20,49 +25,46 @@ import java.util.Map;
public class RightResource { public class RightResource {
final static Logger logger = LoggerFactory.getLogger(RightResource.class); final static Logger logger = LoggerFactory.getLogger(RightResource.class);
public static List<RightDescription> getApplicationRightDecription(long applicationId) throws Exception {
public static Object transform(String type, String value) { return SqlWrapper.getsWhere(RightDescription.class,
if ("BOOLEAN".equals(type)) { List.of(
return Boolean.valueOf(value); new WhereCondition("applicationId", "=", applicationId),
} else if ("STRING".equals(type)) { new WhereCondition("deleted", "=", 0)
return value; ));
} else if ("LONG".equals(type)) {
return Long.valueOf(value);
} else if ("NUMBER".equals(type)) {
return Double.valueOf(value);
} else {
return null;
}
} }
public static Map<String, Object> getUserRight(long userId, long applicationId) throws Exception { public static List<Right> getRawUserRight(long userId, long applicationId) throws Exception {
Map<String, Object> out = new HashMap<>(); return SqlWrapper.getsWhere(Right.class,
List<RightDescription> rightsDescriptions = SqlWrapper.getsWhere(RightDescription.class,
List.of(
new WhereCondition("applicationId", "=", applicationId),
new WhereCondition("deleted", "=", 0)
));
logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
if (rightsDescriptions != null && rightsDescriptions.size() != 0) {
List<Right> rights = SqlWrapper.getsWhere(Right.class,
List.of( List.of(
new WhereCondition("applicationId", "=", applicationId), new WhereCondition("applicationId", "=", applicationId),
new WhereCondition("userId", "=", userId), new WhereCondition("userId", "=", userId),
new WhereCondition("deleted", "=", 0) new WhereCondition("deleted", "=", 0)
)); ));
}
public static Map<String, Object> getUserRight(long userId, long applicationId) throws Exception {
Map<String, Object> out = new HashMap<>();
List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
if (rightsDescriptions != null && rightsDescriptions.size() != 0) {
List<Right> rights = getRawUserRight(userId, applicationId);
logger.debug("Get some user right: {}userID={}", rights.size(), userId); logger.debug("Get some user right: {}userID={}", rights.size(), userId);
if (rights != null && rights.size() != 0) { for (RightDescription description : rightsDescriptions) {
for (Right right: rights) { if (description == null) {
RightDescription description = rightsDescriptions.stream() // TODO: this is a really strange case to manage later...
.filter(elem -> right.rightDescriptionId == elem.id) continue;
.findAny() }
.orElse(null); Right right = rights.stream()
if (description != null) { .filter(elem -> elem.rightDescriptionId == description.id)
out.put(description.key, transform(description.type, right.value)); .findAny()
} .orElse(null);
if (right != null) {
out.put(description.key, Transform.convertToType(description.type, right.value));
} else if (description.defaultValue != null){
out.put(description.key, Transform.convertToType(description.type, description.defaultValue));
} else {
out.put(description.key, null);
} }
} else {
logger.debug("The User have no specific right...");
} }
} else { } else {
// the application does not manage right with Karso (normal use-case) // the application does not manage right with Karso (normal use-case)
@ -70,6 +72,49 @@ public class RightResource {
} }
return out; return out;
} }
public static void updateUserRight(long userId, long applicationId, Map<String, Object> delta) throws Exception {
List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
if (rightsDescriptions == null || rightsDescriptions.size() == 0) {
throw new IllegalArgumentException("Request change right on an application that does not manage any right");
}
List<Right> rights = getRawUserRight(userId, applicationId);
logger.debug("Get some user right: {}userID={}", rights.size(), userId);
for (RightDescription description : rightsDescriptions) {
if (description == null) {
// TODO: this is a really strange case to manage later...
continue;
}
Object newValue = delta.get(description.key);
if (newValue == null) {
//No need to update or create...
continue;
}
String convertedValue = Transform.convertToStringCheck(description.type, newValue);
if (convertedValue == null) {
throw new IllegalArgumentException("Uncompatible value:'" + description.type + "'");
}
Right right = rights.stream()
.filter(elem -> elem.rightDescriptionId == description.id)
.findAny()
.orElse(null);
if (right != null) {
// The value exist, we need to update it
logger.debug("Request update a knonwn parameter: {} with {}", description.key, newValue);
right.value = convertedValue;
SqlWrapper.update(right, right.id, List.of("value"));
} else {
// we need to create it
logger.debug("Request create parameter: {} with {}", description.key, newValue);
right = new Right();
right.applicationId = applicationId;
right.userId = userId;
right.rightDescriptionId = description.id;
right.value = convertedValue;
SqlWrapper.insert(right);
}
}
}
@GET @GET

View File

@ -86,28 +86,21 @@ public class UserResource {
@GET @GET
@Path("{userId}/application/{applicationId}/rights") @Path("{userId}/application/{applicationId}/rights")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<Right> getApplicationRight(@Context SecurityContext sc, public Map<String, Object> getApplicationRight(@Context SecurityContext sc,
@PathParam("userId") long userId, @PathParam("userId") long userId,
@PathParam("applicationId") long applicationId) throws Exception { @PathParam("applicationId") long applicationId) throws Exception {
return SqlWrapper.getsWhere(Right.class, List.of( return RightResource.getUserRight(userId, applicationId);
new WhereCondition("applicationId", "=", applicationId),
new WhereCondition("userId", "=", userId)),
false);
} }
@PUT @PUT
@Path("{userId}/application/{applicationId}/rights") @Path("{userId}/application/{applicationId}/rights")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<Right> patchApplicationRight(@Context SecurityContext sc, public Map<String, Object> patchApplicationRight(@Context SecurityContext sc,
@PathParam("userId") long userId, @PathParam("userId") long userId,
@PathParam("applicationId") long applicationId, Map<String, Object> data) throws Exception { @PathParam("applicationId") long applicationId, Map<String, Object> data) throws Exception {
logger.info("get data from FRONT: {}", data); logger.info("get data from FRONT: {}", data);
/* RightResource.updateUserRight(userId, applicationId, data);
return SqlWrapper.getsWhere(Right.class, List.of( return RightResource.getUserRight(userId, applicationId);
new WhereCondition("applicationId", "=", applicationId),
new WhereCondition("userId", "=", userId)),
false);
*/
return null;
} }
// TODO: check this it might be deprecated ... // TODO: check this it might be deprecated ...

View File

@ -31,6 +31,9 @@ public class RightDescription extends GenericTable {
@SQLLimitSize(1024) @SQLLimitSize(1024)
@SQLComment("Description of the right") @SQLComment("Description of the right")
public String description; public String description;
@SQLLimitSize(1024)
@SQLComment("default value if Never set")
public String defaultValue;
@SQLNotNull @SQLNotNull
@SQLLimitSize(16) @SQLLimitSize(16)
@SQLComment("Type of the property") @SQLComment("Type of the property")

View File

@ -10,7 +10,7 @@ import { AdminUserService, ApplicationModel, ApplicationService, ApplicationUser
import { ApplicationRightModel } from 'base/service/application'; import { ApplicationRightModel } from 'base/service/application';
import { SettingType, SettingsItem } from '../manage-accounts/manage-accounts'; import { SettingType, SettingsItem } from '../manage-accounts/manage-accounts';
import { UserService } from 'common/service'; import { UserService } from 'common/service';
import { isUndefined } from 'common/utils'; import { isNullOrUndefined, isUndefined } from 'common/utils';
import { AsyncActionState } from 'common/component'; import { AsyncActionState } from 'common/component';
@ -29,7 +29,7 @@ export class applicationUserRightEditScene implements OnInit {
rowRight: ApplicationRightModel[] = []; rowRight: ApplicationRightModel[] = [];
applicationName: string; applicationName: string;
userName: string; userName: string;
userRights: ApplicationUserRight[] = []; userRights: ApplicationUserRight = {};
constructor( constructor(
private settingService: SettingsService, private settingService: SettingsService,
@ -81,7 +81,7 @@ export class applicationUserRightEditScene implements OnInit {
this.userAdminService this.userAdminService
.getApplicationRights(this.userId, this.applicationId) .getApplicationRights(this.userId, this.applicationId)
.then((userRights: ApplicationUserRight[]) => { .then((userRights: ApplicationUserRight) => {
console.log(`getApplicationRights OK response: ${JSON.stringify(userRights, null, 4)}`); console.log(`getApplicationRights OK response: ${JSON.stringify(userRights, null, 4)}`);
self.userRights = userRights; self.userRights = userRights;
self.configureEditInput(); self.configureEditInput();
@ -130,24 +130,8 @@ export class applicationUserRightEditScene implements OnInit {
for (let iii = 0; iii < this.rowRight.length; iii++) { for (let iii = 0; iii < this.rowRight.length; iii++) {
const elem = this.rowRight[iii]; const elem = this.rowRight[iii];
let value = undefined; let value = undefined;
for (let jjj = 0; jjj < this.userRights.length; jjj++) { if (!isNullOrUndefined(this.userRights[elem.key])) {
const elemRight = this.userRights[jjj]; value = this.userRights[elem.key];
if (elemRight.rightDescriptionId == elem.id) {
value = elemRight.value;
break;
}
}
// TODO: maybe transfer this in the SERVER API....
if (!isUndefined(value)) {
if (elem.type === "BOOLEAN") {
value = value.toLowerCase() == 'true';
} else if (elem.type === "STRING") {
// nothing to do...
} else if (elem.type === "LONG" || elem.type === "NUMBER") {
value = Number(value);
} else {
console.error(`Can not interpret type of the input value model: ${elem.type}`);
}
} }
tmp.push({ tmp.push({
type: SettingType.BOOLEAN, type: SettingType.BOOLEAN,

View File

@ -32,10 +32,7 @@ interface MessageAnswer_USER_CONNECT {
avatar: string; avatar: string;
} }
*/ */
export interface ApplicationUserRight { export type ApplicationUserRight = Object;
rightDescriptionId: number;
value: string;
}
@Injectable() @Injectable()
export class AdminUserService { export class AdminUserService {
@ -354,8 +351,8 @@ export class AdminUserService {
}); });
}); });
} }
// !!!!! la fonction ci dessous ne retourne pas des élément bijectif avec la fuction courente et c'est un problème...
getApplicationRights(userId: number, applicationId: number): Promise<ApplicationUserRight[]> { getApplicationRights(userId: number, applicationId: number): Promise<ApplicationUserRight> {
const self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http
@ -373,12 +370,12 @@ export class AdminUserService {
resolve(response.data); resolve(response.data);
}) })
.catch((error: any) => { .catch((error: any) => {
reject(`return ERROR ${JSON.stringify(error, null, 2)}`); reject(error);
}); });
}); });
} }
updateApplicationRights(userId: number, applicationId: number, dataUpdate: object): Promise<ApplicationUserRight[]> { updateApplicationRights(userId: number, applicationId: number, dataUpdate: object): Promise<ApplicationUserRight> {
const self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http

View File

@ -69,9 +69,6 @@ export class HttpWrapperService {
} }
request(properties: HTTPRequest): Promise<Response> { 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 connectionAddresses = this.createRESTCall2({ let connectionAddresses = this.createRESTCall2({
server: properties.server, server: properties.server,
api: properties.endPoint, api: properties.endPoint,
@ -87,7 +84,6 @@ export class HttpWrapperService {
if (properties.requestType !== HTTPRequestModel.GET) { if (properties.requestType !== HTTPRequestModel.GET) {
headers['Content-Type'] = properties.contentType; headers['Content-Type'] = properties.contentType;
} }
//console.log(`disble tocken : ${JSON.stringify(properties)} properties.disableTocken=${properties.disableTocken}`);
if ( if (
properties.disableTocken === undefined || properties.disableTocken === undefined ||
properties.disableTocken === null || properties.disableTocken === null ||
@ -119,7 +115,7 @@ export class HttpWrapperService {
response response
.json() .json()
.then((value: any) => { .then((value: any) => {
//console.log(`REICEIVE ==> ${response.status}=${ JSON.stringify(value, null, 2)}`); //console.log(`RECEIVE ==> ${response.status}=${ JSON.stringify(value, null, 2)}`);
resolve({ status: response.status, data: value }); resolve({ status: response.status, data: value });
}) })
.catch((reason: any) => { .catch((reason: any) => {
@ -135,7 +131,13 @@ export class HttpWrapperService {
} }
}) })
.catch((error: any) => { .catch((error: any) => {
reject({ status: error.status, data: error.error }); reject({
time: Date(),
status: 999,
error: error,
statusMessage: "Fetch error",
message: "http-wrapper.ts detect an error in the fetch request"
});
}); });
}); });
} }
@ -164,7 +166,13 @@ export class HttpWrapperService {
} }
}) })
.catch((error: any) => { .catch((error: any) => {
reject({ status: error.status, data: error.error }); reject({
time: Date(),
status: 999,
error: error,
statusMessage: "Fetch image error",
message: "http-wrapper.ts detect an error in the fetch request"
});
}); });
}); });
} }
@ -258,13 +266,13 @@ export class HttpWrapperService {
post(uriRest: string, headerOption: any, data: any, progress: ProgressCallback = null) { post(uriRest: string, headerOption: any, data: any, progress: ProgressCallback = null) {
//console.log(`-------------------------------------------------------\nHTTP-wrapper POST '${ uriRest }'\n\t\theaderOption=${ JSON.stringify(headerOption, null, 2)}\n\t\tdata=${ JSON.stringify(data, null, 2)}`); //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); this.addTokenIfNeeded(headerOption);
let connectionAdresse = this.createRESTCall(uriRest, {}); let connectionAddresses = this.createRESTCall(uriRest, {});
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (this.displayReturn === true) { if (this.displayReturn === true) {
console.log(`call POST ${connectionAdresse} data=${JSON.stringify(data, null, 2)}`); console.log(`call POST ${connectionAddresses} data=${JSON.stringify(data, null, 2)}`);
} }
let request = this.http.post(connectionAdresse, data, { let request = this.http.post(connectionAddresses, data, {
headers: new HttpHeaders(headerOption), headers: new HttpHeaders(headerOption),
reportProgress: true, reportProgress: true,
observe: 'events', observe: 'events',