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

81 lines
2.3 KiB
PHP
Raw Normal View History

2020-06-17 14:30:37 +02:00
<?php
namespace Api\User;
use Api\Parameter\StringType;
use \Api\Request;
2020-06-17 19:32:30 +02:00
use Driver\SQL\Condition\Compare;
2020-06-17 14:30:37 +02:00
class Create extends Request {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
'username' => new StringType('username', 32),
'email' => new StringType('email', 64, true),
'password' => new StringType('password'),
'confirmPassword' => new StringType('confirmPassword'),
));
$this->csrfTokenRequired = true;
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
}
public function execute($values = array()) {
2020-06-17 20:20:31 +02:00
if (!parent::execute($values)) {
2020-06-17 14:30:37 +02:00
return false;
}
2020-06-17 19:32:30 +02:00
$username = $this->getParam('username');
$email = $this->getParam('email');
2020-06-17 20:20:31 +02:00
if (!$this->userExists($username, $email) || !$this->success) {
return false;
2020-06-17 19:32:30 +02:00
}
$password = $this->getParam('password');
$confirmPassword = $this->getParam('confirmPassword');
2020-06-17 20:20:31 +02:00
if ($password !== $confirmPassword) {
return false;
2020-06-17 19:32:30 +02:00
}
$this->success = $this->createUser($username, $email, $password);
2020-06-17 14:30:37 +02:00
return $this->success;
}
2020-06-17 19:32:30 +02:00
2020-06-17 20:20:31 +02:00
private function userExists($username, $email) {
$sql = $this->user->getSQL();
$res = $sql->select("User.name", "User.email")
->from("User")
->where(new Compare("User.name", $username), new Compare("User.email", $email))
->execute();
$this->success = ($res !== FALSE);
$this->lastError = $sql->getLastError();
if (!empty($res)) {
$row = $res[0];
if (strcasecmp($username, $row['name']) === 0) {
$this->lastError = "This username is already in use.";
$this->success = false;
} else if (strcasecmp($username, $row['email']) === 0) {
$this->lastError = "This email address is already taken";
$this->success = false;
2020-06-17 20:06:36 +02:00
}
2020-06-17 20:20:31 +02:00
}
2020-06-17 20:06:36 +02:00
2020-06-17 20:20:31 +02:00
return $this->success;
2020-06-17 19:32:30 +02:00
}
2020-06-17 20:20:31 +02:00
private function createUser($username, $email, $password) {
$sql = $this->user->getSQL();
$salt = generateRandomString(16);
$hash = hash('sha256', $password . $salt);
$res = $sql->insert("User", array(
'username' => $username,
'password' => $hash,
'salt' => $salt,
'email' => $email
))->execute();
$this->lastError = $sql->getLastError();
return $res === TRUE;
2020-06-17 19:32:30 +02:00
}
2020-06-17 14:30:37 +02:00
}