OTA improvements

This commit is contained in:
JonatanRek 2019-10-30 15:18:29 +01:00
parent 2200508fff
commit df71f7c780
8 changed files with 294 additions and 109 deletions

View File

@ -172,7 +172,7 @@ if ($values != null || $values != "") {
];
break;
}
if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
if ($notificationData != []) {
$subscribers = $notificationMng::getSubscription();
foreach ($subscribers as $key => $subscriber) {

View File

@ -3,8 +3,8 @@ class UserManager
{
public function getUsers () {
try {
$allRoom = Db::loadAll ("SELECT * FROM users");
return $allRoom;
$allUsers = Db::loadAll ("SELECT user_id, username, at_home, ota FROM users");
return $allUsers;
} catch(PDOException $error) {
echo $error->getMessage();
die();
@ -26,12 +26,12 @@ class UserManager
if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
if ($user['password'] == UserManager::getHashPassword($password)) {
if (isset($rememberMe) && $rememberMe == 'true') {
setcookie ("rememberMe", $this->setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), str_replace("login", "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])), $_SERVER['HTTP_HOST'], 1);
setcookie ("rememberMe", $this->setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
}
$_SESSION['user']['id'] = $user['user_id'];
$page = "./index.php";
$page = "";
if ($user["startPage"] == 1) {
$page = "./dashboard.php";
$page = "dashboard";
}
unset($_POST['login']);
return $page;
@ -62,9 +62,12 @@ class UserManager
}
public function logout () {
setcookie ("rememberMe","", time() - (30 * 24 * 60 * 60 * 1000), str_replace("login", "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])), $_SERVER['HTTP_HOST'], 1);
unset($_SESSION['user']);
session_destroy();
if (isset($_COOKIE['rememberMe'])){
unset($_COOKIE['rememberMe']);
setcookie("rememberMe", 'false', time(), BASEDIR, $_SERVER['HTTP_HOST']);
}
}
public function setEncryptedCookie($value){
@ -98,13 +101,15 @@ class UserManager
return false;
}
public static function getUserData ($type) {
public static function getUserData ($type, $userId = '') {
if (isset($_SESSION['user']['id'])) {
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($_SESSION['user']['id']));
return $user[$type];
}
$userId = $_SESSION['user']['id'];
} else {
return "";
}
$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
return $user[$type];
}
public function setUserData ($type, $value) {
if (isset ($_SESSION['user']['id'])) {
@ -118,56 +123,6 @@ class UserManager
return $hashPassword;
}
public function ulozitObrazek ($file, $path = "", $name = "") {
if (!@is_array (getimagesize($file['tmp_name']))) {
throw new ChybaUzivatele("Formát obrázku ". $file['name'] ." není podporován!");
} else {
$extension = strtolower(strrchr($file['name'], '.'));
switch ($extension) {
case '.jpg':
case '.jpeg':
$img = @imagecreatefromjpeg($file['tmp_name']);
break;
case '.gif':
$img = @imagecreatefromgif($file['tmp_name']);
break;
case '.png':
$img2 = @imagecreatefrompng($file['tmp_name']);
break;
case '.ico':
$img3 = @$file['tmp_name'];
break;
default:
$img = false;
break;
}
if($name == ""){
$nazev = substr($file['name'], 0, strpos($file['name'], ".")) ."_". round(microtime(true) * 1000);
}else{
$nazev = $name;
}
if(!file_exists($path)){
mkdir($path, 0777, true);
}
if (@$img) {
if (!imagejpeg ($img, $path . $nazev .".jpg", 95)) {
throw new ChybaUzivatele ("Obrázek neuložen!");
}
imagedestroy ($img);
} else if (@$img2) {
if (!imagepng ($img2, $path . $nazev .".jpg")) {
throw new ChybaUzivatele ("Obrázek neuložen!");
}
imagedestroy ($img2);
} else if (@$img3) {
if (!copy($img3, $path . $nazev .'.ico')) {
throw new ChybaUzivatele ("Obrázek neuložen!");
}
}
return array('success' => true, 'url' => $path . $nazev .".jpg");
}
}
public function atHome($userId, $atHome){
try {
Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
@ -176,5 +131,51 @@ class UserManager
die();
}
}
public function changePassword($oldPassword, $newPassword, $newPassword2){
if ($newPassword == $newPassword2) {
//Password Criteria
$oldPasswordSaved = self::getUserData('password');
if (self::getHashPassword($oldPassword) == $oldPasswordSaved) {
self::setUserData('password', self::getHashPassword($newPassword));
} else {
throw new Exception ("old password did not match");
}
} else {
throw new Exception ("new password arent same");
}
}
public function createUser($userName, $password){
$userId = Db::loadOne('SELECT * FROM users WHERE username = ?;', array($userName))['user_id'];
if ($userId != null) {
return false;
};
try {
$user = [
'username' => $userName,
'password' => self::getHashPassword($password),
];
return Db::add ('users', $user);
} catch(PDOException $error) {
echo $error->getMessage();
die();
}
}
public function haveOtaEnabled($userName){
$ota = $this->getUser($userName)['ota'];
if ($ota != ''){
return ($ota != '' ? $ota : false);
} else {
return false;
}
}
public function setOta($code, $secret){
$userId = $_SESSION['user']['id'];
Db::edit ('users', ['ota' => $secret], 'WHERE user_id = ?', array($userId));
}
}
?>

51
app/controls/login.php Normal file
View File

@ -0,0 +1,51 @@
<?php
global $userManager;
if (
isset($_POST['username']) &&
$_POST['username'] != '' &&
isset($_POST['password']) &&
$_POST['password'] != ''
){
$ota = false;
$userName = $_POST['username'];
$userPassword = $_POST['password'];
$rememberMe = (isset ($_POST['remember']) ? $_POST['remember'] : "");
$ota = $userManager->haveOtaEnabled($userName);
if ($ota == "") {
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
header('Location: ' . BASEDIR . $landingPage);
die();
}
$_SESSION['USERNAME'] = $userName;
$_SESSION['PASSWORD'] = $userPassword;
$_SESSION['REMEMBER'] = $rememberMe;
$_SESSION['OTA'] = $ota;
} else if (
isset($_POST['otaCode']) &&
$_POST['otaCode'] != ''
) {
$otaCode = $_POST['otaCode'];
$otaSecret = $_POST['otaSecret'];
$ga = new PHPGangsta_GoogleAuthenticator();
$ota = $_SESSION['OTA'];
$userName = $_SESSION['USERNAME'];
$userPassword = $_SESSION['PASSWORD'];
$rememberMe = $_SESSION['REMEMBER'];
unset($_SESSION['OTA']);
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
header('Location: ' . BASEDIR . $landingPage);
echo 'OK';
} else {
echo 'FAILED';
}
//TODO: upravi a ověřit jeslti ja zabezpečené
//TODO:
die();
}

29
app/controls/setting.php Normal file
View File

@ -0,0 +1,29 @@
<?php
if (isset($_POST) && !empty($_POST)){
if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
$oldPassword = $_POST['oldPassword'];
$newPassword = $_POST['newPassword1'];
$newPassword2 = $_POST['newPassword2'];
UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
header('Location: ' . BASEDIR . 'logout');
die();
} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
$userName = $_POST['userName'];
$password = $_POST['userPassword'];
UserManager::createUser($userName, $password);
header('Location: ' . BASEDIR . 'setting');
die();
} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
echo $otaCode = $_POST['otaCode'];
echo $otaSecret = $_POST['otaSecret'];
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
UserManager::setOta($otaCode, $otaSecret);
}
header('Location: ' . BASEDIR . 'setting');
die();
}
}

View File

@ -62,14 +62,20 @@
<thead>
<tr>
<th><?php $LANGMNG->echo('t_time');?></th>
<?php if (DEBUGMOD) { ?>
<th><?php $LANGMNG->echo('t_raw');?></th>
<?php } ?>
<th><?php $LANGMNG->echo('t_state');?></th>
</tr>
</thead>
<tbody>
<?php foreach ($SUBDEVICE['events'] as $key => $value) { ?>
<tr>
<th><?php echo (new DateTime($value['time']))->format(DATEFORMAT); ?></th>
<th title="test"><?php echo $value['value'] . $SUBDEVICE['unit'];?></th>
<td><?php echo (new DateTime($value['time']))->format(DATEFORMAT); ?></td>
<?php if (DEBUGMOD) { ?>
<td><?php echo $SUBDEVICE['eventsRaw'][$key]['value']; ?></td>
<?php } ?>
<td title="test"><?php echo $value['value'] . $SUBDEVICE['unit'];?></td>
<?php //TODO: P5IDAT TOOLTIP PRO RAW VALUE?>
</tr>
<?php } ?>

View File

@ -56,15 +56,91 @@
<a href="rooms" class="button"><?php $LANGMNG->echo('b_rooms') ?></a>
</div>
</div>
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_changePassword') ?></h4>
<form method="post">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_oldPassword') ?>:</div>
<input type="password" class="input" name="oldPassword" value="" data-cip-id="cIPJQ342845639">
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_newPassword') ?>:</div>
<input type="password" class="input" name="newPassword1" value="">
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_newPassword') ?>:</div>
<input type="password" class="input" name="newPassword2" value="">
</div>
<div class="field">
<input type="submit" name="submitPasswordChange" class="button" value="Uložit">
</div>
</form>
</div>
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_ota') ?></h4>
<?php if (!empty($QRURL)) {?>
<img src="<?php echo $QRURL;?>" />
<?php echo $OTACODE; ?>
<form method="post" action="setting">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_gooleAutenticatorOtaCode') ?>:</div>
<input type="text" class="input" name="otaCode" value="" required>
<input type="hidden" class="input" name="otaSecret" value="<?php echo $OTASECRET;?>" required>
</div>
<div class="field">
<input type="submit" name="submitEnableOta" class="button" value="Uložit">
</div>
</form>
<?php } else {?>
<button name="deactivateOta" type="button" class="button is-danger fa"><?php $LANGMNG->echo('b_disable');?> <?php $LANGMNG->echo('b_ota'); ?></button>
<?php }?>
</div>
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_listUsers') ?></h4>
<table class="table is-fluid">
<thead>
<tr>
<th><?php $LANGMNG->echo('t_userName');?></th>
<th><?php $LANGMNG->echo('t_ota');?></th>
<th><?php $LANGMNG->echo('t_action');?></th>
</tr>
</thead>
<tbody>
<?php foreach ($USERS as $key => $user) { ?>
<tr>
<td><?php echo $user['username']; ?></td>
<td><?php echo ($user['ota'] ? '<span class="fa">&#xf00c;</span>' : ''); ?></td>
<td><button name="deleteUser" type="button" class="button is-danger fa">&#xf1f8;</button></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="col-12 col-sm-9 mx-auto mt-4">
<h4 class="mb-4"><?php $LANGMNG->echo('t_createuser') ?></h4>
<form method="post">
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_userName') ?>:</div>
<input type="text" class="input" name="userName" value="" data-cip-id="cIPJQ342845639">
</div>
<div class="field">
<div class="label"><?php $LANGMNG->echo('l_password') ?>:</div>
<input type="password" class="input" name="userPassword" value="" data-cip-id="cIPJQ342845639">
</div>
<div class="field">
<input type="submit" name="submitCreateUser" class="button" value="Uložit">
</div>
</form>
</div>
</div>
</div>
<script src="./app/templates/js/setting.js"></script>
<?php
$partial = new Partial('footer');
$partial->render();
?>
<script src="./app/templates/js/setting.js"></script>
</script>
</body>
</html>

View File

@ -22,10 +22,10 @@ class Home extends Template
$usersAtHome = '';
$i = 0;
foreach ($users as $user) {
$i++;
if ($user['at_home'] == 'true') {
$i++;
$usersAtHome .= $user['username'];
if ($usersAtHome != "" && isset($users[$i + 1])){
if ($usersAtHome != "" && isset($users[$i + 1]) && $users[$i + 1]['at_home'] == 'true'){
$usersAtHome .= ', ';
}
}
@ -44,6 +44,7 @@ class Home extends Template
foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
$events = RecordManager::getLastRecord($subDeviceData['subdevice_id'], 5);
$eventsRaw = $events;
$connectionError = true;
$parsedValue = "";
@ -103,6 +104,7 @@ class Home extends Template
$parsedValue = $replacementTrue;
}
//parsing last events values
foreach ($events as $key => $value) {
$events[$key]['value'] = $replacementFalse;
@ -127,6 +129,7 @@ class Home extends Template
$subDevices[$subDeviceData['subdevice_id']] = [
'events'=> $events,
'eventsRaw'=> $eventsRaw,
'type' => $subDeviceData['type'],
'unit' => $subDeviceData['unit'],
'comError' => $connectionError,

View File

@ -3,6 +3,7 @@ class Setting extends Template
{
function __construct()
{
global $userManager;
global $langMng;
@ -27,6 +28,24 @@ class Setting extends Template
$template->prepare('langMng', $langMng);
$template->prepare('automations', $automations);
$users = $userManager->getUsers();
$template->prepare('users', $users);
if ($userManager->getUserData('ota') == ''){
$ga = new PHPGangsta_GoogleAuthenticator();
$otaSecret = $ga->createSecret();
$qrCodeUrl = $ga->getQRCodeGoogleUrl('Smart Home', $otaSecret);
$oneCode = $ga->getCode($otaSecret);
$template->prepare('qrUrl', $qrCodeUrl);
$template->prepare('otaSecret', $otaSecret);
$template->prepare('otaCode', $oneCode);
// echo "Secret is: ".$secret."\n\n";
// echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n";
// echo "Checking Code '$oneCode' and Secret '$otaSecret':\n";
}
$template->render();
}
}