Initial commit

This commit is contained in:
Andreas Greiner 2021-08-02 17:04:26 +02:00
commit fe1c8c4c15
15 changed files with 5058 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules/
loginbase.db

8
Dockerfile Normal file
View File

@ -0,0 +1,8 @@
FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]

56
README.md Normal file
View File

@ -0,0 +1,56 @@
# MQTT <-> Webrequest-Bridge
This bridge delivers the functionality to post MQTT message on incoming web requests and call web requests on MQTT events. This all is bundles into a docker container.
## Building the container yourself
One can eighter use the public docker container **greinet/webmqttbridge** or build the container yourself.
docker build . -t ownname/webmqttbridge.
## Configuration
The configuration file is created by the docker container. The following command creates the **config.js** file in the current directory and deletes the docker container afterwards.
docker run --rm -v .:/usr/src/app/config agreiner/advancedmqttbridge npm run create_config
## Running the container
The contaier can be run via normal docker run or via docker compose. It is recommended to use a https-proxy as passwords and other confidential information is transfered in clear-text otherwise.
* docker run
docker run -v /home/ubuntu/config:/usr/src/app/config \
-v /home/ubuntu/database:/usr/src/app/database \
greinet/advancedmqttbridge npm run create_config
- docker compose with traefik example
advancedmqttbridge:
image: greinet/advancedmqttbridge
labels:
- "traefik.enable=true"
- "traefik.http.routers.advancedmqttbridge.rule=Host(`advancedmqttbridge.url.com`)"
- "traefik.http.routers.advancedmqttbridge.entrypoints=websecure"
- "traefik.http.routers.advancedmqttbridge.tls=true"
- "traefik.http.services.advancedmqttbridge.loadBalancer.server.port=3000"
- "traefik.docker.network=traefik"
restart: always
volumes:
- "/home/ubuntu/database:/usr/src/app/database"
- "/home/ubuntu/config:/usr/src/app/config"
networks:
- traefik
## Using the Bridge
- /login endpoint
Offers basic login and sign-up funcionality
![Login and Sign-up page](https://git.greinet.com/agreiner/advancedmqttbridge/raw/branch/master/images/login.png)
- /home endpoint
Offers the functionality to add listeners to mqtt topics and message values with a request url to be called if the message is posted to the topic.
![home page](https://git.greinet.com/agreiner/advancedmqttbridge/raw/branch/master/images/home.png)
- /mqttbridge endpoint
Reacts to GET-Request and takes as parameters the auth-token defined in the config.js, a mqtt topic and a message and then sends the message to the topic.
Example:
mqttbridge:3000/mqttbridge?auth=1234&topic=cmnd/kitchen/light&message=ON

12
createConfig.js Normal file
View File

@ -0,0 +1,12 @@
const fs = require('fs');
const path = require("path");
const pathToFile = path.join(__dirname, "sampleConfig.js")
const pathToNewDestination = path.join(__dirname, "config", "config.js")
try {
fs.copyFileSync(pathToFile, pathToNewDestination)
console.log("Successfully copied and moved config file!")
} catch(err) {
throw err
}

BIN
images/home.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
images/login.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -0,0 +1,88 @@
import mqtt from 'mqtt'
import config from '../config/config.js'
import request from 'request';
export default class MqttManager{
constructor(){}
init(){
this.messageHandlers = []
this.client = mqtt.connect(config.mqtt.url, config.mqtt.options)
console.log("[MQTT] Connected to MQTT broker ["+config.mqtt.url+"].");
this.ready = true
this.client.on('message', (topic, message) => {
if(this.getSubscribedTopics().includes(topic)){
console.log("[MQTT] Got message ["+message+"] on handled topic ["+topic+"].");
const suitingMessageHandlers = this.messageHandlers.filter(handler => handler.topic == topic && handler.message == message);
suitingMessageHandlers.forEach(handler => {
console.log("[MQTT] Sending web request ["+handler.requestUrl+"].");
request(handler.requestUrl, { json: true }, (err, res, body) => {
if (err) {
console.log("[MQTT] Error sending web request ["+handler.requestUrl+"].");
}else{
console.log("[MQTT] Sent web request ["+handler.requestUrl+"].");
}
});
});
}else{
console.log("[MQTT] Got message ["+message+"] on unhandled topic ["+topic+"].");
}
});
}
subscribe(topic){
this.client.subscribe(topic, function(err){
if(err != null){
console.log("[MQTT] Error subscribing to topic ["+topic+"].");
}else{
console.log("[MQTT] Subscribed to topic ["+topic+"].");
}
});
}
unsubscribe(topic){
this.client.unsubscribe(topic, function(err){
if(err != null){
console.log("[MQTT] Error unsubscribing to topic ["+topic+"].");
}else{
console.log("[MQTT] Unsubscribed to topic ["+topic+"].");
}
});
}
publishMessage(topic, message){
this.client.publish(topic, message);
console.log("[MQTT] Publishing message ["+message+"] in topic ["+topic+"].");
}
getSubscribedTopics(){
return this.messageHandlers.map(h => h.topic);
}
addMessageHandler(messageHandler){
if(!this.getSubscribedTopics().includes(messageHandler.topic)){
this.subscribe(messageHandler.topic)
}
this.messageHandlers.push(messageHandler);
console.log("[MQTT] Added new message handler ["+JSON.stringify(messageHandler)+"].");
}
removeMessageHandler(messageHandler){
const messageHandlerIndex = this.messageHandlers.findIndex(handler => handler.topic == messageHandler.topic && handler.message == messageHandler.message && handler.requestUrl == messageHandler.requestUrl);
if(messageHandlerIndex != -1){
this.messageHandlers = this.messageHandlers.splice(messageHandlerIndex,1);
console.log("[MQTT] Removed message handler ["+JSON.stringify(messageHandler)+"].");
}else{
console.log("[MQTT] Error removing message handler ["+JSON.stringify(messageHandler)+"].");
}
if(!this.getSubscribedTopics().includes(messageHandler.topic)){
this.unsubscribe(messageHandler.topic)
}
}
}

View File

@ -0,0 +1,71 @@
import sqlite3 from'sqlite3'
import { open } from 'sqlite'
/**
* Manager for handling the sqlite database
*/
export default class SqliteManager{
constructor(){}
async init(){
sqlite3.verbose()
await open({filename: './database/loginbase.db', driver: sqlite3.Database}).then(
(db) => {
console.log('[SQLITE] Connected to the loginbase database.');
db.run("CREATE TABLE IF NOT EXISTS users (email TEXT PRIMARY KEY, password TEXT)");
console.log('[SQLITE] Created users table if it didnt exist.');
db.run("CREATE TABLE IF NOT EXISTS handlers (topic TEXT, message TEXT, requestUrl TEXT)");
console.log('[SQLITE] Created handlers table if it didnt exist.');
this.database = db
this.ready = true
})
}
async getUser(email){
const result = await this.database.get('SELECT * FROM users WHERE email = ?', email)
console.log('[SQLITE] Got user from database ['+JSON.stringify(result.email)+'].')
return result
}
async addUser(email, password){
try{
await this.database.run(`INSERT INTO users(email, password) VALUES(:email, :password)`, {':email': email, ':password':password});
console.log("[SQLITE] Inserted new user("+email+").")
return true
}catch(err){
console.log("[SQLITE] Failed inserting new user("+email+"): "+err)
return false
}
}
async getHandlers(){
const result = await this.database.all('SELECT * FROM handlers')
console.log('[SQLITE] Got handlers from database ['+JSON.stringify(result)+'].')
return result
}
async addHandler(topic, message, requestUrl){
try{
await this.database.run(`INSERT INTO handlers(topic, message, requestUrl) VALUES(:topic, :message, :requestUrl)`, {':topic': topic, ':message':message, ':requestUrl': requestUrl});
console.log("[SQLITE] Inserted new handler [topic: "+topic+", message: "+message+", requestUrl: "+requestUrl+"].")
return true
}catch(err){
console.log("[SQLITE] Failed inserting new handler [topic: "+topic+", message: "+message+", requestUrl: "+requestUrl+"].")
return false
}
}
async removeHandler(topic, message, requestUrl){
const result = await this.database.run('DELETE FROM handlers WHERE topic = :topic AND message = :message AND requestUrl = :requestUrl', {':topic': topic, ':message': message, ':requestUrl': requestUrl})
if(result.changes>=1){
console.log("[SQLITE] Deleted message handler [topic: "+topic+", message: "+message+", requestUrl: "+requestUrl+"].")
}else{
console.log("[SQLITE] Failed deleting message handler [topic: "+topic+", message: "+message+", requestUrl: "+requestUrl+"].")
}
return result
}
}

4055
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

25
package.json Normal file
View File

@ -0,0 +1,25 @@
{
"dependencies": {
"bcrypt": "^5.0.1",
"crypto": "^1.0.1",
"express": "^4.17.1",
"express-session": "^1.17.2",
"mqtt": "^4.2.8",
"sqlite": "^4.0.23",
"sqlite3": "^5.0.2"
},
"name": "loginbase",
"version": "1.0.0",
"description": "Login base project",
"main": "server.mjs",
"scripts": {
"start": "node server.mjs",
"create_config": "node createConfig.js"
},
"repository": {
"type": "git",
"url": "https://git.greinet.com/agreiner/loginbase.git"
},
"author": "Andreas Greiner",
"license": "ISC"
}

223
public/html/home.html Normal file
View File

@ -0,0 +1,223 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Home</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body {
color: #404E67;
background: -webkit-linear-gradient(left, #03d9ff, #0004ff);
}
.table-wrapper {
width: 700px;
margin: 30px auto;
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 1px 1px rgba(0,0,0,.05);
}
.table-title {
padding-bottom: 10px;
margin: 0 0 10px;
}
.table-title h2 {
margin: 6px 0 0;
font-size: 22px;
}
.table-title .add-new {
float: right;
height: 30px;
font-weight: bold;
font-size: 12px;
text-shadow: none;
min-width: 100px;
border-radius: 50px;
line-height: 13px;
}
.table-title .add-new i {
margin-right: 4px;
}
.table-title .add-new{
background: -webkit-linear-gradient(left, #03d9ff, #0004ff);
}
table.table {
table-layout: fixed;
}
table.table tr th, table.table tr td {
border-color: #dfdfdf;;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table th:last-child {
width: 100px;
}
table.table td a {
cursor: pointer;
display: inline-block;
margin: 0 5px;
min-width: 24px;
}
table.table td a.add {
color: #27C46B;
}
table.table td a.edit {
color: #FFC107;
}
table.table td a.delete {
color: #E34724;
}
table.table td i {
font-size: 19px;
}
table.table td a.add i {
font-size: 24px;
margin-right: -1px;
position: relative;
top: 3px;
}
table.table .form-control {
height: 32px;
line-height: 32px;
box-shadow: none;
border-radius: 2px;
}
table.table .form-control.error {
border-color: #f50000;
}
table.table td .add {
display: none;
}
</style>
<script>
$(document).ready(function(){
fetch(window.location.origin+"/handlers", {
method: 'GET',
}).then(resp => resp.json()
).then(data => {
data.forEach(e=> {
var row = "<tr><td style='word-break:break-all;'>"+e.topic+"</td><td style='word-break:break-all;'>"+e.message+"</td><td style='word-break:break-all;'>"+e.requestUrl+"</td><td><a class='delete' title=''\
data-original-title='Delete'><i class='material-icons'></i></a></td></tr>";
$("table").append(row);
})
}).catch((error) => {console.log(error)});
var actions = "<a class='add' title='Add' ><i class='material-icons'>&#xE03B;\
</i></a><a class='delete' title='Delete' ><i class='material-icons'>&#xE872;</i></a>";
// Append table with add row form on add new button click
$(".add-new").click(function(){
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td style="word-break:break-all;"><input type="text" class="form-control" name="name" id="name"></td>' +
'<td style="word-break:break-all;"><input type="text" class="form-control" name="department" id="department"></td>' +
'<td style="word-break:break-all;"><input type="text" class="form-control" name="phone" id="phone"></td>' +
'<td style="word-break:break-all;">' + actions + '</td>' +
'</tr>';
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
});
// Add row on add button click
$(document).on("click", ".add", function(){
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
let values = []
input.each(function(){
values.push($(this).val())
if(!$(this).val()){
$(this).addClass("error");
empty = true;
} else{
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if(!empty){
input.each(function(){
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
fetch(window.location.origin+"/handlers/add", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({topic: values[0], message: values[1], requestUrl: values[2] })
}).then((resp) => {}).then((body) => {}).catch((error) => {});
}
});
// Delete row on delete button click
$(document).on("click", ".delete", function(){
let values = []
let doDelete = true
let parentTr = $(this).parent().siblings().each(function(){
values.push($(this).html())
doDelete = $(this).children().length <= 0
})
if(doDelete){
fetch(window.location.origin+"/handlers/remove", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({topic: values[0], message: values[1], requestUrl: values[2] })
}).then((resp) => {}).then((body) => {}).catch((error) => {});
}
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
</script>
</head>
<body>
<div class="container-lg">
<div class="table-responsive">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-8"><h2>Message Handlers</h2></div>
<div class="col-sm-4">
<button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
</div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Topic</th>
<th>Message</th>
<th>Request Url</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

329
public/html/login.html Normal file
View File

@ -0,0 +1,329 @@
<!DOCTYPE html>
<!-- Created By CodingNepal -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login and Registration</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
@import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
html,body{
display: grid;
height: 100%;
width: 100%;
place-items: center;
background: -webkit-linear-gradient(left, #03d9ff, #0004ff);
}
::selection{
background: #0004ff;
color: #fff;
}
.wrapper{
overflow: hidden;
max-width: 390px;
background: #fff;
padding: 30px;
border-radius: 5px;
box-shadow: 0px 15px 20px rgba(0,0,0,0.1);
}
.wrapper .title-text{
display: flex;
width: 200%;
}
.wrapper .title{
width: 50%;
font-size: 35px;
font-weight: 600;
text-align: center;
transition: all 0.6s cubic-bezier(0.68,-0.55,0.265,1.55);
}
.wrapper .slide-controls{
position: relative;
display: flex;
height: 50px;
width: 100%;
overflow: hidden;
margin: 30px 0 10px 0;
justify-content: space-between;
border: 1px solid lightgrey;
border-radius: 5px;
}
.slide-controls .slide{
height: 100%;
width: 100%;
color: #fff;
font-size: 18px;
font-weight: 500;
text-align: center;
line-height: 48px;
cursor: pointer;
z-index: 1;
transition: all 0.6s ease;
}
.slide-controls label.signup{
color: #000;
}
.slide-controls .slider-tab{
position: absolute;
height: 100%;
width: 50%;
left: 0;
z-index: 0;
border-radius: 5px;
background: -webkit-linear-gradient(left, #03d9ff, #0004ff);
transition: all 0.6s cubic-bezier(0.68,-0.55,0.265,1.55);
}
input[type="radio"]{
display: none;
}
#signup:checked ~ .slider-tab{
left: 50%;
}
#signup:checked ~ label.signup{
color: #fff;
cursor: default;
user-select: none;
}
#signup:checked ~ label.login{
color: #000;
}
#login:checked ~ label.signup{
color: #000;
}
#login:checked ~ label.login{
cursor: default;
user-select: none;
}
.wrapper .form-container{
width: 100%;
overflow: hidden;
}
.form-container .form-inner{
display: flex;
width: 200%;
}
.form-container .form-inner form{
width: 50%;
transition: all 0.6s cubic-bezier(0.68,-0.55,0.265,1.55);
}
.form-inner form .field{
height: 50px;
width: 100%;
margin-top: 20px;
}
.form-inner form .field input{
height: 100%;
width: 100%;
outline: none;
padding-left: 15px;
border-radius: 5px;
border: 1px solid lightgrey;
border-bottom-width: 2px;
font-size: 17px;
transition: all 0.3s ease;
}
.form-inner form .field input:focus{
border-color: #0004ff;
}
.form-inner form .field input::placeholder{
color: #999;
transition: all 0.3s ease;
}
form .field input:focus::placeholder{
color: #b3b3b3;
}
.form-inner form .pass-link{
margin-top: 5px;
}
.form-inner form .signup-link{
text-align: center;
margin-top: 30px;
}
.form-inner form .pass-link a, .form-inner form .signup-link a{
color: #0004ff;
text-decoration: none;
}
.form-inner form .pass-link a:hover, .form-inner form .signup-link a:hover{
text-decoration: underline;
}
form .btn{
height: 50px;
width: 100%;
border-radius: 5px;
position: relative;
overflow: hidden;
}
form .btn .btn-layer{
height: 100%;
width: 300%;
position: absolute;
left: -100%;
background: -webkit-linear-gradient(right, #03d9ff, #0004ff,#03d9ff, #0004ff);
border-radius: 5px;
transition: all 0.4s ease;;
}
form .btn:hover .btn-layer{
left: 0;
}
form .btn input[type="submit"]{
height: 100%;
width: 100%;
z-index: 1;
position: relative;
background: none;
border: none;
color: #fff;
padding-left: 0;
border-radius: 5px;
font-size: 20px;
font-weight: 500;
cursor: pointer;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="title-text">
<div class="title login">
Login Form
</div>
<div class="title signup">
Signup Form
</div>
</div>
<div class="form-container">
<div class="slide-controls">
<input type="radio" name="slide" id="login" checked>
<input type="radio" name="slide" id="signup">
<label for="login" class="slide login">Login</label>
<label for="signup" class="slide signup">Signup</label>
<div class="slider-tab"></div>
</div>
<div class="form-inner">
<form action="login" class="login" id="login">
<div class="field">
<input type="text" placeholder="Email Address" id="loginEmail" required>
</div>
<div class="field">
<input type="password" placeholder="Password" id="loginPassword" required>
</div>
<!--<div class="pass-link">
<a href="#">Forgot password?</a>
</div>-->
<div class="field btn">
<div class="btn-layer"></div>
<input type="submit" value="Login">
</div>
<div class="signup-link">
Not a member? <a href="">Signup now</a>
</div>
</form>
<form action="register" class="signup" id="signup">
<div class="field">
<input type="email" placeholder="Email Address" id="signupEmail" required>
</div>
<div class="field">
<input type="password" placeholder="Password" id="signupPassword" onkeyup="check();" required minlength="8" >
</div>
<div class="field">
<input type="password" placeholder="Confirm password" id="signupPasswordConfirm" onkeyup="check();" required minlength="8">
</div>
<div class="field btn">
<div class="btn-layer"></div>
<input type="submit" value="Signup">
</div>
</form>
</div>
</div>
</div>
<script>
var check = function() {
if (document.getElementById('signupPassword').value ==
document.getElementById('signupPasswordConfirm').value) {
document.getElementById('signupPasswordConfirm').style.borderColor = '#0004ff';
} else {
//box-shadow: 0px 15px 20px rgba(0,0,0,0.1);
document.getElementById('signupPasswordConfirm').style.borderColor = '#ff0000';
}
}
const loginText = document.querySelector(".title-text .login");
const loginForm = document.querySelector("form.login");
const loginBtn = document.querySelector("label.login");
const signupBtn = document.querySelector("label.signup");
const signupLink = document.querySelector("form .signup-link a");
signupBtn.onclick = (()=>{
loginForm.style.marginLeft = "-50%";
loginText.style.marginLeft = "-50%";
});
loginBtn.onclick = (()=>{
loginForm.style.marginLeft = "0%";
loginText.style.marginLeft = "0%";
});
signupLink.onclick = (()=>{
signupBtn.click();
return false;
});
</script>
<script>
document.forms['login'].addEventListener('submit', (event) => {
event.preventDefault();
fetch(event.target.action, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email: document.getElementById("loginEmail").value, password: document.getElementById("loginPassword").value })
}).then((resp) => {
switch(resp.status){
case 400:
alert("No user found")
break;
case 200:
window.location.href="home"
break;
case 401:
alert("Wrong password")
break;
case 500:
alert("Internal server Error")
break;
}
}).then((body) => {}).catch((error) => {});
});
document.forms['signup'].addEventListener('submit', (event) => {
event.preventDefault();
if(document.getElementById('signupPassword').value !=
document.getElementById('signupPasswordConfirm').value){
alert("password mismatch")
return;
}
fetch(event.target.action, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email: document.getElementById("signupEmail").value, password: document.getElementById("signupPassword").value })
}).then((resp) => {
switch(resp.status){
case 400:
alert("User already exists")
break;
case 201:
window.location.href="home"
break;
}
}).then((body) => {}).catch((error) => {});
});
</script>
</body>
</html>

21
sampleConfig.js Normal file
View File

@ -0,0 +1,21 @@
var config = {}
config.mqtt = {}
config.sqlite = {}
config.mqtt.options = {
clientId: 'mqttclientid',
username: 'mqttusername',
password: 'mqttpassword',
keepalive: 60,
reconnectPeriod: 1000,
protocolVersion: 3,
protocolId: 'MQIsdp',
clean: true,
encoding: 'utf8'
};
config.mqtt.url = 'mqtt://MQTTURL'
config.auth = "random auth token"
module.exports = config

147
server.mjs Normal file
View File

@ -0,0 +1,147 @@
// Libraries
import express from 'express'
import bcrypt from 'bcrypt'
import session from 'express-session'
import path from 'path'
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import crypto from "crypto";
import config from './config/config.js'
import SqliteManager from "./own_modules/sqliteManager.mjs"
import MqttManager from "./own_modules/mqttManager.mjs"
// Setup express
const app = express()
app.use(express.json())
var randomSecret = crypto.randomBytes(20).toString('hex');
app.use(session({
secret: randomSecret,
resave: true,
saveUninitialized: true
}));
// Setup path
const __dirname = dirname(fileURLToPath(import.meta.url));
// Setup database manager
var databaseManager = new SqliteManager();
await databaseManager.init();
// Setup mqtt manager
var mqttManager = new MqttManager();
mqttManager.init();
// Update mqtt handlers from sqlite
initMqttHandlers();
// Register route
app.post('/register', async (req, res) => {
var password = req.body.password
var email = req.body.email
if(password && email){
const hashedPassword = await bcrypt.hash(req.body.password, 10);
let inserted = await databaseManager.addUser(email, hashedPassword)
if(inserted){
req.session.loggedin = true
req.session.email = email
res.sendStatus(201)
}else{
res.sendStatus(400)
}
}else{
res.sendStatus(400)
}
})
// Default GET route, redirects to login when not logged in or to the homepage when logged in
app.get('/', function(req, res) {
if(req.session.loggedin){
res.redirect("/home")
}else{
res.redirect("/login")
}
});
// Login GET route
app.get('/login', function(request, response) {
response.sendFile(path.join(__dirname + '/public/html/login.html'));
});
// Login POST route
app.post('/login', async (req,res) => {
const user = await databaseManager.getUser(req.body.email);
if(user == null){
return res.sendStatus(400)
}
try{
if(await bcrypt.compare(req.body.password, user.password)){
req.session.loggedin = true
req.session.email = user.email
res.sendStatus(200);
}else{
res.sendStatus(401)
}
}catch{
res.status(500).send()
}
})
// Home GET route
app.get('/home', function(request, response) {
if (request.session.loggedin) {
response.sendFile(path.join(__dirname + '/public/html/home.html'));
} else {
response.redirect('/login');
}
});
app.get('/mqttbridge', (req, res)=>{
var auth = req.query.auth;
var topic = req.query.topic;
var message = req.query.message;
if(auth == undefined || topic == undefined || message == undefined){
res.sendStatus(400);
}else if(auth != config.auth){
res.sendStatus(401);
}else{
mqttManager.publishMessage(topic, message)
res.sendStatus(200);
}
})
app.get('/handlers', async (req, res)=>{
var answer = await databaseManager.getHandlers();
res.json(answer);
})
app.post('/handlers/remove', async (req,res) =>{
let topic = req.body.topic;
let message = req.body.message;
let requestUrl = req.body.requestUrl;
await databaseManager.removeHandler(topic, message, requestUrl)
res.sendStatus(200)
mqttManager.removeMessageHandler({topic: topic, message: message, requestUrl: requestUrl})
})
app.post('/handlers/add', async (req,res) => {
let topic = req.body.topic;
let message = req.body.message;
let requestUrl = req.body.requestUrl;
await databaseManager.addHandler(topic, message, requestUrl)
res.sendStatus(200)
mqttManager.addMessageHandler({topic: topic, message: message, requestUrl: requestUrl})
})
async function initMqttHandlers(){
console.log("[MAIN] Initializing mqtt handlers from database.")
let handlers = await databaseManager.getHandlers();
handlers.forEach(handler => {
mqttManager.addMessageHandler(handler)
});
}
app.listen(3000)

21
test/request.rest Normal file
View File

@ -0,0 +1,21 @@
GET http://localhost:3000/users
###
POST http://localhost:3000/users
Content-Type: application/json
{
"email": "kyle@kyle.de",
"password": "password"
}
###
POST http://localhost:3000/users/login
Content-Type: application/json
{
"username": "Kyle",
"password": "password1"
}