[DEV] migration and right in progress

This commit is contained in:
Edouard DUPIN 2023-05-08 23:31:50 +02:00
parent 41775a9e86
commit 8a700864d6
16 changed files with 223 additions and 127 deletions

View File

@ -39,7 +39,9 @@ public class WebLauncher {
final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class); final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class);
protected ResourceConfig rc = null; protected ResourceConfig rc = null;
HttpServer server = null; HttpServer server = null;
public WebLauncher() {} public WebLauncher() {
ConfigBaseVariable.bdDatabase = "karso";
}
private static URI getBaseURI() { private static URI getBaseURI() {
return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build(); return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build();
} }
@ -52,15 +54,13 @@ public class WebLauncher {
WebLauncher.LOGGER.info("STOP the REST server:"); WebLauncher.LOGGER.info("STOP the REST server:");
} }
public void generateDB() throws Exception { public void migrateDB() throws Exception {
MigrationEngine migrationEngine = new MigrationEngine(); MigrationEngine migrationEngine = new MigrationEngine();
migrationEngine.setInit(new Initialization()); migrationEngine.setInit(new Initialization());
migrationEngine.migrate(DBEntry.createInterface(GlobalConfiguration.dbConfig)); migrationEngine.migrate(GlobalConfiguration.dbConfig);
} }
public void process() throws InterruptedException { public void process() throws InterruptedException {
ConfigBaseVariable.bdDatabase = "karso";
try { try {
JWTWrapper.initLocalToken(ConfigVariable.getUUIDKeyRoot()); JWTWrapper.initLocalToken(ConfigVariable.getUUIDKeyRoot());
} catch (Exception e1) { } catch (Exception e1) {
@ -71,33 +71,29 @@ public class WebLauncher {
return; return;
} }
// =================================================================== // ===================================================================
// Configure resources // Configure resources
// =================================================================== // ===================================================================
rc = new ResourceConfig(); rc = new ResourceConfig();
// global authentication system // global authentication system
rc.register(new OptionFilter()); rc.register(OptionFilter.class);
// remove cors ==> all time called by an other system... rc.register(CORSFilter.class);
rc.register(new CORSFilter()); rc.register(KarsoAuthenticationFilter.class);
rc.registerClasses(KarsoAuthenticationFilter.class);
// register exception catcher // register exception catcher
rc.register(InputExceptionCatcher.class); rc.register(InputExceptionCatcher.class);
rc.register(SystemExceptionCatcher.class); rc.register(SystemExceptionCatcher.class);
rc.register(FailExceptionCatcher.class); rc.register(FailExceptionCatcher.class);
rc.register(FailException404API.class); rc.register(FailException404API.class);
rc.register(ExceptionCatcher.class); rc.register(ExceptionCatcher.class);
// add default resource: // add default resource:
rc.registerClasses(UserResource.class); rc.register(UserResource.class);
rc.registerClasses(PublicKeyResource.class); rc.register(PublicKeyResource.class);
rc.registerClasses(ApplicationResource.class); rc.register(ApplicationResource.class);
rc.registerClasses(ApplicationTokenResource.class); rc.register(ApplicationTokenResource.class);
rc.registerClasses(SystemConfigResource.class); rc.register(SystemConfigResource.class);
rc.registerClasses(RightResource.class); rc.register(RightResource.class);
rc.registerClasses(Front.class); rc.register(Front.class);
rc.registerClasses(HealthCheck.class); rc.register(HealthCheck.class);
// add jackson to be discover when we are ins stand-alone server // add jackson to be discover when we are ins stand-alone server
rc.register(JacksonFeature.class); rc.register(JacksonFeature.class);
// enable this to show low level request // enable this to show low level request
@ -117,7 +113,7 @@ public class WebLauncher {
// =================================================================== // ===================================================================
try { try {
server.start(); server.start();
LOGGER.debug("Jersey app started at {}", getBaseURI()); LOGGER.info("Jersey app started at {}", getBaseURI());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("There was an error while starting Grizzly HTTP server."); LOGGER.error("There was an error while starting Grizzly HTTP server.");
e.printStackTrace(); e.printStackTrace();

View File

@ -1,11 +1,6 @@
package org.kar.karso; package org.kar.karso;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.karso.util.ConfigVariable; import org.kar.karso.util.ConfigVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -29,11 +24,21 @@ 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,nmQLSDK,NFMQLKSdjmlKQJSDMLQK,S;ndmLQKZNERMAL"; ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf,nmQLSDKNFMQLKSdjmlKQJSDMLQKSndmLQKZNERMAL";
//ConfigBaseVariable.dbType = "sqlite"; //ConfigBaseVariable.dbType = "sqlite";
//ConfigBaseVariable.dbHost = "./bdd_base.sqlite"; //ConfigBaseVariable.dbHost = "./bdd_base.sqlite";
} }
try {
super.migrateDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
while (true) {
logger.error("Migration fail ==> waiting intervention of administrator...");
Thread.sleep(60*60*1000);
}
}
super.process(); super.process();
} }
} }

View File

@ -188,6 +188,27 @@ public class ApplicationResource {
return out; return out;
} }
public record AddUserData(long userId) {};
// TODO : review the function to correct admin only access...
@POST
@Path("{id}/users")
@RolesAllowed(value= {"ADMIN"})
public boolean addUser(@PathParam("id") Long applicationId, AddUserData data) throws Exception {
logger.debug("getApplications");
SqlWrapper.addLink(UserAuth.class, data.userId, "application", applicationId);
return true;
}
// TODO : review the function to correct admin only access...
@DELETE
@Path("{id}/users")
@RolesAllowed(value= {"ADMIN"})
public boolean rmUser(@PathParam("id") Long applicationId, AddUserData data) throws Exception {
logger.debug("getApplications");
SqlWrapper.removeLink(UserAuth.class, data.userId, "application", applicationId);
return true;
}
@GET @GET
@Path("get_token") @Path("get_token")
@RolesAllowed(value= {"USER", "ADMIN"}) @RolesAllowed(value= {"USER", "ADMIN"})
@ -224,31 +245,6 @@ public class ApplicationResource {
logger.error(" result: {}", result); logger.error(" result: {}", result);
return Response.status(401).entity(result).build(); return Response.status(401).entity(result).build();
} }
if (false) {
// the application id is not streamed in the application liny in the where elements
// get the local user:
UserAuth localUser = null;
try {
localUser = SqlWrapper.get(UserAuth.class, gc.userByToken.id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
String result = "SERVER Internal error";
logger.error(" result: {}", result);
return Response.status(500).entity(result).build();
}
if (localUser == null) {
String result = "Authenticate-wrong results '" + applicationName + "')";
logger.error(" result: {}", result);
return Response.status(401).entity(result).build();
}
logger.debug("Get application list: " + localUser.applications);
if (localUser.applications == null || localUser.applications.indexOf((Long)gc.userByToken.id) == -1) {
String result = "Authenticate impossible ==> application not accessible '" + applicationName + "'";
logger.error(" result: {}", result);
return Response.status(401).entity(result).build();
}
} else {
UserLinkApplication links = null; UserLinkApplication links = null;
try { try {
links = SqlWrapper.getWhere(UserLinkApplication.class, links = SqlWrapper.getWhere(UserLinkApplication.class,
@ -269,7 +265,6 @@ public class ApplicationResource {
logger.error(" result: {}", result); logger.error(" result: {}", result);
return Response.status(401).entity(result).build(); return Response.status(401).entity(result).build();
} }
}
// Get the USER Right // Get the USER Right
Map<String, Object> applicationRight = RightResource.getUserRight(gc.userByToken.id, appl.id); Map<String, Object> applicationRight = RightResource.getUserRight(gc.userByToken.id, appl.id);
if (!applicationRight.containsKey("USER")) { if (!applicationRight.containsKey("USER")) {

View File

@ -50,6 +50,7 @@ public class ApplicationTokenResource {
} }
return values; return values;
} }
@DELETE @DELETE
@Path("{applicationId}/{tokenId}") @Path("{applicationId}/{tokenId}")
@RolesAllowed(value= {"ADMIN"}) @RolesAllowed(value= {"ADMIN"})

View File

@ -9,6 +9,7 @@ import org.kar.archidata.exception.FailException;
import org.kar.archidata.exception.InputException; import org.kar.archidata.exception.InputException;
import org.kar.archidata.exception.SystemException; import org.kar.archidata.exception.SystemException;
import org.kar.archidata.filter.GenericContext; import org.kar.archidata.filter.GenericContext;
import org.kar.karso.migration.Initialization;
import org.kar.karso.model.*; import org.kar.karso.model.*;
import org.kar.karso.util.ConfigVariable; import org.kar.karso.util.ConfigVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -290,8 +291,8 @@ public class UserResource {
// this authentication is valid only for Karso ==> not for the application // this authentication is valid only for Karso ==> not for the application
int expirationTimeInMinutes = ConfigVariable.getAuthExpirationTime(); int expirationTimeInMinutes = ConfigVariable.getAuthExpirationTime();
// Get the USER Right (Note: by construction KARSO have application ID = 0 // Get the USER Right (Note: by construction KARSO have application ID = KARSO_INITIALISATION_ID
Map<String, Object> ssoRight = RightResource.getUserRight(user.id, 0); Map<String, Object> ssoRight = RightResource.getUserRight(user.id, Initialization.KARSO_INITIALISATION_ID);
if (!ssoRight.containsKey("USER")) { if (!ssoRight.containsKey("USER")) {
// If the USER is not override, the system add by default USER // If the USER is not override, the system add by default USER
ssoRight.put("USER", true); ssoRight.put("USER", true);

View File

@ -1,6 +1,5 @@
package org.kar.karso.migration; package org.kar.karso.migration;
import org.kar.archidata.migration.MigrationModel;
import org.kar.archidata.migration.MigrationSqlStep; import org.kar.archidata.migration.MigrationSqlStep;
import org.kar.karso.model.Application; import org.kar.karso.model.Application;
import org.kar.karso.model.ApplicationToken; import org.kar.karso.model.ApplicationToken;
@ -11,29 +10,29 @@ import org.kar.karso.model.UserAuth;
public class Initialization extends MigrationSqlStep { public class Initialization extends MigrationSqlStep {
public static final int KARSO_INITIALISATION_ID = 1;
@Override @Override
public String getName() { public String getName() {
return Initialization.class.getCanonicalName(); return "Initialization";
} }
public Initialization() throws Exception { public Initialization() throws Exception {
addClass(Settings.class); addClass(Settings.class);
addClass(UserAuth.class); addClass(UserAuth.class);
addClass(Application.class); addClass(Application.class);
addClass(ApplicationToken.class); addClass(ApplicationToken.class);
addClass(RightDescription.class); addClass(RightDescription.class);
addClass(Right.class); addClass(Right.class);
addClass(MigrationModel.class);
// default admin: "karadmin" password: "adminA@666"
addAction(""" addAction("""
INSERT INTO `application` (`id`, `name`, `description`, `redirect`, `redirectDev`, `notification`, `ttl`) VALUES INSERT INTO `application` (`id`, `name`, `description`, `redirect`, `redirectDev`, `notification`, `ttl`) VALUES
('0', 'karso', 'Root SSO interface', 'http://atria-soft/karso', '', '', '666'); (1, 'karso', 'Root SSO interface', 'http://atria-soft/karso', '', '', 666);
"""); """);
// default admin: "karadmin" password: "adminA@666"
addAction(""" addAction("""
INSERT INTO `user` (`id`, `login`, `password`, `email`, `admin`) VALUES INSERT INTO `user` (`id`, `login`, `password`, `email`, `admin`) VALUES
('0', 'karadmin', '0ddcac5ede3f1300a1ce5948ab15112f2810130531d578ab8bc4dc131652d7cf7a3ff6e827eb957bff43bc2c65a6a1d46722e5b3a2343ac3176a33ea7250080b', (1, 'karadmin', '0ddcac5ede3f1300a1ce5948ab15112f2810130531d578ab8bc4dc131652d7cf7a3ff6e827eb957bff43bc2c65a6a1d46722e5b3a2343ac3176a33ea7250080b',
'admin@admin.ZZZ', 1); 'admin@admin.ZZZ', 1);
"""); """);
addAction(""" addAction("""
@ -45,11 +44,27 @@ public class Initialization extends MigrationSqlStep {
"""); """);
addAction(""" addAction("""
INSERT INTO `rightDescription` (`id`, `applicationId`, `key`, `title`, `description`, `type`) VALUES INSERT INTO `rightDescription` (`id`, `applicationId`, `key`, `title`, `description`, `type`) VALUES
(0, 0, 'ADMIN', 'Administrator', 'Full administrator Right', 'BOOLEAN'); (1, 1, 'ADMIN', 'Administrator', 'Full administrator Right', 'BOOLEAN');
"""); """);
addAction(""" addAction("""
INSERT INTO `right` (`applicationId`, `userId`, `rightDescriptionId`, `value`) VALUES INSERT INTO `right` (`applicationId`, `userId`, `rightDescriptionId`, `value`) VALUES
(0, 0, 0, 'true'); (1, 1, 1, 'true');
""");
// we generate an offset to permit to manage some generic upgrade in the future...
addAction("""
ALTER TABLE application AUTO_INCREMENT = 1000;
""");
addAction("""
ALTER TABLE user AUTO_INCREMENT = 1000;
""");
addAction("""
ALTER TABLE settings AUTO_INCREMENT = 1000;
""");
addAction("""
ALTER TABLE right AUTO_INCREMENT = 1000;
""");
addAction("""
ALTER TABLE rightDescription AUTO_INCREMENT = 1000;
"""); """);
} }

View File

@ -30,8 +30,6 @@ public class UserAuth extends User {
@SQLLimitSize(512) @SQLLimitSize(512)
@SQLNotNull @SQLNotNull
public String email; public String email;
@SQLNotNull
@SQLDefault("'0'")
public Timestamp emailValidate; // time of validation public Timestamp emailValidate; // time of validation
@SQLLimitSize(512) @SQLLimitSize(512)
public String newEmail; public String newEmail;

View File

@ -1,7 +1,4 @@
package test.kar.karso; package test.kar.karso;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map; import java.util.Map;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -16,9 +13,7 @@ import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.SqlWrapper; import org.kar.archidata.SqlWrapper;
import org.kar.archidata.db.DBEntry;
import org.kar.archidata.exception.RESTErrorResponseExeption; import org.kar.archidata.exception.RESTErrorResponseExeption;
import org.kar.archidata.model.GetToken; import org.kar.archidata.model.GetToken;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.util.ConfigBaseVariable;
@ -54,16 +49,18 @@ public class TestBase {
} }
@BeforeAll @BeforeAll
public static void configureWebServer() throws InterruptedException { public static void configureWebServer() throws Exception {
logger.info("configure server ..."); logger.info("configure server ...");
webInterface = new WebLauncherTest(); webInterface = new WebLauncherTest();
logger.info("Create DB"); logger.info("Create DB");
String dbName = "qsqsdqsdqsdqsd"; String dbName = "sdfsdfsdfsfsdfsfsfsfsdfsdfsd";
boolean data = SqlWrapper.isDBExist(dbName); boolean data = SqlWrapper.isDBExist(dbName);
logger.error(" - {}", data); logger.error("exist: {}", data);
data = SqlWrapper.createDB(dbName); data = SqlWrapper.createDB(dbName);
logger.error(" - {}", data); logger.error("create: {}", data);
data = SqlWrapper.isDBExist(dbName);
logger.error("exist: {}", data);
System.exit(-1); System.exit(-1);
logger.info("Start REST (BEGIN)"); logger.info("Start REST (BEGIN)");

View File

@ -24,11 +24,8 @@ public class WebLauncherTest extends WebLauncher {
////ConfigBaseVariable.dbKeepConnected = "true"; ////ConfigBaseVariable.dbKeepConnected = "true";
ConfigBaseVariable.dbHost = "192.168.14.100"; ConfigBaseVariable.dbHost = "localhost";
ConfigBaseVariable.dbPort = "20006";
ConfigBaseVariable.dbUser = "root"; ConfigBaseVariable.dbUser = "root";
ConfigBaseVariable.dbPassword = "password"; ConfigBaseVariable.dbPassword = "ZERTYSDGFVHSDFGHJYZSDFGSQxfgsqdfgsqdrf4564654";
ConfigBaseVariable.bdDatabase = "";
} }
} }

View File

@ -10,7 +10,7 @@ services:
ports: ports:
- 3306:3306 - 3306:3306
volumes: volumes:
- /workspace/data/global/db:/var/lib/mysql - ./db:/var/lib/mysql
mem_limit: 400m mem_limit: 400m
healthcheck: healthcheck:
test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]
@ -24,7 +24,7 @@ services:
- karauth_db_service - karauth_db_service
# # condition: service_healthy # # condition: service_healthy
ports: ports:
- 17079:8080 - 10079:8080
links: links:
- karauth_db_service:db - karauth_db_service:db
#read_only: true #read_only: true

View File

@ -47,9 +47,9 @@
<td>{{user.id}}</td> <td>{{user.id}}</td>
<td>{{user.login}}</td> <td>{{user.login}}</td>
<td> <td>
<button class="circular-button color-button-validate color-shadow-black" <button class="square-button color-button-validate color-shadow-black"
(click)="onAddApplicationUser($event, user)" type="submit"> (click)="onAddApplicationUser($event, user)" type="submit">
+ <i class="material-icons">add</i>
</button> </button>
</td> </td>
</tr> </tr>

View File

@ -96,13 +96,45 @@ export class ApplicationUserEditScene implements OnInit {
*/ */
} }
onRemoveApplicationUser(value: boolean, user: any) {
console.log(`changeState : ${JSON.stringify(value, null, 2)}`);
const self = this;
this.applicationService.rmUser(this.id, user.id)
.then((response: boolean) => {
if (response === true) {
self.notUsers.push(user);
const index = self.users.indexOf(user, 0);
if (index > -1) {
self.users.splice(index, 1);
}
} else {
// TODO: manage error
}
})
.catch((error: any) => {
console.log(`return ERROR ${JSON.stringify(error, null, 2)}`);
});
//this.cdr.detectChanges();
}
onAddApplicationUser(value: boolean, user: any) { onAddApplicationUser(value: boolean, user: any) {
console.log(`changeState : ${JSON.stringify(value, null, 2)}`); console.log(`changeState : ${JSON.stringify(value, null, 2)}`);
const self = this;
j'en suis la ... add user une application this.applicationService.addUser(this.id, user.id)
//this.createTokenDisabled = value; .then((response: boolean) => {
// we do not change the main ref ==> notify angular that something have change and need to be re-render??? if (response === true) {
this.cdr.detectChanges(); self.users.push(user);
const index = self.notUsers.indexOf(user, 0);
if (index > -1) {
self.notUsers.splice(index, 1);
}
} else {
// TODO: manage error
}
})
.catch((error: any) => {
console.log(`return ERROR ${JSON.stringify(error, null, 2)}`);
});
//this.cdr.detectChanges();
} }
formatTimestamp(unix_timestamp: number) { formatTimestamp(unix_timestamp: number) {

View File

@ -28,6 +28,10 @@
(click)="onEditApplication($event, application)" type="submit"> (click)="onEditApplication($event, application)" type="submit">
<i class="material-icons">edit</i> <i class="material-icons">edit</i>
</button>&nbsp; </button>&nbsp;
<button class="square-button login color-shadow-black"
(click)="onEditRightApplication($event, application)" type="submit">
<i class="material-icons">admin_panel_settings</i>
</button>&nbsp;
<button *ngIf="application.id !== 0" <button *ngIf="application.id !== 0"
class="square-button login color-button-cancel color-shadow-black" class="square-button login color-button-cancel color-shadow-black"
(click)="onRemoveApplication($event, application)" type="submit"> (click)="onRemoveApplication($event, application)" type="submit">

View File

@ -30,7 +30,7 @@ export class ApplicationsScene implements OnInit {
) { ) {
} }
ngOnInit() { ngOnInit() {
let self = this; const self = this;
this.configureInput(); this.configureInput();
this.applicationService this.applicationService
.gets() .gets()
@ -50,7 +50,7 @@ export class ApplicationsScene implements OnInit {
} }
removeApplicationConfirm(application: ApplicationModel) { removeApplicationConfirm(application: ApplicationModel) {
let self = this; const self = this;
this.applicationService.remove(application.id) this.applicationService.remove(application.id)
.then( .then(
() => { () => {
@ -78,7 +78,10 @@ export class ApplicationsScene implements OnInit {
} }
onEditApplication(_event: any, application: ApplicationModel) { onEditApplication(_event: any, application: ApplicationModel) {
this.router.navigate(["application-edit", application.id]); this.router.navigate(['application-edit', application.id]);
}
onEditRightApplication(_event: any, application: ApplicationModel) {
this.router.navigate(['application-user-edit', application.id]);
} }
@ -99,7 +102,7 @@ export class ApplicationsScene implements OnInit {
{ {
type: SettingType.STRING, type: SettingType.STRING,
title: 'Redirect:', title: 'Redirect:',
placeholder: 'Enter http redirect adresses', placeholder: 'Enter http redirect addresses',
key: 'redirect', key: 'redirect',
value: '', value: '',
checker: (value) => { return this.checkRedirect(value) }, checker: (value) => { return this.checkRedirect(value) },
@ -116,16 +119,16 @@ export class ApplicationsScene implements OnInit {
*/ */
checkName(value: CheckerParameterType): string | undefined { checkName(value: CheckerParameterType): string | undefined {
if (!isString(value)) { if (!isString(value)) {
return "must be a string"; return 'must be a string';
} }
console.log(`input value : ${value}`) console.log(`input value : ${value}`);
if (value.length < 6) { if (value.length < 6) {
return "This name is too small >=6."; return 'This name is too small >=6.';
} }
for (let iii = 0; iii < this.applications.length; iii++) { for (let iii = 0; iii < this.applications.length; iii++) {
let application = this.applications[iii]; const application = this.applications[iii];
if (application.name === value) { if (application.name === value) {
return "This name already exist."; return 'This name already exist.';
} }
} }
return undefined; return undefined;
@ -136,10 +139,10 @@ export class ApplicationsScene implements OnInit {
*/ */
checkRedirect(value: CheckerParameterType): string | undefined { checkRedirect(value: CheckerParameterType): string | undefined {
if (!isString(value)) { if (!isString(value)) {
return "must be a string"; return 'must be a string';
} }
if (value.length <= 5) { if (value.length <= 5) {
return "This redirect is too small."; return 'This redirect is too small.';
} }
return undefined; return undefined;
} }
@ -151,8 +154,8 @@ export class ApplicationsScene implements OnInit {
onCreateApplication(): void { onCreateApplication(): void {
console.log(`create user:`); console.log(`create user:`);
this.createState = AsyncActionState.LOADING; this.createState = AsyncActionState.LOADING;
let self = this; const self = this;
this.applicationService.create(this.dataCreateApplication["name"], this.dataCreateApplication["redirect"]) this.applicationService.create(this.dataCreateApplication['name'], this.dataCreateApplication['redirect'])
.then( .then(
(data: ApplicationModel) => { (data: ApplicationModel) => {
self.createState = AsyncActionState.DONE; self.createState = AsyncActionState.DONE;

View File

@ -28,7 +28,7 @@ export class ApplicationTokenService {
} }
gets(applicationId: number): Promise<ApplicationTokenModel[]> { gets(applicationId: number): Promise<ApplicationTokenModel[]> {
let self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http
.requestJson({ .requestJson({

View File

@ -52,7 +52,7 @@ export class ApplicationService {
} }
getApplicationSpecificToken(applicationId: string): Promise<SpecificTokenResponse> { getApplicationSpecificToken(applicationId: string): Promise<SpecificTokenResponse> {
let self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http
.requestJson({ .requestJson({
@ -68,7 +68,7 @@ export class ApplicationService {
.then((response: ModelResponseHttp) => { .then((response: ModelResponseHttp) => {
// TODO: check type ... // TODO: check type ...
console.log( console.log(
`retreive Token for application : get some data to check: ${JSON.stringify(response.data)}` `retrieve Token for application : get some data to check: ${JSON.stringify(response.data)}`
); );
// tODO: check the format... // tODO: check the format...
resolve(response.data); resolve(response.data);
@ -79,8 +79,60 @@ export class ApplicationService {
}); });
} }
addUser(applicationId: number, userId: number): Promise<boolean> {
const self = this;
return new Promise((resolve, reject) => {
this.http
.requestJson({
server: 'karso',
endPoint: `application/${applicationId}/users`,
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
body: {
userId,
},
})
.then((response: ModelResponseHttp) => {
console.log(
`User has been added: ${JSON.stringify(response.data)}`
);
resolve(response.data);
})
.catch((error: any) => {
reject(`return ERROR ${JSON.stringify(error, null, 2)}`);
});
});
}
rmUser(applicationId: number, userId: number): Promise<boolean> {
const self = this;
return new Promise((resolve, reject) => {
this.http
.requestJson({
server: 'karso',
endPoint: `application/${applicationId}/users`,
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON,
body: {
userId,
},
})
.then((response: ModelResponseHttp) => {
console.log(
`User has been added: ${JSON.stringify(response.data)}`
);
resolve(response.data);
})
.catch((error: any) => {
reject(`return ERROR ${JSON.stringify(error, null, 2)}`);
});
});
}
getApplicationReturn(applicationId: string): Promise<SpecificReturnResponse> { getApplicationReturn(applicationId: string): Promise<SpecificReturnResponse> {
let self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http
.requestJson({ .requestJson({
@ -107,7 +159,7 @@ export class ApplicationService {
}); });
} }
getApplicationsSmall(): Promise<GetApplicationSmallResponse[]> { getApplicationsSmall(): Promise<GetApplicationSmallResponse[]> {
let self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http this.http
.requestJson({ .requestJson({