Merge pull request #6 from IngProjDutzlerHeiligenbrunnerMeindl/configurationpage

Configurationpage
This commit is contained in:
Lukas-Heiligenbrunner 2020-04-15 16:59:23 +02:00 committed by GitHub
commit d680046768
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 256 additions and 57 deletions

View File

@ -3,6 +3,7 @@ package com.wasteinformationserver
import com.wasteinformationserver.basicutils.Info
import com.wasteinformationserver.basicutils.Log
import com.wasteinformationserver.basicutils.Storage
import com.wasteinformationserver.db.JDBC
import com.wasteinformationserver.mqtt.MqttService
import com.wasteinformationserver.website.Webserver
@ -16,6 +17,7 @@ import java.io.IOException
fun main() {
Log.setLevel(Log.DEBUG)
Info.init()
Storage.getInstance().init()
Log.info("startup of WasteInformationServer")
@ -23,6 +25,7 @@ fun main() {
try {
Thread.sleep(200)
Log.warning("Shutting down ...")
JDBC.getInstance().disconnect();
//shutdown routine
} catch (e: InterruptedException) {
e.printStackTrace()
@ -35,10 +38,11 @@ fun main() {
//initial connect to db
Log.message("initial login to db")
try {
JDBC.init("ingproject", "Kb9Dxklumt76ieq6", "ingproject", "db.power4future.at", 3306)
// todo make dynamic with settings page
val stor = Storage.getInstance();
JDBC.init(stor.dbUser, stor.dbPassword, stor.dbName, stor.dbhost, stor.dbPort)
//JDBC.init("ingproject", "Kb9Dxklumt76ieq6", "ingproject", "db.power4future.at", 3306)
//JDBC.init("users", "kOpaIJUjkgb9ur6S", "wasteinformation", "192.168.65.15", 3306);
} catch (e: IOException) { //e.printStackTrace();
} catch (e: IOException) {
Log.error("no connection to db")
}
@ -51,6 +55,11 @@ fun main() {
//startup mqtt service
Log.message("starting mqtt service")
val m = MqttService("mqtt.heili.eu", "1883") // todo make dynamic with settings page
m.startupService()
if (JDBC.isConnected()) {
val m = MqttService(Storage.getInstance().mqttServer, Storage.getInstance().mqttPort.toString())
// val m = MqttService("mqtt.heili.eu", "1883")
m.startupService()
}else{
Log.error("could't start mqtt service because of missing db connection!")
}
}

View File

@ -0,0 +1,163 @@
package com.wasteinformationserver.basicutils
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
/**
* Storage of user information
* * database infos
* * mqtt infos
*
* @author Lukas Heiligenbrunner
*/
class Storage {
companion object {
private val obj = Storage()
fun getInstance(): Storage {
return obj;
}
}
var mqttServer: String = ""
get() = field
set(value) {
field = value
}
var mqttPort: Int = -1
get() = field
set(value) {
field = value
}
var dbName: String = ""
get() = field
set(value) {
field = value
}
var dbhost: String = ""
get() = field
set(value) {
field = value
}
var dbUser: String = ""
get() = field
set(value) {
field = value
}
var dbPassword: String = ""
get() = field
set(value) {
field = value
}
var dbPort: Int = -1
get() = field
set(value) {
field = value
}
private val prop = Properties()
/**
* init config file
*/
fun init() {
try {
// try to load existing config file
val inp = FileInputStream("settings.prop")
prop.load(inp)
mqttServer = prop["mqttserver"] as String
mqttPort = (prop["mqttport"] as String).toInt()
dbhost = prop["dbhost"] as String
dbName = prop["dbname"] as String
dbUser = prop["dbuser"] as String
dbPassword = prop["dbpass"] as String
dbPort = (prop["dbport"] as String).toInt()
} catch (ee: FileNotFoundException) {
// file not generated yet
store()
Log.info("new Settings config file generated")
} catch (e: IOException) {
e.printStackTrace()
}
}
/**
* store data to storage file
*/
fun store() {
prop["mqttserver"] = mqttServer
prop["mqttport"] = mqttPort.toString()
prop["dbhost"] = dbhost
prop["dbname"] = dbName
prop["dbuser"] = dbUser
prop["dbpass"] = dbPassword
prop["dbport"] = dbPort.toString()
prop.store(FileOutputStream("settings.prop"), "main config")
}
/**
* check if all needed properties are set up correctly
* todo real check if connections can be established
*/
fun isEveryThingDefined(): Boolean {
return (isMqttServerDefined() &&
isMqttPortDefined() &&
isDBNameDefined() &&
isDBUsernameDefined() &&
isDBPasswdDefined() &&
isDBPortDefined())
}
/**
* is the mqttservername defined?
*/
fun isMqttServerDefined(): Boolean {
return (mqttServer != "")
}
/**
* is the mqttserver port defined?
*/
fun isMqttPortDefined(): Boolean {
return (mqttPort != -1)
}
/**
* is the dbname defined?
*/
fun isDBNameDefined(): Boolean {
return (dbName != "")
}
/**
* is the dbport defined?
*/
fun isDBPortDefined(): Boolean {
return (dbPort != -1)
}
/**
* is the dbpassword defined?
*/
fun isDBPasswdDefined(): Boolean {
return (dbPassword != "")
}
/**
* is the dbusername defined?
*/
fun isDBUsernameDefined(): Boolean {
return (dbUser != "")
}
}

View File

@ -99,6 +99,14 @@ public class JDBC {
}
}
public void disconnect(){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* execute basic query --> requests only
*
@ -133,7 +141,7 @@ public class JDBC {
*
* @return connection state
*/
public boolean isConnected() {
public static boolean isConnected() {
return loggedin;
}
}

View File

@ -4,6 +4,7 @@ import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.wasteinformationserver.basicutils.Log.Log.debug
import com.wasteinformationserver.basicutils.Log.Log.warning
import com.wasteinformationserver.basicutils.Storage
import com.wasteinformationserver.website.datarequests.login.LoginState
import java.io.IOException
@ -19,15 +20,20 @@ class MainPage : HttpHandler {
if (path == "/") {
path += "index.html"
}
debug("looking for: $path")
if (path.contains(".html")) {
if (LoginState.getObject().isLoggedIn || path == "/register.html" || path == "/index.html") { //pass only register page
// if not logged in allow only register and index page!
if (LoginState.getObject().isLoggedIn || path == "/register.html" || path == "/index.html") {
sendPage(path, t)
} else {
}
else {
warning("user not logged in --> redirecting to login page")
sendPage("/index.html", t)
}
} else { //only detect login state on html pages
}
else {
//only detect login state on html pages
sendPage(path, t)
}
}
@ -38,9 +44,11 @@ class MainPage : HttpHandler {
if (fs == null && path.contains(".html")) {
warning("wrong page sending 404")
sendPage("/404Error.html", t)
} else if (fs == null) {
}
else if (fs == null) {
warning("requested resource doesnt exist --> $path")
} else { // Object exists and is a file: accept with response code 200.
}
else { // Object exists and is a file: accept with response code 200.
var mime = "text/html"
val s = path.substring(path.length - 3)
if (s == ".js") mime = "application/javascript"

View File

@ -22,11 +22,12 @@ class DataRequest : PostRequest() {
val sb = StringBuilder()
var set: ResultSet?
var status = -1
val jdbc: JDBC = JDBC.getInstance()
if (!jdbc.isConnected) {
if (!JDBC.isConnected()) {
error("no connection to db")
return "{\"query\" : \"nodbconn\"}"
}
val jdbc: JDBC = JDBC.getInstance()
when (params["action"]) {
/**

View File

@ -15,11 +15,11 @@ import java.util.*
*/
class DeviceRequest : PostRequest() {
override fun request(params: HashMap<String, String>): String {
val jdbc = JDBC.getInstance()
if (!jdbc.isConnected) {
if (!JDBC.isConnected()) {
error("no connection to db")
return "{\"query\" : \"nodbconn\"}"
}
val jdbc: JDBC = JDBC.getInstance()
val sb = StringBuilder()
val deviceset: ResultSet
@ -28,7 +28,7 @@ class DeviceRequest : PostRequest() {
* return all available devices
*/
"getdevices" -> {
deviceset = jdbc!!.executeQuery("SELECT * FROM `devices")
deviceset = jdbc.executeQuery("SELECT * FROM `devices")
sb.append("{\"data\":[")
try {
while (deviceset.next()) {
@ -67,7 +67,7 @@ class DeviceRequest : PostRequest() {
* returns all available city names
*/
"getCitynames" -> {
deviceset = jdbc!!.executeQuery("select * from cities")
deviceset = jdbc.executeQuery("select * from cities")
debug(deviceset.toString())
sb.append("{")
try {
@ -91,7 +91,7 @@ class DeviceRequest : PostRequest() {
* returns all available zones for specified city
*/
"getzones" -> {
deviceset = jdbc!!.executeQuery("select * from cities WHERE `name`='" + params["cityname"] + "' ORDER BY zone ASC")
deviceset = jdbc.executeQuery("select * from cities WHERE `name`='" + params["cityname"] + "' ORDER BY zone ASC")
debug(deviceset.toString())
sb.append("{")
try {
@ -114,7 +114,7 @@ class DeviceRequest : PostRequest() {
* returns all available waste types for specified zone and city
*/
"gettypes" -> {
deviceset = jdbc!!.executeQuery("select * from cities WHERE `name`='" + params["cityname"] + "' AND `zone`='" + params["zonename"] + "' ORDER BY zone ASC")
deviceset = jdbc.executeQuery("select * from cities WHERE `name`='" + params["cityname"] + "' AND `zone`='" + params["zonename"] + "' ORDER BY zone ASC")
debug(deviceset.toString())
sb.append("{")
try {
@ -137,7 +137,7 @@ class DeviceRequest : PostRequest() {
* configure device and save infos to db
*/
"savetodb" -> try {
val cityset = jdbc!!.executeQuery("SELECT id from cities WHERE `name`='" + params["cityname"] + "' AND `zone`='" + params["zonename"] + "' AND `wastetype`='" + params["wastetype"] + "'")
val cityset = jdbc.executeQuery("SELECT id from cities WHERE `name`='" + params["cityname"] + "' AND `zone`='" + params["zonename"] + "' AND `wastetype`='" + params["wastetype"] + "'")
cityset.last()
if (cityset.row != 1) {
error("error saving device to db --> device multiply defined?")

View File

@ -17,11 +17,13 @@ class NewDateRequest : PostRequest() {
override fun request(params: HashMap<String, String>): String {
val sb = StringBuilder()
val set: ResultSet
val jdbc = JDBC.getInstance()
if (!jdbc.isConnected) {
if (!JDBC.isConnected()) {
error("no connection to db")
return "{\"query\" : \"nodbconn\"}"
}
val jdbc: JDBC = JDBC.getInstance()
when (params["action"]) {
"getCitynames" -> {
set = jdbc.executeQuery("select * from cities")

View File

@ -3,6 +3,7 @@ package com.wasteinformationserver.website.datarequests.login
import com.wasteinformationserver.basicutils.Log.Log.debug
import com.wasteinformationserver.basicutils.Log.Log.error
import com.wasteinformationserver.basicutils.Log.Log.message
import com.wasteinformationserver.basicutils.Storage
import com.wasteinformationserver.db.JDBC
import com.wasteinformationserver.website.HttpTools.Companion.stringToMD5
import com.wasteinformationserver.website.basicrequest.PostRequest
@ -11,9 +12,11 @@ import java.sql.SQLException
import java.util.*
/**
* request handler of new login request of user
* request handler of new user login requests
* - checks the truth of username and password
* - replies right error messages or the success login
*
* @author Lukas Heiligenbrunner
*/
class LoginRequest : PostRequest() {
override fun request(params: HashMap<String, String>): String {
@ -22,18 +25,25 @@ class LoginRequest : PostRequest() {
val username = params["username"]
val jdbc: JDBC = try {
JDBC.getInstance()
} catch (e: IOException) {
error("no connection to db")
} catch (e: Exception) {
error("no connection to db" + e.printStackTrace())
return "{\"status\" : \"nodbconn\"}"
}
if (!Storage.getInstance().isEveryThingDefined()) {
error("config not configured correctly")
return "{\"status\" : \"conferror\"}"
}
val s = jdbc.executeQuery("select * from user where username ='$username'")
debug("successfully logged in to db")
var response = "{\"accept\": false}"
try {
s.last()
if (s.row == 1) { //success
if (stringToMD5(password!!) == s.getString("password")) {
if (s.row == 1) {
//success
if (StringToMD5(password!!) == s.getString("password")) {
debug("login success")
LoginState.getObject().logIn()
LoginState.getObject().setAccountData(username, s.getString("firstName"), s.getString("secondName"), s.getString("email"), s.getInt("permission"))
@ -42,9 +52,13 @@ class LoginRequest : PostRequest() {
else {
debug("wrong password")
}
} else if (s.row == 0) { //user not found
}
else if (s.row == 0) {
//user not found
debug("user not found")
} else { //internal error two users with same name...?
}
else {
//internal error two users with same name...?
error("there seem to be two users with same name")
}
debug("rowcount: " + s.row)

View File

@ -2,43 +2,37 @@ $(document).ready(function () {
$('#loginbtn').click(function (e) {
e.preventDefault();
console.log("clicked login button");
var username = $("#userfield")[0].value;
var password = $("#passfield")[0].value;
const username = $("#userfield")[0].value;
const password = $("#passfield")[0].value;
$.post('/senddata/loginget', 'username=' + username + '&password=' + password, function (data) {
console.log(data);
if (data.status == "nodbconn"){
Swal.fire({
icon: "error",
title: 'No connection to Database',
html: 'Setup DB here --> <a href="index.html">click<a/>.',
}).then((result) => {
console.log('Popup closed. ')
});
}
if (data.accept == true) {
console.log("successfully logged in!");
document.cookie = "username=" + username;
window.location = 'dashboard.html';
} else {
if (data.status == "nodbconn") {
Swal.fire({
icon: "error",
title: 'No connection to Database',
html: 'Setup DB in config file!.',
});
} else if (data.status == "conferror") {
Swal.fire({
icon: "error",
title: 'Not configured correctly',
html: 'Please edit settings.prop and restart the server!',
});
} else {
Swal.fire({
icon: "error",
title: 'Wrong login data',
html: 'Maybe a typo in your password?',
});
}
}
}, 'json');
});
//register pwa
async function registerSW() {
console.log("registering service worker!");
if ('serviceWorker' in navigator) {
try {
await navigator.serviceWorker.register('/sw.js');
} catch (e) {
console.log(`SW registration failed`);
}
}
}
registerSW();
});