web-base/core/Api/User/Login.class.php

80 lines
2.2 KiB
PHP
Raw Normal View History

2020-02-10 00:52:25 +01:00
<?php
2020-04-02 21:19:06 +02:00
namespace Api\User;
2020-02-10 00:52:25 +01:00
2020-04-02 21:19:06 +02:00
use \Api\Request;
use \Api\Parameter\Parameter;
use \Api\Parameter\StringType;
use \Driver\SQL\Condition\Compare;
2020-02-10 00:52:25 +01:00
class Login extends Request {
2020-04-03 15:56:04 +02:00
private int $startedAt;
2020-02-10 00:52:25 +01:00
2020-04-03 15:56:04 +02:00
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
2020-02-10 00:52:25 +01:00
'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;
}
2020-04-03 15:56:04 +02:00
}