- added new measvalue submit api

- started to implement login
This commit is contained in:
dorian 2019-07-29 00:24:01 +02:00
parent f94a2d0585
commit f8d113f3bf
10 changed files with 490 additions and 36 deletions

View file

@ -81,11 +81,11 @@ triggered by setting GET parameter 'locId' to a vaild location id
- added
- userid
- sensorname
- property ('indoor' || 'sunny' || 'shadow' )
- property ('indoor' || 'sunny' || 'shadow')
- valuetypeid
- valuetypes
- id
- valuetype ('temperature' || 'humidity')
- valuetype ('temperature' || 'humidity' || 'pressure' || 'fine dust')
- valueunit (html coding)
- displayproperty
- widget (properties for small widget)
@ -98,4 +98,26 @@ triggered by setting GET parameter 'locId' to a vaild location id
- from
- to
## submit sensor data
triggered by setting POST parameter 'submitSensorData' to a JSON encoded string containing the request
### Request
- identity: identity of the api token (given by webinterface)
- signature: SHA1 Hash of the JSON encoded string of 'data' rsa encrypted with the API Key as private key
- data: JSON array[array[
sensorId,
measvalue,
timestamp
]]
CAUTION!! This MUST be a string and NOT direct JSON!!
### Reply
- status:
- 200: was inserted
- 400: format of request was wrong
- 401: signture verify failed
- 404: key identity was not found
- 500: internal error
- 900: format of data JSON string was invalid
- 901: signature was fine but one or more sensors have been ignored due to some error (see 'data') all other sensors were processes successfully
- data: Array[Array[sensorId, errorCode]] sensors which were ignored due to some error (401: user doesn't own sensor; 404: senso wasn't found)
only set if status is 901

View file

@ -1,5 +1,4 @@
<?php
/**
* BlueWeather
*
@ -302,6 +301,197 @@ class BlueWeather
return $data;
}
// --------------------
// - setter functions -
// --------------------
/**
* Function to generate an api key for specific user
*
* @param int $userId userId
*
* @return bool
*/
function createApiKey($userId)
{
//generate random token
$length = 10;
$str = "";
$characters = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));
$max = count($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$rand = mt_rand(0, $max);
$str .= $characters[$rand];
}
$apiKey = password_hash($str, PASSWORD_DEFAULT);
$sql = "INSERT INTO `apikeys` (userid, apikey)
VALUES (\"$userId\", \"$apiKey\")";
return $this->_con->query($sql);
}
/**
* Function to validate and insert submited sensor data
*
* @param mixed $sensorData object containing
* - identity (int)
* - signature (string)
* - data (string: JSON array[array[sensorId,measvalue,timestamp]])
*
* @return array
* 'status': 200: was inserted
* 400: format of request was wrong
* 401: signture verify failed
* 404: key identity was not found
* 500: internal error
* 900: format of data JSON string was invalid
* 901: signature was fine but one or more sensors have been ignored due to some error (see 'data') all other sensors were processes successfully
* 'data': Array[Array[sensorId, errorCode]] sensors which were ignored due to some error (401: user doesn't own sensor; 404: senso wasn't found)
* only set if status is 901
*/
function processSensorData($sensorData)
{
// check if request structure is valid
if (!isset($sensorData['identity']) || !isset($sensorData['signature']) || !isset($sensorData['data'])) {
return array("status"=>400);
}
// get private key from database
$thisIdentity = $this->_con->real_escape_string($sensorData['identity']);
$thisData = $sensorData['data'];
// get public key of user
$sql = "SELECT * FROM `apikeys` WHERE id=$thisIdentity";
$result = $this->_con->query($sql);
if ($result->num_rows < 1) {
// public key was not found
return array("status"=>404);
}
// only one row will be returned
$data = $result->fetch_assoc();
$key = $data['apikey'];
$thisUserId = $data["userid"];
// check signature
$signedHash = hash_hmac("sha256", $thisData, $key);
if ($signedHash !== strtolower($sensorData['signature'])) {
return array("status"=>401);
}
// signature is valid
$measvalues = json_decode($thisData, true);
if (!$measvalues) {
// the format of the data JSON is invalid
return array("status"=>901, "data"=>"malformed data JSON");
}
$allSensors = array();
$validSensors = array();
$ignoredSensors = array();
// find all sensors
foreach ($measvalues as $measvalue) {
$thisSensorId = $this->_con->real_escape_string($measvalue[0]);
if (!in_array($thisSensorId, $allSensors)) {
array_push($allSensors, $thisSensorId);
}
}
// check if all sensors are valid and belong to the user
foreach ($allSensors as $sensor) {
// check if sensor belongs to user
$sql = "SELECT userid FROM `sensors` WHERE id=\"$sensor\"";
$result = $this->_con->query($sql);
if ($result->num_rows < 1) {
// sensor was not found
array_push($ignoredSensors, array($sensor, 404));
continue;
}
// only one row will be returned
$data = $result->fetch_assoc();
if ($data['userid'] !== $thisUserId) {
// sensor does not belong to user
array_push($ignoredSensors, array($sensor, 401));
continue;
}
array_push($validSensors, $sensor);
}
// iterate through all measvalues
// and insert them into the database if the sensor is valid
foreach ($measvalues as $measvalue) {
if (!in_array($measvalue[0], $validSensors)) {
// if the sensor is not valid -> continue
continue;
}
$thisSensorId = $this->_con->real_escape_string($measvalue[0]);
$thisMeasvalue = $this->_con->real_escape_string($measvalue[1]);
$thisTimestamp = $this->_con->real_escape_string($measvalue[2]);
$sql = "INSERT INTO `measvalues` (sensorid,measvalue,timestamp)
VALUES (\"$thisSensorId\", \"$thisMeasvalue\", \"$thisTimestamp\")";
$this->_con->query($sql);
}
if (count($ignoredSensors) > 0) {
return array("status"=>901, "data"=>$ignoredSensors);
}
return array("status"=>200);
}
// --------------------
// - Helper functions -
// --------------------
/**
* Function to convert a string to hex
*
* @param string $string the string to be converted
*
* @return string
*/
function strToHex($string)
{
$hex = '';
for ($i=0; $i<strlen($string); $i++) {
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);
}
/**
* Function to convert hex to string
*
* @param string $hex hex to be converted
*
* @return string
*/
function hexToStr($hex)
{
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2) {
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
}

View file

@ -24,12 +24,18 @@ header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$blueweather = new BlueWeather($config);
//$_POST['submitSensorData'] = '{"signature":"123", "identity":1, "data":"Hello World"}';
if (isset($_GET['locId'])) {
// get data of given location
$data = $blueweather->getLocationData(
$_GET['locId'], $_GET['range'], $_GET['maxVals']
);
} elseif (isset($_POST['submitSensorData'])) {
// sensor data is being submited
$sensorData = json_decode($_POST['submitSensorData'], true);
$ret = $blueweather->processSensorData($sensorData);
$data = $ret;
} else {
$data = $blueweather->getAllLocations();
}

View file

@ -0,0 +1,5 @@
{
"identity": 1,
"signature": "0AC7734264ADF2EC0633E37A635A52E6A4B4A588B27B4EA5AA172CF8BB9E762BFA442AFA1ED3B0F1479B580374AD7F28886362766972043E160B6FD02521440CC38845B3FEA45D17C7188B0BDF8C6E23F5E1BB4429D9EB405E2F944301844A000EFD5908D5BAA788918ED136132B7D406313D3C496EDD27514C1C0A2CF0525BCF7F14E70F2FE7A50CDD0E6385166E2FC86A1B6DE05F35634EE3CE73F478B002FB7F994912EB24A8CDFA7835B90C6B2EFDECCD1CEB5F309F165418AD1359D0A02948F85E935D8F527EDEC015E46520DE44F1775AF5CA87AA85FE90DEAD407D859CEE9B8D9E047CBC3E8A95D6216F58610E7A891F0AF9E16E6032D4E0D3E8F3BB0EE2A94F72AD4D05ED15919175A3F2031C14EA6F51B38961CBED14CE9472B9F22A7D89BA48255A2F9AFC3743E77E68C210F006EB1AB4FA75674897EFAFBF82B7D33F78D353EAD67B460CA5EB5FD552D58558CA481AA69880C5E1A6BE90180126E663496BDA5C92B2DE8060C3E353CEC56278F77D063ADB330229BEF875D2D80057A08926FBF61CDBD43DE1CA55B88297FC712F5C776D9D278C22399E84E33BC68E3B7A2F408D7A0C601559B6D53E9B4286E36F12A454041E6EAEA820B9BA456F0415A0FFA726803F9800C9D0FA9E24CFA9DB780758A132ACEAC229EC69577080C179B18344B4EB01709BF1EC209F70739D47ECC391874EC559E6CAE97F21A544F",
"data": "{\"1\": [ [15.0,1575863], [16.0,1575873] ], \"2\": [ [15.0,1575863], [16.0,1575873] ]}"
}

View file

@ -80,14 +80,6 @@ body {
* Navbar
*/
.navbar-brand {
padding-top: .75rem;
padding-bottom: .75rem;
font-size: 1rem;
background-color: rgba(0, 0, 0, .25);
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}
.navbar .form-control {
padding: .75rem 1rem;
border-width: 0;
@ -120,6 +112,10 @@ body {
}
}
.dropdown-toggle::after {
display:none;
}
/*
*
*/

View file

@ -26,20 +26,51 @@
</head>
<body style="height: 100%;">
<nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="index.html">BlueWeather</a>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark shadow">
<!-- left part of toolbar -->
<a class="navbar-brand" href="index.html">BlueWeather</a>
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="#">Sign out</a>
</li>
</ul>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false" style="padding: 0;">
<img class="img-profile rounded-circle" height="30" src="https://source.unsplash.com/QAB-WJcbgJk/60x60">
</a>
<!-- Dropdown - User Information -->
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
<a class="dropdown-item" href="#">
<span data-feather="user"></span>
Profile
</a>
<a class="dropdown-item" href="#">
<span data-feather="settings"></span>
Settings
</a>
<a class="dropdown-item" href="#">
<i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>
Activity Log
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
<span data-feather="log-out"></span>
Logout
</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="container-fluid" style="height: 100%">
<div class="row" style="height: 100%">
<!-- Nav bar on the right side -->
<nav class="col-md-2 d-none d-md-block bg-light sidebar">
<!-- Nav bar on the left side -->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" style="padding-top:0;">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
@ -70,7 +101,7 @@
</nav>
<!-- Main content area -->
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4" style="height: 90%">
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4" style="padding-top: 0; height: 90%">
<div
class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2" id="titleH1">Dashboard</h1>

View file

@ -9,9 +9,7 @@
<link rel="icon" href="img/favicon.ico" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/offcanvas/">
<link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="css/index.css" rel="stylesheet">
@ -39,9 +37,9 @@
<title>BlueWeather</title>
</head>
<body class="bg-ff">
<nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">BlueWeather</a>
<body class="bg-ff" style="height: 100%;padding-top: 0;">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark shadow">
<a class="navbar-brand" href="#">BlueWeather</a>
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">

View file

@ -6,8 +6,69 @@ class BlueWeather {
this.host = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
this.log("init done", 2)
this.session = {
loggedIn: false,
token: ""
}
this.restoreSession()
}
// ----------------------
// - session management -
// ----------------------
restoreSession() {
if(this.getCookie("session") !== "") {
// old session found
this.session.loggedIn = true
this.session.token = this.getCookie("session")
}
}
login(async, processingFunction, username, password) {
this.xhttp.abort()
var thisObject = this
if(async) {
this.xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
// Typical action to be performed when the document is ready:
if(this.status === 200) {
thisObject.log("login response was: " + this.responseText, 3)
var ret = JSON.parse(this.responseText)
if(ret && ret['status'] === 200) {
this.session.token = ret["token"]
this.session.loggedIn = true
processingFunction(true)
return
}
else {
this.session.token = ""
this.session.loggedIn = false
}
}
processingFunction(false)
}
}
}
var url = this.host + "/api/json.php"
this.log("starting location request; URL is: " + url, 3)
this.xhttp.open("GET", url, async)
this.xhttp.send()
}
endSession() {
document.cookie = "session=;"
window.location.href = "./index.html"
}
// --------------------
// - getter functions -
// --------------------
getLocations(async, processingFunction, errorFunction) {
this.xhttp.abort()
var thisObject = this
@ -32,7 +93,7 @@ class BlueWeather {
};
}
var url = "https://weather.itsblue.de/api/json.php"
var url = this.host + "/api/json.php"
this.log("starting location request; URL is: " + url, 3)
this.xhttp.open("GET", url, async)
this.xhttp.send()
@ -62,18 +123,12 @@ class BlueWeather {
};
}
var url = "https://weather.itsblue.de/api/json.php?locId="+locId+"&range[from]="+range.from + "&range[to]="+range.to + "&maxVals=" + maxVals
var url = this.host + "/api/json.php?locId="+locId+"&range[from]="+range.from + "&range[to]="+range.to + "&maxVals=" + maxVals
this.log("starting location request; URL is: " + url, 3)
this.xhttp.open("GET", url, async)
this.xhttp.send()
}
endSession() {
document.cookie = "session=;"
window.location.href = "./index.html"
}
// --------------------
// - helper functions -
// --------------------

View file

@ -347,7 +347,7 @@ class BlueWeatherDashboard {
data: [],
datasets: [
{
label: sensor.sensorname + " (" + valueType.valuetype + ")",
label: valueType.valuetype + " (" + valueType.valueunit.replace("&deg", "°") + ")",
yAxisID: 'yAxis',
showLine: true,
data: vals

151
loginmodal2.html Normal file
View file

@ -0,0 +1,151 @@
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.modal-login {
color: #636363;
width: 350px;
}
.modal-login .modal-content {
padding: 20px;
border-radius: 5px;
border: none;
}
.modal-login .modal-header {
border-bottom: none;
position: relative;
justify-content: center;
}
.modal-login h4 {
text-align: center;
font-size: 26px;
}
.modal-login .form-group {
position: relative;
}
.modal-login i {
position: absolute;
left: 13px;
top: 11px;
font-size: 18px;
}
.modal-login .form-control,
.modal-login .btn {
min-height: 40px;
border-radius: 3px;
transition: all 0.5s;
}
.modal-login .close {
position: absolute;
top: -5px;
right: -5px;
}
.modal-login .forgot-link {
color: #12b5e5;
float: right;
}
.modal-login .modal-footer {
color: #999;
border: none;
text-align: center;
border-radius: 5px;
font-size: 13px;
margin-top: -20px;
justify-content: center;
}
.modal-login .modal-footer a {
color: #12b5e5;
}
.trigger-btn {
display: inline-block;
margin: 100px auto;
}
</style>
</head>
<body>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-login" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body text-center">
<form class="form-signin">
<fieldset>
<img class="mb-4" src="img/icon.png" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<div class="form-group input-group">
<div class="input-group-prepend">
<div class="input-group-text"><span data-feather="user"></span></div>
</div>
<input type="text" class="form-control" id="inlineFormInputGroupUsername"
placeholder="Username">
</div>
<div class="form-group input-group">
<div class="input-group-prepend">
<div class="input-group-text"><span data-feather="lock"></span></div>
</div>
<input type="password" class="form-control" id="inlineFormInputGroupUsername"
placeholder="Password">
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<script src="js/feather.js"></script>
<script>
feather.replace()
</script>
</body>
</html>