Socket
Socket
Sign inDemoInstall

syshub-rest-module

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

syshub-rest-module - npm Package Compare versions

Comparing version 2.0.0-rc3 to 2.0.0-rc4

2

package.json
{
"name": "syshub-rest-module",
"version": "2.0.0-rc3",
"version": "2.0.0-rc4",
"description": "This package provides a generic library for the communication from an Angular SPA with a NT-Ware uniFLOW sysHUB backend server based on HTTPS Rest API with OAuth2 flow.",

@@ -5,0 +5,0 @@ "keywords": [

# Syshub Rest Module
This package provides a generic library for the communication from an Angular SPA with a NT-Ware uniFLOW sysHUB backend server based on HTTPS Rest API with OAuth2 flow. The contained Rest Service provides methods for login and logout-functionality and an automatic token refresh. Furthermore you can use the get- and post-methods to send a request to any sysHUB Rest API endpoint.
The package contains anything needed for the communication, just at it as a provider to your application and provide it with settings like hostname and credentials.
The **syshub-rest-module** provides an encapsulated module for communication between an Angular single-page application (SPA) and an NT-Ware uniFLOW sysHUB server. Communication takes place via the OAuth2-based rest interface provided by the sysHUB server, optionally via basic authentication.
The *RestService* included in this module provides generic methods for HTTP GET, POST, DELETE, PATCH and PUT operations as well as type-safe methods like `getCurrentUser()`. After a user logs in via OAuth, the module takes care of renewing the session token shortly before expiry.
Follow the installation instructions below to integrate the module into an Angular app.
## Install

@@ -10,10 +13,9 @@

### Setup configuration
### Configuration
After installing the module, create a configuration for the credentials, for example in your `environment.ts` file. If there is no `environment.ts` yet, see [this article](https://stackoverflow.com/a/74558518) on StackOverflow.
Make sure that the `environment` variable implements the `Env` interface so that type checking prevents errors already during the development of the app.
Make sure that your configuration implements the `Env` interface, so that type checking prevents errors already during the development of the app. For each property within the `Env` type, type hints are implemented, please take note of them. For example, it is not intended to enable OAuth and Basic Auth in parallel (as described in the type hint). If both are activated anyway, an error will be thrown.
```
import { Env } from "syshub-rest-module";
import { SyshubVersion } from 'syshub-rest-module';
```ts
import { Env, SyshubVersion } from 'syshub-rest-module';

@@ -34,2 +36,3 @@ export const environment: Env = {

clientSecret: "<syshubAuthserverClientSecret>",
scope: "private+public"
}

@@ -40,67 +43,156 @@ }

Make sure to enable either basic auth or oauth. Basic auth requires an authentication provider that you must set up in API Server configuration. This is not required for OAuth authentication. For a detailed explanation of the configuration values see chapter [Configuration](#configuration).
#### Env Data Type Specification
The `Env` data type in the `environment.ts` file forms the basic configuration unit for the *RestModule* and is intended to ensure that only valid properties are set. This detailed specification describes all properties and their permitted values and effects. The description is also stored within the module so that it is shown in the code editor.
`Env` is not mandatory. It contains the property `syshub` (`Type RestSettings`, see below), which must be used in the constructor of the `Settings` class. If `environment` is not declared as `Env`, it must be otherwise ensured that `syshub` conforms to the type `RestSettings`.
#### Env property syshub - Data Type RestSettings Specification
Root element for the `Settings` class constructor that is essential for configuring the *RestService*.
- `host`: **Required** (type string URL); URL to the sysHUB Webserver root, for example: `http://localhost:8088/`.
- `version`: Optional, **required for sysHUB 2021 server**; Pick one value from the enum:
- `SyshubVersion.sysHUB_2021`
- `SyshubVersion.sysHUB_2022`
- `SyshubVersion.sysHUB_2023`
- `SyshubVersion.DEFAULT` which is the same as `SyshubVersion.sysHUB_2023`
- `basic`: Optional, **required for basic authentication** (type object)
- `enabled`: Required (type boolean); `true` if basic auth is to be enabled, default `false`.
- `username`: Optional, **required for basic authentication** (type string)
- `password`: Optional, **required for basic authentication** (type string)
- `provider`: Optional, **required for basic authentication** (type string); The name of the API server provider from the sysHUB configuration.
- `oauth`: Optional, **required for OAuth** (type object)
- `enabled`: Required (type boolean); `true` if OAuth is to be enabled, default `false`.
- `clientId`: Optional, **required for OAuth** (type string); The name of the Auth server client.
- `clientSecret`: Optional, **required for OAuth** (type string); The name of the Auth server client secret.
- `scope`: Optional (type string); The scope as defined in the sysHUB Auth server, replace `;` with `+`. Allowed values: `private`, `public`, `private+public`, or `public+private`. Default: `public`.
- `storeKey`: Optional (type string); The name that is used to store the credentials in the local browser cache. Default: `authmod-session`.
- `options`: Optional (type object)
- `autoConnect`, Optional (type boolean), Not yet implemented.
- `autoLogoutOn401`, Optional (type boolean), If the sysHUB Rest API returns HTTP Status 401, this property causes the Rest Service to remove the user's session information from the browser cache. Default: `true`.
- `autoLogoutTimer`, Optional (type boolean), Not yet implemented.
#### A short note on sysHUB 2021 server
The Rest API had a huge change from 2021 to 2022 version of the server. The API is now available in the url path `/webapi/` instead of the old `/cosmos-webapi/`. Therefore this module contains a version switch in the configuration. If the switch is not set, it will always use the latest version, currently 2023. In order to use the module with an old 2021 server change the version accordingly.
The Rest API has changed significantly from version 2021 to version 2022 of the server. The API is now available via `/webapi/` instead of the old `/cosmos-webapi/`, which is why this module contains a version switch in the configuration. If the switch is not set, the latest version, currently 2023, is always used. To use the module with an old 2021 server, change the version accordingly.
### Link module in your app.module.ts
In your `app.module.ts` add the following three providers:
In your `app.module.ts` make sure that the `HttpClientModule` is imported and add the three providers `Settings`, `RestService` and `HTTP_INTERCEPTORS`. The minimal configuration looks something like this:
```
```ts
import { HTTP_INTERCEPTORS, HttpClient, HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { RestService, RestSettings, Settings, SyshubInterceptor } from 'syshub-rest-module';
...
providers: [
@NgModule({
imports: [
HttpClientModule,
],
providers: [
{ provide: Settings, multi: false, useValue: new Settings(<RestSettings>(environment.syshub)) },
{ provide: RestService, multi: false, deps: [Settings, HttpClient] },
{ provide: HTTP_INTERCEPTORS, multi: true, useClass: SyshubInterceptor, deps: [Settings, RestService] }
{ provide: HTTP_INTERCEPTORS, multi: true, useClass: SyshubInterceptor, deps: [Settings, RestService] },
],
})
export class AppModule { }
```
The Settings-provider requires an initialized object of type `Settings`, where the constructor expects an object that implements the `RestSettings` interface. For an example, see above the `environment.syshub` object in the [Install/Setup configuration chapter](#setup-configuration).
The `Settings` provider requires an initialised object of the class `Settings`, whose constructor in turn expects an object corresponding to the type `RestSettings`. For an example, see object `environment.syshub` in the [Install/Setup configuration chapter](#setup-configuration).
## Usage
In any component you require access to the REST API import the `RestService`:
In each component that needs access to the sysHUB Rest API, the `RestService` must be imported and injected in the constructor of the component. Minimal example:
```ts
import { RestService } from 'syshub-rest-module';
@Component({})
export class FooComponent {
constructor(private restService: RestService) {}
}
```
### Userlogin example
The user login is programmed with a few lines of code. In the following example, the `onSubmitBtnClicked()` method is called by clicking a button in the HTML and the contents of the variables `username` and `password` are sent to the sysHUB server via the `login()` method of the *RestService*. The response is then either `true` in case of success or an error containing further information. In case of success, the Rest Service saves the received token and takes care of its renewal.
```ts
import { Component } from '@angular/core';
import { RestService } from 'syshub-rest-module';
@Component({
selector: 'app-login-min',
templateUrl: './login-min.component.html',
styleUrls: ['./login-min.component.scss']
})
export class LoginMinComponent {
username: string = 'foo';
password: string = '<foobar!>';
constructor(private restService: RestService) { }
onSubmitBtnClicked(): void {
this.restService.login(this.username, this.password).subscribe((response) => {
if (response === null) // Initial status, not yet any response from server
return;
if (response === true) // Login successfull
console.log(`User ${this.username} logged in`);
else // Error while logging in, see details in response
console.log(response);
});
}
}
```
### Userlogin
### Check login state before sending request
Within your components you are now able to access all service methods and properties. For example:
Before sending a request to the server's Rest API, it should be ensured that a user is logged in. For this, either the method `getIsLoggedIn()` of the *RestService* can be queried or subscribed to `isLoggedIn`. `isLoggedIn` reports every change of the login status and so it is also possible to react on successful logout and login.
```
In the following example code (which supplements the code from the previous section [Userlogin example](#userlogin-example)), the properties `loggedIn` and `sub` have been added. In the constructor, `RestService.isLoggedIn` is subscribed to and any status change is stored in `loggedIn`. The subscription itself is stored in `sub` and terminated when the component is exited.
```ts
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { RestService } from 'syshub-rest-module';
...
@Component({
selector: 'app-login-min',
templateUrl: './login-min.component.html',
styleUrls: ['./login-min.component.scss']
})
export class LoginMinComponent implements OnDestroy {
export class AppComponent {
username: string = 'foo';
password: string = '<foobar!>';
...
loggedIn: boolean = false;
sub?: Subscription;
constructor(private restService: RestService) {}
constructor(private restService: RestService) {
this.sub = this.restService.isLoggedIn.subscribe((state) => this.loggedIn = state);
}
...
ngOnDestroy(): void {
this.sub?.unsubscribe();
}
sendLogin(): void {
this.restService.login(this.username, this.password).subscribe((response) => {
console.log(response)
if (response == null) // initial status
return;
if (response === true) {
// login successfull
}
else {
// login failed
}
});
}
onSubmitBtnClicked(): void {
this.restService.login(this.username, this.password).subscribe((response) => {
if (response === null) // Initial status, not yet any response from server
return;
if (response === true) // Login successfull
console.log(`User ${this.username} logged in`);
else // Error while logging in, see details in response
console.log(response);
});
}
...
}

@@ -110,75 +202,81 @@ ```

### Calling Rest API endpoints
With version 2.0 of this module we started adding lots of methods to the Rest service to call designated endpoints like method `getCurrentUser()` to call the endpoint `/webapi/v2/currentUser`. A documentation of this methods is at the end of this document in chapter [Implemented endpoint methods](#implemented-endpoint-methods).
Whenever possible use this methods. If your require a call to a different Rest API endpoint that is not available as a method use one of the following generic methods for Http GET, POST, etc instead.
Calling Rest API endpoints is quite simple with the *RestService*. Call one of the generic methods `get()`, `post()`, `delete()`, `patch()` or `put()` of the *RestService* to reach any endpoint. For `post()`, `patch()` and `put()` a payload is required in addition to the endpoint. The content of the payload can be seen in the Swagger definition.
**Important**: The actual call to the sysHUB server only takes place when the result is subscribed to, nothing happens before that.
### Rest API GET
To send an HTTP GET to the Rest API use `get()` method from the RestService, for example:
#### HTTP GET
```
```ts
this.restService.get('currentUser').subscribe((response) => {
if (response.status == HttpStatusCode.Ok) {
// Ok response
// Rest API endpoint may return a different status, check Swagger UI to know which status to check for
} else {
//Failed response
}
if (response.status == HttpStatusCode.Ok) {
// Ok response
/**
* The sysHUB server may return a status code other than 200/OK.
* The specification for this can be found in Swagger.
*/
} else {
//Failed response
}
});
```
In case of OAuth Authentication: make sure the user is already logged in (subscribe to `RestService.isLoggedIn` or call `RestService.getIsLoggedIn()`). If user is not yet loggedin the endpoint will return HTTP Status code 401 (Unauthorized).
#### HTTP POST
### Rest API POST
To send an HTTP POST to the Rest API use `post()` method from the RestService, for example:
```
this.restService.post('jobs', myJobObject).subscribe((response) => {
if (response.status == HttpStatusCode.Ok) {
// Ok response
// Rest API endpoint may return a different status, check Swagger UI to know which status to check for
} else {
//Failed response
}
```ts
this.restService.post('jobs', {...}).subscribe((response) => {
if (response.status == HttpStatusCode.Ok) {
// Ok response
/**
* The sysHUB server may return a status code other than 200/OK.
* The specification for this can be found in Swagger.
*/
} else {
//Failed response
}
});
```
In case of OAuth Authentication: make sure the user is already logged in (subscribe to `RestService.isLoggedIn` or call `RestService.getIsLoggedIn()`). If user is not yet loggedin the endpoint will return HTTP Status code 401 (Unauthorized). Also make sure that your provided object matches the definition from sysHUB as you can find it in the Swagger UI.
### HTTP DELETE, PATCH and PUT
### Rest API DELETE, PATCH and PUT
The sysHUB Rest API also expects the HTTP methods Delete, Patch or Put depending on the endpoint. Therefore the RestService provides those methods too: `RestService.delete()`, `RestService.patch()` and `RestService.put()`.
As they work almost identically to the Get and Post methods, there's no separate usage guide here. Just replace `RestService.get()` with `RestService.delete()` to call a Delete-Endpoint. Replace `RestService.post()` with `RestService.patch()` or `RestService.put()` to call the Patch and Put endpoints. The later ones also expect an object to be sent to the Webserver.
The sysHUB Rest API also expects the HTTP methods Delete, Patch or Put depending on the endpoint. Accordingly, the *RestService* also provides these methods.
Since they work almost identically to the `get()` and `post()` methods, there are no separate instructions for their use here. Just replace `RestService.get()` with `RestService.delete()` to call a delete endpoint. Replace `RestService.post()` with `RestService.patch()` or `RestService.put()` to call the patch and put endpoints. The latter also expect an object to be sent to the web server.
## Configuration
### Typesafe methods
The configuration of the RestService is done with a `Settings` object which requires a `RestSettings` object. The later one can easily be created within the `environments`-files or at runtime (see [Install](#install) and [Usage](#usage)).
The `RestSettings` object must have basic or oauth enabled and may allow some other values:
As of version 2.0, this module also includes specialised, type-safe methods to call endpoints specifically and not use the generic way of e.g. `get()`. These methods are programmed so that both the parameters for the rest of the API call are typed, as are the return values from the sysHUB server. To do this, the method interposes itself between your calling code and the underlying generic method, typing all variables.
- `host`: **Required** (type string Url); Url to the sysHUB Webserer root, like `http://localhost:8088/`.
- `version`: Optional, **required for sysHUB 2021 server**; Pick one value from the enum:
- `SyshubVersion.sysHUB_2021`
- `SyshubVersion.sysHUB_2022`
- `SyshubVersion.sysHUB_2023`
- `SyshubVersion.DEFAULT` which is the same as `SyshubVersion.sysHUB_2023`
- `basic`: Optional, **required for basic authentication** (type object)
- `enabled`: Required (type boolean); `true` if basic auth to be enabled, default `false`.
- `username`: Optional, **required for basic authentication** (type string)
- `password`: Optional, **required for basic authentication** (type string)
- `provider`: Optional, **required for basic authentication** (type string); The name of the Api server provider from the sysHUB configuration
- `oauth`: Optional, **required for OAuth** (type object)
- `enabled`: Required (type boolean); `true` if OAuth to be enabled, default `false`.
- `clientId`: Optional, **required for OAuth** (type string); The name of the Auth server client
- `clientSecret`: Optional, **required for OAuth** (type string); The name of the Auth server client secret
- `scope`: Optional (type string); The scope as defined in the sysHUB Auth server, replace `;` with `+`. Allowed values: `private`, `public`, `private+public` or `public+private`, Default: `public`
- `storeKey`: Optional (type string); The name that is used to store the credentials in the local browser cache, Default: `authmod-session`
- `options`: Optional (type object)
- `autoConnect`, Optional (type boolean), Not yet implemented
- `autoLogoutOn401`, Optional (type boolean), If the sysHUB Rest API returns HTTP Status 401, this property causes the Rest Service to remove the users session information from the browser cache, Default: `true`
- `autoLogoutTimer`, Optional (type boolean), Not yet implemented
As an example, consider the method `getCurrentUser()`: This method calls the endpoint `currentUser` via HTTP GET and types the return value from the sysHUB server as type `SyshubUserAccount`. This data type is also included in the module and contains all the properties that the sysHUB server is guaranteed to deliver. Your calling code will then receive either this object or an object of type `Error` as a response, for example because no user is logged in.
## Implemented endpoint methods
The following methods provide a type-checked shorthand for the generic `get()`/`post()`/... implementation and also convert the default sysHUB response into a specialized one (eg. the console command `MEM` returns just a `string[]` which is converted into an object with meaningfull names and values). If the endpoint requires any payload, the specialized methods do expect this payload with a predefined interface to make sure you provide all the necessary information when calling it. Whenever possible use this methods instead of `get()` or the other ones.
#### List of typesafe methods
### backupSyshub(string, string, string, string[])
The following list is sorted by topic and endpoint (like Swagger).
| Method | Return type | Scope | Verb | Endpoint |
|:-------|:------------|:------|:-----|:---------|
| **Backup and Restore operations** | | | |
| [backupSyshub()](#backupsyshubstring-string-string-string) | `SyshubResponseSimple` | public | `POST` | `/webapi/v3/backuprestore/backup?folder=...` |
| [restoreSyshub()](#restoresyshubstring-string) | `SyshubResponseSimple` | public | `POST` | `/webapi/v3/backuprestore/restore?folder=...` |
| [getBackupMetadata()](#getbackupmetadatastring) | `SyshubBackupMeta` | public | `GET` | `/webapi/v3/backuprestore/metadata?folder=...` |
| **Certificate operations** | | | |
| [getCertStoreItems()](#getcertstoreitemskeystoretruststore) | `SyshubCertStoreItem` | public | `GET` | `/webapi/v3/certificate/list/...` |
| **Console operations** | | | |
| [runConsoleCommand()](#runconsolecommandstring-string) | `string[]` | public | `POST` | `/webapi/v3/consolecommands/execute/...` |
| [runConsoleCommandHelp()](#runconsolecommandhelp) | `{ [key: string]: string }`<br />(key = command, value = description of the command) | public | `POST` | `/webapi/v3/consolecommands/execute/HELP` |
| [runConsoleCommandMem()](#runconsolecommandmem) | `SyshubMemCommandResult` | public | `POST` | `/webapi/v3/consolecommands/execute/MEM` |
| [runConsoleCommandP()](#runconsolecommandp) | `SyshubPCommandLine[]` | public | `POST` | `/webapi/v3/consolecommands/execute/P` |
| **Job operations** | | | |
| [getJobs()](#getjobs) | `JobsResponse` / `SyshubJob[]` | public | `GET` | `/webapi/v3/jobs` |
| [createJob()](#createjobsyshubjob) | `JobResponse` / `SyshubJob` | public | `POST` | `/webapi/v3/jobs` |
| **Server operations** | | | |
| [getServerInformation()](#getserverinformation) | `SyshubServerInformation` | public | `GET` | `/webapi/v3/list/information` |
| [getServerProperties()](#getserverproperties) | `{ [key: string]: string }` | private | `GET` | `/webapi/v3/server/properties` |
| **User operations** | | | |
| [getCurrentUser()](#getcurrentuser) | `SyshubUserAccount` | public | `GET` | `/webapi/v3/currentUser` |
| **Workflow operations** | | | |
| [getWorkflowExecutions()](#getworkflowexecutions) | `SyshubWorkflowExecution[]` | public | `GET` | `/webapi/v3/workflows/execute` |
| [runWorkflow()](#runworkflowstring-bool-numberundefined) | `[string, number]`<br />(string = Status Url, number = HTTP Status) | public | `POST` | `/webapi/v3/workflows/execute` |
| [getWorkflowExecution()](#getworkflowexecution) | `SyshubWorkflowExecution[]` | public | `GET` | `/webapi/v3/workflows/execute?uuid=...` |
| [runWorkflowAlias()](#runworkflowaliasstring-anyundefined-string) | `any` | public | `POST` | `/webapi/v3/execute/alias/...` |
#### backupSyshub(string, string, string, string[])
This method calls the POST endpoint `/webapi/v3/backuprestore/backup?folder=...`.

@@ -193,3 +291,3 @@

### createJob(SyshubJob)
#### createJob(SyshubJob)
This method calls the POST endpoint `/webapi/v3/jobs`.

@@ -201,4 +299,4 @@

### getBackupMetadata(string)
This method calls the POST endpoint `/webapi/v3/backuprestore/metadata?folder=...`.
#### getBackupMetadata(string)
This method calls the GET endpoint `/webapi/v3/backuprestore/metadata?folder=...`.

@@ -209,3 +307,3 @@ - **Payload**:

### getCertStoreItems('keystore'|'truststore')
#### getCertStoreItems('keystore'|'truststore')
This method calls the GET endpoint `/webapi/v3/certificate/list/...`.

@@ -217,3 +315,3 @@

### getCurrentUser()
#### getCurrentUser()
This method calls the GET endpoint `/webapi/v3/currentUser`.

@@ -224,3 +322,3 @@

### getJobs()
#### getJobs()
This method calls the GET endpoint `/webapi/v3/jobs`.

@@ -236,3 +334,3 @@

### getServerInformation()
#### getServerInformation()
This method calls the GET endpoint `/webapi/v3/server/list/information`.

@@ -243,3 +341,3 @@

### getServerProperties()
#### getServerProperties()
This method calls the GET endpoint `/webapi/v3/server/properties`.

@@ -250,3 +348,3 @@

### getWorkflowExecution()
#### getWorkflowExecution()
This method calls the GET endpoint `/webapi/v3/workflows/execute?uuid=...` and returns a list of running workflow executions started via Rest API and matching the given uuid param.

@@ -257,3 +355,3 @@

### getWorkflowExecutions()
#### getWorkflowExecutions()
This method calls the GET endpoint `/webapi/v3/workflows/execute` and returns a list of running workflow executions started via Rest API.

@@ -264,3 +362,3 @@

### restoreSyshub(string, string[])
#### restoreSyshub(string, string[])
This method calls the POST endpoint `/webapi/v3/backuprestore/restore?folder=...`.

@@ -273,3 +371,3 @@

### runConsoleCommand(string, string[])
#### runConsoleCommand(string, string[])
This method calls the POST endpoint `/webapi/v3/consolecommands/execute/...`.

@@ -284,3 +382,3 @@

### runConsoleCommandHelp()
#### runConsoleCommandHelp()
This method calls the POST endpoint `/webapi/v3/consolecommands/execute/HELP`.

@@ -291,3 +389,3 @@

### runConsoleCommandMem()
#### runConsoleCommandMem()
This method calls the POST endpoint `/webapi/v3/consolecommands/execute/MEM`.

@@ -298,3 +396,3 @@

### runConsoleCommandP()
#### runConsoleCommandP()
This method calls the POST endpoint `/webapi/v3/consolecommands/execute/P`.

@@ -305,3 +403,3 @@

### runWorkflow(string, bool, number|undefined)
#### runWorkflow(string, bool, number|undefined)
This method calls the POST endpoint `/webapi/v3/workflows/execute` and starts an workflow execution optionally with job context.

@@ -317,3 +415,3 @@

### runWorkflowAlias(string, any|undefined, string)
#### runWorkflowAlias(string, any|undefined, string)
This method calls the endpoint `/webapi/v3/workflows/execute/alias/...` based on the given method (param 3) and returns whatever the workflow returns.

@@ -320,0 +418,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc