Files
GEOVizor_PHP/android/users/index.php
2023-11-07 19:51:49 +06:00

189 lines
6.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once("../../monitoring/config.php");
//require_once("../../monitoring/tools.php");
require_once("../../resources/metadata/include/tools.php");
require_once("../createTerminalAndObject.php");
session_start();
function sendError($msg)
{
$obj = new StdClass();
$obj->errorCode = 1;
$obj->errorMessage = $msg;
$obj->data = array();
header('Content-Type: application/json');
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($obj);
exit();
}
//Отвечаю только на POST запросы
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
sendError("Request is GET method!");
}
$fn=filter_input(INPUT_GET, 'fn', FILTER_VALIDATE_INT, array('options'=>array('default'=>-1)));
if(isset($_GET['lng'])) $_SESSION["LNG"]=$_GET['lng']; else $_SESSION["LNG"]=2;//'en';
if($fn==0) { //Авторизация пользователя
$object = json_decode(file_get_contents("php://input"));
if ($object == null) {
sendError("Request is empty!");
}
$db = connectToDB();
$sql = "
select
id,
cast(del as integer) as del,
seq,
main.getcompanyid(id) company_id,
name,
surname,
patronymic,
email,
login,
password,
hash
from
main._users
where
del=false and (email='" . $object->login . "' or phone='" . $object->login . "' or login='" . $object->login . "') and (password='" . $object->password . "' or hash = '" . $object->password . "')
order by seq";
try {
$res = $db->query($sql);
} catch (Exception $ex) {
sendError($ex->getMessage());
}
$obj = new StdClass();
$obj->errorCode = 0;
$obj->errorMessage = "";
$obj->data = array();
if ($row = $res->fetch(PDO::FETCH_ASSOC)) {
$usr = new stdClass();
$usr->id = $row['id'];
$usr->del = $row['del'];
$usr->seq = $row['seq'];
$usr->company_id = $row['company_id'];
$usr->name = $row['name'];
$usr->surname = $row['surname'];
$usr->patronymic = $row['patronymic'];
$usr->email = $row['email'];
$usr->login = $row['login'];
$usr->password = $row['password'];
$usr->hash = $row['hash']; //Временный пароль (TODO должен быть в паре с id сесии для разделения устройств)
array_push($obj->data, $usr);
//Проверяем есть ли терминал и объект у пользователя если нет то создаём
createTerminalAndObject($usr->id,$object->android_id);
}
echo json_encode($obj);
}else
if ($fn==1) //Регистрация пользователя скопировал содержимое из основного приложения
{
$object = json_decode(file_get_contents("php://input"));
if ($object == null) {
sendError("Request is empty!");
}
$db = connectToDB();
$password = getPassword(5);
$sql = "select * from main.p__users_1(1,null,:company_name,:surname,:name,:position,:phone,:email,:password);";
$stmt = $db->prepare($sql);
$stmt->bindParam(':company_name', $object->firstname, PDO::PARAM_STR);
$stmt->bindParam(':surname', $object->lastname, PDO::PARAM_STR);
$stmt->bindParam(':name', $object->firstname, PDO::PARAM_STR);
$stmt->bindParam(':position', $object->position, PDO::PARAM_STR);
$stmt->bindParam(':phone', $object->phone, PDO::PARAM_STR);
$stmt->bindParam(':email', $object->email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$response = new stdClass();
$response->errorCode = '0';
$response->errorMessage = '';
try
{
$res = $stmt->execute();
} catch (Exception $ex)
{
if($ex->getCode()=='U1000')
{
sendError(trt('User_with_this_email_already_exists'));
}else {
sendError($ex->getMessage());
}
}
$response->data = array();
$usr = new stdClass();
$usr->id = '-1';
if($row = $stmt->fetch(PDO::FETCH_NUM))
{
$usr->id=$row[0];
$usr->del = 0; //SQLIte нет false
$usr->seq = 1;
$usr->company_id = ''; //Заполню ниже
$usr->name = $object->firstname;
$usr->surname = $object->lastname;
$usr->patronymic = '';
$usr->email = $object->email;
$usr->phone = $object->phone;
$usr->login = '';
$usr->password = ''; //Пароль не отправляю а использую временный идентификатор
$usr->hash = md5(uniqid(rand(), true));
//Обновляю идентификатор временного пароля для авторизации без ввода пароля
try {
$db->query("update main._users set hash='".$usr->hash."' where id=".$usr->id); //TODO сделать в одной функции p__users_1 что выше
} catch (Exception $e){
sendError($e->getMessage());
}
}
$stmt=null;
//Получаю id компании
try {
$res = $db->query("select company_id from main._users where id =".$usr->id);
} catch (Exception $e){
sendError($e->getMessage());
}
if($res->rowCount()>0) {
$row = $res->fetch(PDO::FETCH_ASSOC);
$usr->company_id = $row['company_id'];
}
array_push($response->data, $usr);
if($_SESSION["LNG"]==1){
$html='<html><head><title>Сообщение</title></head><body>
<h3>Поздравляю, вы зарегистрированы!</h3>
<b>Ваш пароль: </b> '.$password.'<br>
</body></html>';
}else{
$html='<html><head><title>Message</title></head><body>
<h3>Congratulations, you are registered!</h3>
<b>Your password: </b> '.$password.'<br>
</body></html>';
}
//Отсылаю пароль на почту
if(mail($usr->email,'Motion-Engine.com',$html,"Content-type: text/html; charset=utf-8\r\nFrom: GEOVizor Site <info@geovizor.com>"))
{
}else{
sendError('Failed to send password email to!');
}
echo json_encode($response);
exit();
}