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

84 lines
2.7 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 21:39:46 +02:00
use Api\SendMail;
use DateTime;
2020-06-17 20:49:25 +02:00
use Driver\SQL\Condition\Compare;
2020-06-17 14:30:37 +02:00
class Invite extends Request {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
'username' => new StringType('username', 32),
'email' => new StringType('email', 64),
));
$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 20:49:25 +02:00
$username = $this->getParam('username');
$email = $this->getParam('email');
if (!$this->userExists($username, $email) || !$this->success) {
return false;
}
2020-06-17 20:50:39 +02:00
//add to DB
2020-06-17 20:49:25 +02:00
$token = generateRandomString(36);
$valid_until = (new DateTime())->modify("+48 hour");
$sql = $this->user->getSQL();
2020-06-17 21:39:46 +02:00
$res = $sql->insert("UserInvitation", array("username", "email", "token", "valid_until"))
->addRow($username, $email, $token, $valid_until)
2020-06-17 20:49:25 +02:00
->execute();
$this->success = ($res !== FALSE);
$this->lastError = $sql->getLastError();
2020-06-17 14:30:37 +02:00
2020-06-17 20:50:39 +02:00
//send validation mail
2020-06-17 20:49:25 +02:00
if($this->success) {
2020-06-17 21:39:46 +02:00
$request = new SendMail($this->user);
$link = "http://localhost/acceptInvitation?token=$token";
2020-06-17 20:49:25 +02:00
$this->success = $request->execute(array(
2020-06-17 21:39:46 +02:00
"from" => "webmaster@romanh.de",
"to" => $email,
"subject" => "Account Invitation for web-base@localhost",
"body" =>
"Hello,<br>
you were invited to create an account on web-base@localhost. Click on the following link to confirm the registration, it is 48h valid from now.
If the invitation was not intended, you can simply ignore this email.<br><br><a href=\"$link\">$link</a>"
)
);
2020-06-17 20:49:25 +02:00
$this->lastError = $request->getLastError();
}
2020-06-17 14:30:37 +02:00
return $this->success;
}
2020-06-17 20:49:25 +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 ($this->success && !empty($res)) {
$row = $res[0];
if (strcasecmp($username, $row['name']) === 0) {
return $this->createError("This username is already taken.");
} else if (strcasecmp($username, $row['email']) === 0) {
return $this->createError("This email address is already in use.");
}
}
return $this->success;
}
2020-06-17 14:30:37 +02:00
}