PHP_SMART_HOME_V3/app/controllers/oauthController.php

90 lines
2.2 KiB
PHP
Raw Normal View History

2020-05-16 23:27:06 +00:00
<?php
2020-06-26 14:57:54 +00:00
$userManager = new UserManager();
2020-05-16 23:27:06 +00:00
if (
isset($_POST['username']) &&
$_POST['username'] != '' &&
isset($_POST['password']) &&
$_POST['password'] != ''
){
$ota = false;
$userName = $_POST['username'];
2020-06-26 14:57:54 +00:00
echo $_POST['username'];
2020-05-16 23:27:06 +00:00
$userPassword = $_POST['password'];
$state = $_POST["state"];
$clientId = $_POST["clientId"];
$ota = $userManager->haveOtaEnabled($userName);
2020-05-16 23:27:06 +00:00
if ($ota == "") {
$token = (new AuthManager)->getToken($userName,$userPassword, $clientId);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$get=[];
if ($_POST['response_type'] = 'code') {
$get = [
"state"=>$state,
"code"=>$token,
"state"=>$state,
];
} else {
$get = [
"access_token"=>$token,
"token_type"=>"Bearer",
"state"=>$state,
];
}
//Log
$logManager = new LogManager(__DIR__ . '/../../logs/auth/' . date("Y-m-d") . '.log');
$logManager->setLevel(LOGLEVEL);
$logManager->write("[OAUTH] Response " . $_POST["redirectUrl"] . '?' . http_build_query($get), LogRecordTypes::WARNING);
header('Location: ' . $_POST["redirectUrl"] . '?' . http_build_query($get));
2020-05-16 23:27:06 +00:00
die();
}
$_SESSION['USERNAME'] = $userName;
$_SESSION['PASSWORD'] = $userPassword;
$_SESSION['OTA'] = $ota;
$_SESSION['STATE'] = $state;
$_SESSION['REDIRECT'] = $_POST["redirectUrl"];
$_SESSION['CLIENT'] = $clientId;
} else if (
isset($_POST['otaCode']) &&
$_POST['otaCode'] != ''
) {
$otaCode = $_POST['otaCode'];
$otaSecret = $_POST['otaSecret'];
$userName = $_SESSION['USERNAME'];
$userPassword = $_SESSION['PASSWORD'];
$ota = $_SESSION['OTA'];
$oauthState = $_SESSION['STATE'];
$oauthRedirect = $_SESSION['REDIRECT'];
$oauthClientId = $_SESSION['CLIENT'];
$ga = new PHPGangsta_GoogleAuthenticator();
$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
$token = (new AuthManager)->getToken($userName,$userPassword, $oauthClientId);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$get = [
"access_token"=>$token,
"token_type"=>"Bearer",
"state"=>$oauthState,
];
header('Location: ' . $oauthRedirect . '#' . http_build_query($get));
echo 'OK';
} else {
echo 'FAILED';
}
die();
}