Skip to content

Commit

Permalink
[#172975866] 🔒 Add support for API token
Browse files Browse the repository at this point in the history
Update the java demo code so it's possible to add an api token. 
fixit

Added authentication to the HTML example. You need to supply a token and press authenticate.
  • Loading branch information
bobhobelman committed Jul 22, 2020
1 parent 532d442 commit 96ab4d0
Show file tree
Hide file tree
Showing 19 changed files with 244 additions and 117 deletions.
41 changes: 37 additions & 4 deletions html/NedapApiWebSocketClient.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

if ('WebSocket' in window) {
document.getElementById('initButton').disabled = false;
document.getElementById('closeButton').disabled = true;
document.getElementById('subscribe').disabled = true;
document.getElementById('heartbeat').disabled = true;
} else {
Expand All @@ -23,6 +24,19 @@
}
}

function authorize() {
if ( document.getElementById("token").value ) {
writeToScreen("Start authentication.")
var authenticate = new Object();
authenticate.request = 'authenticate'
authenticate.token = document.getElementById("token").value;
var requestJson = JSON.stringify(authenticate)
eventsWebSocket.send(requestJson)
} else {
writeToScreen("Please add an token.")
}
}

function initWebSocket() {
var ipAddress = document.getElementById('websocketUrl').value;
var url = "ws://" + ipAddress + "/api/v2/events";
Expand All @@ -34,19 +48,35 @@
eventsWebSocket.onerror = function(event) { onError(event) };
}

function closeWebSocket() {
eventsWebSocket.close();
}

function onOpen(event, url) {
writeToScreen("Connected to Renos API WebSocket server " + url);
authorize()
document.getElementById('initButton').disabled = true;
document.getElementById('closeButton').disabled = false;
document.getElementById('subscribe').disabled = false;
document.getElementById('heartbeat').disabled = false;
writeToScreen("Connected to Renos API WebSocket server " + url);
}

function onClose(event, url) {
document.getElementById('initButton').disabled = false;
document.getElementById('closeButton').disabled = true;
document.getElementById('subscribe').disabled = true;
document.getElementById('heartbeat').disabled = true;

if (document.getElementById('autoReconnect').checked) {
if(event.code) {
writeError("Something went wrong. Response code: " + event.code);
} else {
writeToScreen("Disconnected from Renos API WebSocket server " + url);
}
if (document.getElementById('autoReconnect').checked) {

reconnect();
}
}

function onMessage(event) {
Expand Down Expand Up @@ -166,9 +196,12 @@
</head>
<body>
<h2>Nedap Renos WebSocket API V2 Client</h2>
<span>Please enter IP address on which Renos can be found:
<input id="websocketUrl" type="text"/>
<button id="initButton" style="width:50px" onclick="initWebSocket()">Init</button>
<span>
Please enter IP address on which Renos can be found: <input id="websocketUrl" type="text"/>
Token: <input type="text" id="token" style="width:150px"/>
<button id="initButton" style="width:50px" onclick="initWebSocket()" >Init</button>
<button id="closeButton" style="width:50px" onclick="closeWebSocket()" >Close</button><br><br>
Automaticly reconnect: <input type="checkbox" id="autoReconnect" value="reconnect"/><br><br>
</span>
<div style="width:400px">
<fieldset>
Expand Down
2 changes: 1 addition & 1 deletion java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
<dependency>
<groupId>com.nedap.retail.renos.api.v2</groupId>
<artifactId>renos-api-message</artifactId>
<version>1.1</version>
<version>1.2</version>
</dependency>
</dependencies>

Expand Down
Binary file not shown.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0f2a57a8e5cb3cb46cef0ecc317c61c2
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
751ae6a1a07c53cc9514725b5be992a35e0b7941
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
<artifactId>RhEAS</artifactId>
<groupId>com.nedap.retail</groupId>
<version>develop-SNAPSHOT</version>
</parent>

<groupId>com.nedap.retail.renos.api.v2</groupId>
<artifactId>renos-api-message</artifactId>
<version>1.2</version>
<!-- <version/> is not defined because we want to inherit the parent (Renos) version -->
<packaging>jar</packaging>

<name>Renos API v2 Message Parser</name>
<properties>
<java.version.supported>1.8</java.version.supported>
</properties>

<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.nedap.retail</groupId>
<artifactId>renos-json</artifactId>
<version>develop-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version.supported}</source>
<target>${java.version.supported}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

<distributionManagement>
<snapshotRepository>
<id>snapshots</id>
<name>libs-snapshots</name>
<url>http://${artifactory.server}:8081/artifactory/libs-snapshots-local</url>
</snapshotRepository>
<repository>
<id>releases</id>
<name>libs-releases</name>
<url>http://${artifactory.server}:8081/artifactory/libs-releases-local</url>
</repository>
</distributionManagement>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a14948be1b2aea8cabd28a559b2eb576
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
d15ee5f972c85c4be94970105d31f2c88832c59a
92 changes: 56 additions & 36 deletions java/src/main/java/com/nedap/retail/example/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,10 @@
import java.util.function.Function;
import java.util.stream.Collectors;

import com.nedap.retail.example.rest.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nedap.retail.example.rest.ApiCaller;
import com.nedap.retail.example.rest.HttpRequestException;
import com.nedap.retail.example.rest.InputParsingException;
import com.nedap.retail.example.rest.MessageParsingException;
import com.nedap.retail.example.websocket.client.RenosWebSocketClient;
import com.nedap.retail.renos.api.v2.rest.message.*;
import com.nedap.retail.renos.api.v2.rest.message.Settings.LightAndSoundStatus;
Expand All @@ -32,21 +29,28 @@ public class Application {

private static RenosWebSocketClient client;
private static ApiCaller api;
private static String BASE_URL;

public static void main(final String[] args) {
if (args.length == 0) {
LOG.info("Please use URL of device as parameter, for example: http://localhost:8081");
System.exit(0);
} else {
BASE_URL = trimTrailingSlash(args[0]);
}

final String baseUrl = trimTrailingSlash(args[0]);

api = new ApiCaller(baseUrl);
api = new ApiCaller(BASE_URL);

LOG.info("Application starting...");
client = new RenosWebSocketClient(baseUrl);
client = new RenosWebSocketClient(BASE_URL);

try (BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in))) {


addAuthentication(inputBuffer);

client.run();

String input;
Expand Down Expand Up @@ -80,14 +84,16 @@ private static void printMenu() {
// print line
LOG.info("------------------------------------------------------");
LOG.info("Available commands:");
LOG.info(" a) authenticate against Renos");
LOG.info(" a) add authentication token");
LOG.info(" h) send heartbeat to Renos");
LOG.info(" i) get system information from Renos");
LOG.info(" g) get group information from Renos");
LOG.info(" s) get system status from Renos");
LOG.info(" t) get system settings from Renos");
LOG.info(" u) update system settings");
LOG.info(" b) send blink request to Renos");
LOG.info(" r) reconnect WS to Renos");
LOG.info(" d) disconnect WS to Renos");
LOG.info(" e) subscribe to events from Renos");
LOG.info("Please enter your choice and press Enter, or just Enter to exit.");
// print line
Expand All @@ -99,7 +105,7 @@ private static void handleCommand(final BufferedReader inputBuffer, final char k
try {
switch (keycode) {
case 'a':
handleBasicAuthentication(inputBuffer);
addAuthentication(inputBuffer);
break;
case 'h':
sendHeartbeat(inputBuffer);
Expand All @@ -122,6 +128,12 @@ private static void handleCommand(final BufferedReader inputBuffer, final char k
case 'b':
sendBlinkRequest(inputBuffer);
break;
case 'r':
reconnectWSToRenos();
break;
case 'd':
disconnectWSToRenos();
break;
case 'e':
subscribeToEvents(inputBuffer);
break;
Expand All @@ -130,24 +142,24 @@ private static void handleCommand(final BufferedReader inputBuffer, final char k
printMenu();
break;
}
} catch (final UnauthorizedException e) {
LOG.info("Unauthorized access to Renos API. Please supply a valid toke in your requests.");
} catch (final HttpRequestException | MessageParsingException | InputParsingException e) {
LOG.info(e.getMessage());
} catch (final Exception e) {
LOG.error("There was an error in communication with Renos: ", e);
}
}

private static void handleBasicAuthentication(final BufferedReader inputBuffer) throws IOException {
LOG.info("Please supply credentials needed for authentication against Renos API.");
LOG.info("Credentials are only needed if basic authentication is enabled for Renos.");
LOG.info("If that's not the case, feel free to press Enter when asked for username and password");
private static void addAuthentication(final BufferedReader inputBuffer) throws Exception {
LOG.info("Please supply a token needed for authentication against Renos API.");
LOG.info("A token is only needed if authentication is enabled for Renos.");
LOG.info("Authentication is default enabled for firmware versions after 20.10.");
LOG.info("");
LOG.info("Please enter username:");
final String username = inputBuffer.readLine();
LOG.info("Please enter password:");
final String password = inputBuffer.readLine();
api.setUsername(username);
api.setPassword(password);
LOG.info("Please enter token:");
final String token = readString(inputBuffer, "");
api.setToken(token);
client.setToken(token);
}

private static void sendHeartbeat(final BufferedReader inputBuffer) throws IOException {
Expand Down Expand Up @@ -177,50 +189,50 @@ private static void sendHeartbeat(final BufferedReader inputBuffer) throws IOExc
private static void retrieveSystemInfo() throws MessageParsingException, HttpRequestException {
final SystemInfo info = api.retrieveSystemInfo();
LOG.info("System info");
LOG.info("System id: {}", info.id);
LOG.info("Firmware version: {}", info.version);
LOG.info("System role: {}", info.systemRole);
LOG.info("System time: {}", info.systemTime);
LOG.info("System id: {}", info.getId());
LOG.info("Firmware version: {}", info.getVersion());
LOG.info("System role: {}", info.getSystemRole());
LOG.info("System time: {}", info.getSystemTime());
}

private static void logGroupInfo(final GroupInfo.Group group) {
if (group != null) {
LOG.info("Group {}: '{}'", group.id, group.name);
if (group.units != null) {
for (final GroupInfo.Unit u : group.units) {
LOG.info("Group {}: '{}'", group.getId(), group.getName());
if (group.getUnits() != null) {
for (final GroupInfo.Unit u : group.getUnits()) {
LOG.info(" Unit {}: '{}'", u.id, u.name);
}
}
if (group.aisles != null) {
LOG.info(" Aisles: {}", group.aisles.stream().map((a) -> a.id).collect(Collectors.toList()));
if (group.getAisles() != null) {
LOG.info(" Aisles: {}", group.getAisles().stream().map((a) -> a.getId()).collect(Collectors.toList()));
}
}
}

private static void retrieveGroupInfo() throws MessageParsingException, HttpRequestException {
final GroupInfo groupInfo = api.retrieveGroupInfo();
LOG.info("Group information");
for (final GroupInfo.Group group : groupInfo.groups) {
for (final GroupInfo.Group group : groupInfo.getGroups()) {
logGroupInfo(group);
}
}

private static void retrieveSystemStatus() throws MessageParsingException, HttpRequestException {
final SystemStatus status = api.retrieveSystemStatus();
LOG.info("System status");
LOG.info("Unreachable units: {}", status.unreachableUnits != 0);
LOG.info("Device management connection error: {}", status.deviceManagementConnectionError != 0);
LOG.info("Rfid reader errors: {}", status.rfidErrors != 0);
LOG.info("Blocked IR beam sensors: {}", status.blockedIrBeamSensors != 0);
LOG.info("Unreachable units: {}", status.getUnreachableUnits() != 0);
LOG.info("Device management connection error: {}", status.getDeviceManagementConnectionError() != 0);
LOG.info("Rfid reader errors: {}", status.getRfidErrors() != 0);
LOG.info("Blocked IR beam sensors: {}", status.getBlockedIrBeamSensors() != 0);
}

private static void retrieveSystemSettings() throws MessageParsingException, HttpRequestException {
final Settings settings = api.retrieveSystemSettings();
LOG.info("System settings");
LOG.info("RF enabled {}", settings.enableRf);
LOG.info("RFID enabled {}", settings.enableRfid);
LOG.info("RF alarm triggers {}", settings.lightSoundRf);
LOG.info("RFID alarm triggers {}", settings.lightSoundRfid);
LOG.info("RF enabled {}", settings.getEnableRf());
LOG.info("RFID enabled {}", settings.getEnableRfid());
LOG.info("RF alarm triggers {}", settings.getLightSoundRf());
LOG.info("RFID alarm triggers {}", settings.getLightSoundRfid());
}

private static void updateSystemSettings(final BufferedReader inputBuffer)
Expand Down Expand Up @@ -318,6 +330,14 @@ private static void sendBlinkRequest(final BufferedReader inputBuffer)
api.sendBlink(request);
}

private static void reconnectWSToRenos() {
client.reconnect();
}

private static void disconnectWSToRenos(){
client.disconnect();
}

private static void subscribeToEvents(final BufferedReader inputBuffer)
throws InputParsingException, HttpRequestException {
LOG.info("Subscribe to: ");
Expand Down
Loading

0 comments on commit 96ab4d0

Please sign in to comment.