2020-02-10 00:52:25 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Api;
|
|
|
|
|
|
|
|
use Api\Parameter\Parameter;
|
|
|
|
use Api\Parameter\StringType;
|
2020-04-02 00:02:51 +02:00
|
|
|
use Driver\SQL\Condition\Compare;
|
2020-02-10 00:52:25 +01:00
|
|
|
|
|
|
|
class Login extends Request {
|
|
|
|
|
|
|
|
private $startedAt;
|
|
|
|
|
|
|
|
public function __construct($user, $externCall = false) {
|
|
|
|
parent::__construct($user, $externCall, array(
|
|
|
|
'username' => new StringType('username', 32),
|
|
|
|
'password' => new StringType('password'),
|
2020-02-17 00:18:37 +01:00
|
|
|
'stayLoggedIn' => new Parameter('stayLoggedIn', Parameter::TYPE_BOOLEAN, true, true)
|
2020-02-10 00:52:25 +01:00
|
|
|
));
|
|
|
|
$this->forbidMethod("GET");
|
|
|
|
}
|
|
|
|
|
|
|
|
private function wrongCredentials() {
|
|
|
|
$runtime = microtime(true) - $this->startedAt;
|
|
|
|
$sleepTime = round(3e6 - $runtime);
|
|
|
|
if($sleepTime > 0) usleep($sleepTime);
|
|
|
|
return $this->createError(L('Wrong username or password'));
|
|
|
|
}
|
|
|
|
|
|
|
|
public function execute($values = array()) {
|
|
|
|
if(!parent::execute($values)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if($this->user->isLoggedIn()) {
|
|
|
|
$this->lastError = L('You are already logged in');
|
|
|
|
$this->success = true;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->startedAt = microtime(true);
|
|
|
|
$this->success = false;
|
|
|
|
$username = $this->getParam('username');
|
|
|
|
$password = $this->getParam('password');
|
2020-02-17 00:18:37 +01:00
|
|
|
$stayLoggedIn = $this->getParam('stayLoggedIn');
|
2020-02-10 00:52:25 +01:00
|
|
|
|
2020-04-02 00:02:51 +02:00
|
|
|
$sql = $this->user->getSQL();
|
|
|
|
$res = $sql->select("User.uid", "User.password", "User.salt")
|
|
|
|
->from("User")
|
|
|
|
->where(new Compare("User.name", $username))
|
|
|
|
->execute();
|
|
|
|
|
|
|
|
$this->success = ($res !== FALSE);
|
|
|
|
$this->lastError = $sql->getLastError();
|
2020-02-10 00:52:25 +01:00
|
|
|
|
|
|
|
if($this->success) {
|
2020-04-02 00:02:51 +02:00
|
|
|
if(count($res) === 0) {
|
2020-02-10 00:52:25 +01:00
|
|
|
return $this->wrongCredentials();
|
|
|
|
} else {
|
2020-04-02 00:02:51 +02:00
|
|
|
$row = $res[0];
|
2020-02-10 00:52:25 +01:00
|
|
|
$salt = $row['salt'];
|
|
|
|
$uid = $row['uid'];
|
|
|
|
$hash = hash('sha256', $password . $salt);
|
|
|
|
if($hash === $row['password']) {
|
2020-04-02 00:02:51 +02:00
|
|
|
if(!($this->success = $this->user->createSession($uid, $stayLoggedIn))) {
|
|
|
|
return $this->createError("Error creating Session: " . $sql->getLastError());
|
|
|
|
} else {
|
|
|
|
$this->result['logoutIn'] = $this->user->getSession()->getExpiresSeconds();
|
|
|
|
$this->success = true;
|
|
|
|
}
|
2020-02-10 00:52:25 +01:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
return $this->wrongCredentials();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->success;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
?>
|