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

90 lines
2.5 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()) {
if(!parent::execute($values)) {
return false;
}
2020-06-17 19:32:30 +02:00
$username = $this->getParam('username');
$email = $this->getParam('email');
2020-06-17 20:06:36 +02:00
if(!$this->userExists($username, $email) || !$this->success) {
2020-06-17 19:32:30 +02:00
return false;
}
2020-06-17 20:06:36 +02:00
2020-06-17 19:32:30 +02:00
$password = $this->getParam('password');
$confirmPassword = $this->getParam('confirmPassword');
if($password !== $confirmPassword) {
return false;
}
$sql = $this->user->getSQL();
$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
private function userExists($username, $email){
$sql = $this->user->getSQL();
2020-06-17 20:06:36 +02:00
$res = $sql->select("User.name", "User.email")
2020-06-17 19:32:30 +02:00
->from("User")
->where(new Compare("User.name", $username), new Compare("User.email",$email))
->execute();
2020-06-17 20:06:36 +02:00
$this->success = ($res !== FALSE);
$this->lastError = $sql->getLastError();
if($res !== 0) {
$this->success = false;
$row = $res[0];
$message = "";
if (strcmp($username,row['name']) != 0 && strcmp($email, row['email']) != 0) {
$message = "Username and email are already taken";
}else if (strcmp($username,row['name']) != 0) {
$message = "Username is already taken";
}else{
$message = "Email is already taken";
}
$this->lastError = $message;
return true;
}
return false;
2020-06-17 19:32:30 +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,
'email' => $email
2020-06-17 20:06:36 +02:00
))->execute();
$this->lastError = $sql->getLastError();
2020-06-17 19:32:30 +02:00
return $res === TRUE;
}
2020-06-17 14:30:37 +02:00
}