Core Update 1.4.0

This commit is contained in:
2022-02-20 16:53:26 +01:00
parent 918244125c
commit bd1f302433
86 changed files with 3301 additions and 41128 deletions

View File

@@ -32,6 +32,7 @@ namespace Api\ApiKey {
use Api\ApiKeyAPI;
use Api\Parameter\Parameter;
use Api\Request;
use DateTime;
use Driver\SQL\Condition\Compare;
use Exception;
@@ -64,12 +65,11 @@ namespace Api\ApiKey {
if ($this->success) {
$this->result["api_key"] = array(
"api_key" => $apiKey,
"valid_until" => $validUntil->getTimestamp(),
"valid_until" => $validUntil->format("Y-m-d H:i:s"),
"uid" => $sql->getLastInsertId(),
);
} else {
$this->result["api_key"] = null;
}
return $this->success;
}
}
@@ -77,7 +77,9 @@ namespace Api\ApiKey {
class Fetch extends ApiKeyAPI {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
parent::__construct($user, $externalCall, array(
"showActiveOnly" => new Parameter("showActiveOnly", Parameter::TYPE_BOOLEAN, true, true)
));
$this->loginRequired = true;
}
@@ -87,12 +89,16 @@ namespace Api\ApiKey {
}
$sql = $this->user->getSQL();
$res = $sql->select("uid", "api_key", "valid_until")
$query = $sql->select("uid", "api_key", "valid_until", "active")
->from("ApiKey")
->where(new Compare("user_id", $this->user->getId()))
->where(new Compare("valid_until", $sql->currentTimestamp(), ">"))
->where(new Compare("active", true))
->execute();
->where(new Compare("user_id", $this->user->getId()));
if ($this->getParam("showActiveOnly")) {
$query->where(new Compare("valid_until", $sql->currentTimestamp(), ">"))
->where(new Compare("active", true));
}
$res = $query->execute();
$this->success = ($res !== FALSE);
$this->lastError = $sql->getLastError();
@@ -100,16 +106,12 @@ namespace Api\ApiKey {
if($this->success) {
$this->result["api_keys"] = array();
foreach($res as $row) {
try {
$validUntil = (new DateTime($row["valid_until"]))->getTimestamp();
} catch (Exception $e) {
$validUntil = $row["valid_until"];
}
$this->result["api_keys"][] = array(
"uid" => intval($row["uid"]),
$apiKeyId = intval($row["uid"]);
$this->result["api_keys"][$apiKeyId] = array(
"id" => $apiKeyId,
"api_key" => $row["api_key"],
"valid_until" => $validUntil,
"valid_until" => $row["valid_until"],
"revoked" => !$sql->parseBool($row["active"])
);
}
}
@@ -146,7 +148,7 @@ namespace Api\ApiKey {
$this->lastError = $sql->getLastError();
if ($this->success) {
$this->result["valid_until"] = $validUntil->getTimestamp();
$this->result["valid_until"] = $validUntil;
}
return $this->success;
@@ -168,7 +170,7 @@ namespace Api\ApiKey {
}
$id = $this->getParam("id");
if(!$this->apiKeyExists($id))
if (!$this->apiKeyExists($id))
return false;
$sql = $this->user->getSQL();

View File

File diff suppressed because it is too large Load Diff

View File

@@ -25,6 +25,7 @@ namespace Api {
$connectionData = new ConnectionData($host, $port, $login, $password);
$connectionData->setProperty("from", $settings["mail_from"] ?? "");
$connectionData->setProperty("last_sync", $settings["mail_last_sync"] ?? "");
$connectionData->setProperty("mail_footer", $settings["mail_footer"] ?? "");
return $connectionData;
}
@@ -41,22 +42,20 @@ namespace Api\Mail {
use DateTimeInterface;
use Driver\SQL\Column\Column;
use Driver\SQL\Condition\Compare;
use Driver\SQL\Condition\CondBool;
use Driver\SQL\Condition\CondIn;
use Driver\SQL\Condition\CondNot;
use Driver\SQL\Expression\CurrentTimeStamp;
use Driver\SQL\Expression\JsonArrayAgg;
use Driver\SQL\Strategy\UpdateStrategy;
use External\PHPMailer\Exception;
use External\PHPMailer\PHPMailer;
use Objects\ConnectionData;
use Objects\GpgKey;
use Objects\User;
class Test extends MailAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
"receiver" => new Parameter("receiver", Parameter::TYPE_EMAIL)
"receiver" => new Parameter("receiver", Parameter::TYPE_EMAIL),
"gpgFingerprint" => new StringType("gpgFingerprint", 64, true, null)
));
}
@@ -70,7 +69,9 @@ namespace Api\Mail {
$this->success = $req->execute(array(
"to" => $receiver,
"subject" => "Test E-Mail",
"body" => "Hey! If you receive this e-mail, your mail configuration seems to be working."
"body" => "Hey! If you receive this e-mail, your mail configuration seems to be working.",
"gpgFingerprint" => $this->getParam("gpgFingerprint"),
"asnyc" => false
));
$this->lastError = $req->getLastError();
@@ -78,6 +79,7 @@ namespace Api\Mail {
}
}
// TODO: expired gpg keys?
class Send extends MailAPI {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
@@ -85,7 +87,9 @@ namespace Api\Mail {
'subject' => new StringType('subject', -1),
'body' => new StringType('body', -1),
'replyTo' => new Parameter('replyTo', Parameter::TYPE_EMAIL, true, null),
'replyName' => new StringType('replyName', 32, true, "")
'replyName' => new StringType('replyName', 32, true, ""),
"gpgFingerprint" => new StringType("gpgFingerprint", 64, true, null),
'async' => new Parameter("async", Parameter::TYPE_BOOLEAN, true, true)
));
$this->isPublic = false;
}
@@ -101,11 +105,24 @@ namespace Api\Mail {
}
$fromMail = $mailConfig->getProperty('from');
$mailFooter = $mailConfig->getProperty('mail_footer');
$toMail = $this->getParam('to') ?? $fromMail;
$subject = $this->getParam('subject');
$replyTo = $this->getParam('replyTo');
$replyName = $this->getParam('replyName');
$body = $this->getParam('body');
$gpgFingerprint = $this->getParam("gpgFingerprint");
if ($this->getParam("async")) {
$sql = $this->user->getSQL();
$this->success = $sql->insert("MailQueue", ["from", "to", "subject", "body",
"replyTo", "replyName", "gpgFingerprint"])
->addRow($fromMail, $toMail, $subject, $body, $replyTo, $replyName, $gpgFingerprint)
->execute() !== false;
$this->lastError = $sql->getLastError();
return $this->success;
}
if (stripos($body, "<body") === false) {
$body = "<body>$body</body>";
@@ -114,6 +131,14 @@ namespace Api\Mail {
$body = "<html>$body</html>";
}
if (!empty($mailFooter)) {
$email_signature = realpath(WEBROOT . DIRECTORY_SEPARATOR . $mailFooter);
if (is_file($email_signature)) {
$email_signature = file_get_contents($email_signature);
$body .= $email_signature;
}
}
try {
$mail = new PHPMailer;
$mail->IsSMTP();
@@ -129,12 +154,36 @@ namespace Api\Mail {
$mail->Host = $mailConfig->getHost();
$mail->Port = $mailConfig->getPort();
$mail->SMTPAuth = true;
$mail->Timeout = 15;
$mail->Username = $mailConfig->getLogin();
$mail->Password = $mailConfig->getPassword();
$mail->SMTPSecure = 'tls';
$mail->CharSet = 'UTF-8';
$mail->msgHTML($body);
$mail->AltBody = strip_tags($body);
if ($gpgFingerprint) {
$encryptedHeaders = implode("\r\n", [
"Date: " . (new \DateTime())->format(DateTimeInterface::RFC2822),
"Content-Type: text/html",
"Content-Transfer-Encoding: quoted-printable"
]);
$mimeBody = $encryptedHeaders . "\r\n\r\n" . quoted_printable_encode($body);
$res = GpgKey::encrypt($mimeBody, $gpgFingerprint);
if ($res["success"]) {
$encryptedBody = $res["data"];
$mail->AltBody = '';
$mail->Body = '';
$mail->AllowEmpty = true;
$mail->ContentType = PHPMailer::CONTENT_TYPE_MULTIPART_ENCRYPTED;
$mail->addStringAttachment("Version: 1", null, PHPMailer::ENCODING_BASE64, "application/pgp-encrypted", "");
$mail->addStringAttachment($encryptedBody, "encrypted.asc", PHPMailer::ENCODING_7BIT, "application/octet-stream", "");
} else {
return $this->createError($res["error"]);
}
} else {
$mail->msgHTML($body);
$mail->AltBody = strip_tags($body);
}
$this->success = @$mail->Send();
if (!$this->success) {
@@ -415,4 +464,101 @@ namespace Api\Mail {
return $this->success;
}
}
class SendQueue extends MailAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"debug" => new Parameter("debug", Parameter::TYPE_BOOLEAN, true, false)
]);
$this->isPublic = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$debug = $this->getParam("debug");
$startTime = time();
if ($debug) {
echo "Start of processing mail queue at $startTime" . PHP_EOL;
}
$sql = $this->user->getSQL();
$res = $sql->select("uid", "from", "to", "subject", "body",
"replyTo", "replyName", "gpgFingerprint", "retryCount")
->from("MailQueue")
->where(new Compare("retryCount", 0, ">"))
->where(new Compare("status", "waiting"))
->where(new Compare("nextTry", $sql->now(), "<="))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if ($this->success && is_array($res)) {
if ($debug) {
echo "Found " . count($res) . " mails to send" . PHP_EOL;
}
$successfulMails = [];
foreach ($res as $row) {
if (time() - $startTime >= 45) {
$this->lastError = "Not able to process whole mail queue within 45 seconds, will continue on next time";
break;
}
$to = $row["to"];
$subject = $row["subject"];
if ($debug) {
echo "Sending subject=$subject to=$to" . PHP_EOL;
}
$mailId = intval($row["uid"]);
$retryCount = intval($row["retryCount"]);
$req = new Send($this->user);
$args = [
"to" => $to,
"subject" => $subject,
"body" => $row["body"],
"replyTo" => $row["replyTo"],
"replyName" => $row["replyName"],
"gpgFingerprint" => $row["gpgFingerprint"],
"async" => false
];
$success = $req->execute($args);
$error = $req->getLastError();
if (!$success) {
$delay = [0, 720, 360, 60, 30, 1];
$minutes = $delay[max(0, min(count($delay) - 1, $retryCount))];
$nextTry = (new \DateTime())->modify("+$minutes minute");
$sql->update("MailQueue")
->set("retryCount", $retryCount - 1)
->set("status", "error")
->set("errorMessage", $error)
->set("nextTry", $nextTry)
->where(new Compare("uid", $mailId))
->execute();
} else {
$successfulMails[] = $mailId;
}
}
$this->success = count($successfulMails) === count($res);
if (!empty($successfulMails)) {
$res = $sql->update("MailQueue")
->set("status", "success")
->where(new CondIn(new Column("uid"), $successfulMails))
->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
}
}
return $this->success;
}
}
}

199
core/Api/NewsAPI.class.php Normal file
View File

@@ -0,0 +1,199 @@
<?php
namespace Api {
use Objects\User;
abstract class NewsAPI extends Request {
public function __construct(User $user, bool $externalCall = false, array $params = array()) {
parent::__construct($user, $externalCall, $params);
$this->loginRequired = true;
}
}
}
namespace Api\News {
use Api\NewsAPI;
use Api\Parameter\Parameter;
use Api\Parameter\StringType;
use Driver\SQL\Condition\Compare;
use Objects\User;
class Get extends NewsAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"since" => new Parameter("since", Parameter::TYPE_DATE_TIME, true, null),
"limit" => new Parameter("limit", Parameter::TYPE_INT, true, 10)
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$sql = $this->user->getSQL();
$query = $sql->select("News.uid", "title", "text", "publishedAt",
"User.uid as publisherId", "User.name as publisherName", "User.fullName as publisherFullName")
->from("News")
->innerJoin("User", "User.uid", "News.publishedBy")
->orderBy("publishedAt")
->descending();
$since = $this->getParam("since");
if ($since) {
$query->where(new Compare("publishedAt", $since, ">="));
}
$limit = $this->getParam("limit");
if ($limit < 1 || $limit > 30) {
return $this->createError("Limit must be in range 1-30");
} else {
$query->limit($limit);
}
$res = $query->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
if ($this->success) {
$this->result["news"] = [];
foreach ($res as $row) {
$newsId = intval($row["uid"]);
$this->result["news"][$newsId] = [
"id" => $newsId,
"title" => $row["title"],
"text" => $row["text"],
"publishedAt" => $row["publishedAt"],
"publisher" => [
"id" => intval($row["publisherId"]),
"name" => $row["publisherName"],
"fullName" => $row["publisherFullName"]
]
];
}
}
return $this->success;
}
}
class Publish extends NewsAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"title" => new StringType("title", 128),
"text" => new StringType("text", 1024)
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$sql = $this->user->getSQL();
$title = $this->getParam("title");
$text = $this->getParam("text");
$res = $sql->insert("News", ["title", "text"])
->addRow($title, $text)
->returning("uid")
->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
if ($this->success) {
$this->result["newsId"] = $sql->getLastInsertId();
}
return true;
}
}
class Delete extends NewsAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"id" => new Parameter("id", Parameter::TYPE_INT)
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$sql = $this->user->getSQL();
$id = $this->getParam("id");
$res = $sql->select("publishedBy")
->from("News")
->where(new Compare("uid", $id))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
} else if (empty($res) || !is_array($res)) {
return $this->createError("News Post not found");
} else if (intval($res[0]["publishedBy"]) !== $this->user->getId() && !$this->user->hasGroup(USER_GROUP_ADMIN)) {
return $this->createError("You do not have permissions to delete news post of other users.");
}
$res = $sql->delete("News")
->where(new Compare("uid", $id))
->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
return $this->success;
}
}
class Edit extends NewsAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"id" => new Parameter("id", Parameter::TYPE_INT),
"title" => new StringType("title", 128),
"text" => new StringType("text", 1024)
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$sql = $this->user->getSQL();
$id = $this->getParam("id");
$text = $this->getParam("text");
$title = $this->getParam("title");
$res = $sql->select("publishedBy")
->from("News")
->where(new Compare("uid", $id))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
} else if (empty($res) || !is_array($res)) {
return $this->createError("News Post not found");
} else if (intval($res[0]["publishedBy"]) !== $this->user->getId() && !$this->user->hasGroup(USER_GROUP_ADMIN)) {
return $this->createError("You do not have permissions to edit news post of other users.");
}
$res = $sql->update("News")
->set("title", $title)
->set("text", $text)
->where(new Compare("uid", $id))
->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
return $this->success;
}
}
}

View File

@@ -17,13 +17,19 @@ class Parameter {
// only internal access
const TYPE_RAW = 8;
// only json will work here i guess
// only json will work here I guess
// nope. also name[]=value
const TYPE_ARRAY = 9;
const TYPE_MIXED = 10;
const names = array('Integer', 'Float', 'Boolean', 'String', 'Date', 'Time', 'DateTime', 'E-Mail', 'Raw', 'Array', 'Mixed');
const DATE_FORMAT = "Y-m-d";
const TIME_FORMAT = "H:i:s";
const DATE_TIME_FORMAT = self::DATE_FORMAT . " " . self::TIME_FORMAT;
private $defaultValue;
public string $name;
public $value;
public bool $optional;
@@ -33,11 +39,44 @@ class Parameter {
public function __construct(string $name, int $type, bool $optional = FALSE, $defaultValue = NULL) {
$this->name = $name;
$this->optional = $optional;
$this->defaultValue = $defaultValue;
$this->value = $defaultValue;
$this->type = $type;
$this->typeName = $this->getTypeName();
}
public function reset() {
$this->value = $this->defaultValue;
}
public function getSwaggerTypeName(): string {
$typeName = strtolower(($this->type >= 0 && $this->type < count(Parameter::names)) ? Parameter::names[$this->type] : "invalid");
if ($typeName === "mixed" || $typeName === "raw") {
return "object";
}
if (!in_array($typeName, ["array", "boolean", "integer", "number", "object", "string"])) {
return "string";
}
return $typeName;
}
public function getSwaggerFormat(): ?string {
switch ($this->type) {
case self::TYPE_DATE:
return self::DATE_FORMAT;
case self::TYPE_TIME:
return self::TIME_FORMAT;
case self::TYPE_DATE_TIME:
return self::DATE_TIME_FORMAT;
case self::TYPE_EMAIL:
return "email";
default:
return null;
}
}
public function getTypeName(): string {
return ($this->type >= 0 && $this->type < count(Parameter::names)) ? Parameter::names[$this->type] : "INVALID";
}
@@ -65,11 +104,11 @@ class Parameter {
return Parameter::TYPE_BOOLEAN;
else if(is_a($value, 'DateTime'))
return Parameter::TYPE_DATE_TIME;
else if(($d = DateTime::createFromFormat('Y-m-d', $value)) && $d->format('Y-m-d') === $value)
else if(($d = DateTime::createFromFormat(self::DATE_FORMAT, $value)) && $d->format(self::DATE_FORMAT) === $value)
return Parameter::TYPE_DATE;
else if(($d = DateTime::createFromFormat('H:i:s', $value)) && $d->format('H:i:s') === $value)
else if(($d = DateTime::createFromFormat(self::TIME_FORMAT, $value)) && $d->format(self::TIME_FORMAT) === $value)
return Parameter::TYPE_TIME;
else if(($d = DateTime::createFromFormat('Y-m-d H:i:s', $value)) && $d->format('Y-m-d H:i:s') === $value)
else if(($d = DateTime::createFromFormat(self::DATE_TIME_FORMAT, $value)) && $d->format(self::DATE_TIME_FORMAT) === $value)
return Parameter::TYPE_DATE_TIME;
else if (filter_var($value, FILTER_VALIDATE_EMAIL))
return Parameter::TYPE_EMAIL;
@@ -110,8 +149,8 @@ class Parameter {
return true;
}
$d = DateTime::createFromFormat('Y-m-d', $value);
if($d && $d->format('Y-m-d') === $value) {
$d = DateTime::createFromFormat(self::DATE_FORMAT, $value);
if($d && $d->format(self::DATE_FORMAT) === $value) {
$this->value = $d;
return true;
}
@@ -123,8 +162,8 @@ class Parameter {
return true;
}
$d = DateTime::createFromFormat('H:i:s', $value);
if($d && $d->format('H:i:s') === $value) {
$d = DateTime::createFromFormat(self::TIME_FORMAT, $value);
if($d && $d->format(self::TIME_FORMAT) === $value) {
$this->value = $d;
return true;
}
@@ -135,8 +174,8 @@ class Parameter {
$this->value = $value;
return true;
} else {
$d = DateTime::createFromFormat('Y-m-d H:i:s', $value);
if($d && $d->format('Y-m-d H:i:s') === $value) {
$d = DateTime::createFromFormat(self::DATE_TIME_FORMAT, $value);
if($d && $d->format(self::DATE_TIME_FORMAT) === $value) {
$this->value = $d;
return true;
}

View File

@@ -2,7 +2,9 @@
namespace Api;
use Api\Parameter\Parameter;
use Objects\User;
use PhpMqtt\Client\MqttClient;
class Request {
@@ -45,6 +47,14 @@ class Request {
}
}
public function getDefaultParams(): array {
return $this->defaultParams;
}
public function isDisabled(): bool {
return $this->isDisabled;
}
protected function allowMethod($method) {
$availableMethods = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "TRACE", "CONNECT"];
if (in_array($method, $availableMethods) && !in_array($method, $this->allowedMethods)) {
@@ -70,6 +80,7 @@ class Request {
return $this->createError("Missing parameter: $name");
}
$param->reset();
if (!is_null($value) && !$isEmpty) {
if (!$param->parseParam($value)) {
$value = print_r($value, true);
@@ -97,6 +108,7 @@ class Request {
}
public function execute($values = array()): bool {
$this->params = array_merge([], $this->defaultParams);
$this->success = false;
$this->result = array();
@@ -165,6 +177,13 @@ class Request {
$this->lastError = 'You are not logged in.';
http_response_code(401);
return false;
} else if ($this->user->isLoggedIn()) {
$tfaToken = $this->user->getTwoFactorToken();
if ($tfaToken && $tfaToken->isConfirmed() && !$tfaToken->isAuthenticated()) {
$this->lastError = '2FA-Authorization is required';
http_response_code(401);
return false;
}
}
}
@@ -172,7 +191,8 @@ class Request {
if ($this->csrfTokenRequired && $this->user->isLoggedIn()) {
// csrf token required + external call
// if it's not a call with API_KEY, check for csrf_token
if (!isset($values["csrf_token"]) || strcmp($values["csrf_token"], $this->user->getSession()->getCsrfToken()) !== 0) {
$csrfToken = $values["csrf_token"] ?? $_SERVER["HTTP_XSRF_TOKEN"] ?? null;
if (!$csrfToken || strcmp($csrfToken, $this->user->getSession()->getCsrfToken()) !== 0) {
$this->lastError = "CSRF-Token mismatch";
http_response_code(403);
return false;
@@ -223,6 +243,10 @@ class Request {
return (isset($obj[$name]) ? $obj[$name]->value : NULL);
}
public function isMethodAllowed(string $method): bool {
return in_array($method, $this->allowedMethods);
}
public function isPublic(): bool {
return $this->isPublic;
}
@@ -268,6 +292,14 @@ class Request {
flush();
}
protected function disableCache() {
header("Last-Modified: " . (new \DateTime())->format("D, d M Y H:i:s T"));
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
}
protected function setupSSE() {
$this->user->getSQL()->close();
$this->user->sendCookies();
@@ -276,11 +308,33 @@ class Request {
header('Content-Type: text/event-stream');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');
header('Cache-Control: no-cache');
$this->disableCache();
$this->disableOutputBuffer();
}
/**
* @throws \PhpMqtt\Client\Exceptions\ProtocolViolationException
* @throws \PhpMqtt\Client\Exceptions\DataTransferException
* @throws \PhpMqtt\Client\Exceptions\MqttClientException
*/
protected function startMqttSSE(MqttClient $mqtt, callable $onPing) {
$lastPing = 0;
$mqtt->registerLoopEventHandler(function(MqttClient $mqtt, $elapsed) use (&$lastPing, $onPing) {
if ($elapsed - $lastPing >= 5) {
$onPing();
$lastPing = $elapsed;
}
if (connection_status() !== 0) {
$mqtt->interrupt();
}
});
$mqtt->loop();
$this->lastError = "MQTT Loop disconnected";
$mqtt->disconnect();
}
protected function processImageUpload(string $uploadDir, array $allowedExtensions = ["jpg","jpeg","png","gif"], $transformCallback = null) {
if (empty($_FILES)) {
return $this->createError("You need to upload an image.");

198
core/Api/Swagger.class.php Normal file
View File

@@ -0,0 +1,198 @@
<?php
namespace Api;
use Api\Parameter\StringType;
use Objects\User;
class Swagger extends Request {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, []);
$this->csrfTokenRequired = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
header("Content-Type: application/x-yaml");
header("Access-Control-Allow-Origin: *");
die($this->getDocumentation());
}
private function getApiEndpoints(): array {
// first load all direct classes
$classes = [];
$basePath = realpath(WEBROOT . "/core/Api/");
foreach (scandir($basePath) as $fileName) {
$fullPath = $basePath . "/" . $fileName;
if (is_file($fullPath) && endsWith($fileName, ".class.php")) {
require_once $fullPath;
$apiName = explode(".", $fileName)[0];
$className = "\\Api\\$apiName";
if (!class_exists($className)) {
var_dump("Class not exist: $className");
continue;
}
$reflection = new \ReflectionClass($className);
if (!$reflection->isSubclassOf(Request::class) || $reflection->isAbstract()) {
continue;
}
$endpoint = "/" . strtolower($apiName);
$classes[$endpoint] = $reflection;
}
}
// then load all inheriting classes
foreach (get_declared_classes() as $declaredClass) {
$reflectionClass = new \ReflectionClass($declaredClass);
if (!$reflectionClass->isAbstract() && $reflectionClass->isSubclassOf(Request::class)) {
$inheritingClass = $reflectionClass->getParentClass();
if ($inheritingClass->isAbstract() && endsWith($inheritingClass->getShortName(), "API")) {
$endpoint = strtolower(substr($inheritingClass->getShortName(), 0, -3));
$endpoint = "/$endpoint/" . lcfirst($reflectionClass->getShortName());
$classes[$endpoint] = $reflectionClass;
}
}
}
return $classes;
}
private function fetchPermissions(): array {
$req = new Permission\Fetch($this->user);
$this->success = $req->execute();
$permissions = [];
foreach( $req->getResult()["permissions"] as $permission) {
$permissions["/" . strtolower($permission["method"])] = $permission["groups"];
}
return $permissions;
}
private function canView(array $requiredGroups, Request $request): bool {
if (!$request->isPublic()) {
return false;
}
if (($request->loginRequired() || !empty($requiredGroups)) && !$this->user->isLoggedIn()) {
return false;
}
// special case: hardcoded permission
if ($request instanceof Permission\Save && (!$this->user->isLoggedIn() || !$this->user->hasGroup(USER_GROUP_ADMIN))) {
return false;
}
if (!empty($requiredGroups)) {
return !empty(array_intersect($requiredGroups, $this->user->getGroups()));
}
return true;
}
private function getDocumentation(): string {
$settings = $this->user->getConfiguration()->getSettings();
$siteName = $settings->getSiteName();
$domain = parse_url($settings->getBaseUrl(), PHP_URL_HOST);
$permissions = $this->fetchPermissions();
$definitions = [];
$paths = [];
foreach (self::getApiEndpoints() as $endpoint => $apiClass) {
$body = null;
$requiredProperties = [];
$apiObject = $apiClass->newInstance($this->user);
if (!$this->canView($permissions[strtolower($endpoint)] ?? [], $apiObject)) {
continue;
}
$parameters = $apiObject->getDefaultParams();
if (!empty($parameters)) {
$body = [];
foreach ($apiObject->getDefaultParams() as $param) {
$body[$param->name] = [
"type" => $param->getSwaggerTypeName(),
"default" => $param->value
];
if ($param instanceof StringType && $param->maxLength > 0) {
$body[$param->name]["maxLength"] = $param->maxLength;
}
if ($body[$param->name]["type"] === "string" && ($format = $param->getSwaggerFormat())) {
$body[$param->name]["format"] = $format;
}
if (!$param->optional) {
$requiredProperties[] = $param->name;
}
}
$bodyName = $apiClass->getShortName() . "Body";
$definitions[$bodyName] = [
"description" => "Body for $endpoint",
"properties" => $body
];
if (!empty($requiredProperties)) {
$definitions[$bodyName]["required"] = $requiredProperties;
}
}
$endPointDefinition = [
"post" => [
"produces" => ["application/json"],
"responses" => [
"200" => ["description" => ""],
"401" => ["description" => "Login or 2FA Authorization is required"],
]
]
];
if ($apiObject->isDisabled()) {
$endPointDefinition["post"]["deprecated"] = true;
}
if ($body) {
$endPointDefinition["post"]["consumes"] = ["application/json"];
$endPointDefinition["post"]["parameters"] = [[
"in" => "body",
"name" => "body",
"required" => !empty($requiredProperties),
"schema" => ["\$ref" => "#/definitions/" . $apiClass->getShortName() . "Body"]
]];
} else if ($apiObject->isMethodAllowed("GET")) {
$endPointDefinition["get"] = $endPointDefinition["post"];
unset($endPointDefinition["post"]);
}
$paths[$endpoint] = $endPointDefinition;
}
$yamlData = [
"swagger" => "2.0",
"info" => [
"description" => "This is the Backend API-Description of $siteName",
"version" => WEBBASE_VERSION,
"title" => $siteName,
"contact" => [ "email" => "webmaster@$domain" ],
],
"host" => $domain,
"basePath" => "/api",
"schemes" => ["https"],
"paths" => $paths,
"definitions" => $definitions
];
return yaml_emit($yamlData);
}
}

409
core/Api/TfaAPI.class.php Normal file
View File

@@ -0,0 +1,409 @@
<?php
namespace Api {
use Objects\TwoFactor\AuthenticationData;
use Objects\TwoFactor\KeyBasedTwoFactorToken;
use Objects\User;
abstract class TfaAPI extends Request {
private bool $userVerficiationRequired;
public function __construct(User $user, bool $externalCall = false, array $params = array()) {
parent::__construct($user, $externalCall, $params);
$this->loginRequired = true;
$this->userVerficiationRequired = false;
}
protected function verifyAuthData(AuthenticationData $authData): bool {
$settings = $this->user->getConfiguration()->getSettings();
// $relyingParty = $settings->getSiteName();
$domain = parse_url($settings->getBaseUrl(), PHP_URL_HOST);
// $domain = "localhost";
if (!$authData->verifyIntegrity($domain)) {
return $this->createError("mismatched rpIDHash. expected: " . hash("sha256", $domain) . " got: " . bin2hex($authData->getHash()));
} else if (!$authData->isUserPresent()) {
return $this->createError("No user present");
} else if ($this->userVerficiationRequired && !$authData->isUserVerified()) {
return $this->createError("user was not verified on device (PIN/Biometric/...)");
} else if ($authData->hasExtensionData()) {
return $this->createError("No extensions supported");
}
return true;
}
protected function verifyClientDataJSON($jsonData, KeyBasedTwoFactorToken $token): bool {
$settings = $this->user->getConfiguration()->getSettings();
$expectedType = $token->isConfirmed() ? "webauthn.get" : "webauthn.create";
$type = $jsonData["type"] ?? "null";
if ($type !== $expectedType) {
return $this->createError("Invalid client data json type. Expected: '$expectedType', Got: '$type'");
} else if ($token->getData() !== base64url_decode($jsonData["challenge"] ?? "")) {
return $this->createError("Challenge does not match");
} else if (($jsonData["origin"] ?? null) !== $settings->getBaseURL()) {
$baseUrl = $settings->getBaseURL();
return $this->createError("Origin does not match. Expected: '$baseUrl', Got: '${$jsonData["origin"]}'");
}
return true;
}
}
}
namespace Api\TFA {
use Api\Parameter\StringType;
use Api\TfaAPI;
use Driver\SQL\Condition\Compare;
use Objects\TwoFactor\AttestationObject;
use Objects\TwoFactor\AuthenticationData;
use Objects\TwoFactor\KeyBasedTwoFactorToken;
use Objects\TwoFactor\TimeBasedTwoFactorToken;
use Objects\User;
// General
class Remove extends TfaAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"password" => new StringType("password", 0, true)
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$token = $this->user->getTwoFactorToken();
if (!$token) {
return $this->createError("You do not have an active 2FA-Token");
}
$sql = $this->user->getSQL();
$password = $this->getParam("password");
if ($password) {
$res = $sql->select("password")
->from("User")
->where(new Compare("uid", $this->user->getId()))
->execute();
$this->success = !empty($res);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
} else if (!password_verify($password, $res[0]["password"])) {
return $this->createError("Wrong password");
}
} else if ($token->isConfirmed()) {
// if the token is fully confirmed, require a password to remove it
return $this->createError("Missing parameter: password");
}
$res = $sql->delete("2FA")
->where(new Compare("uid", $token->getId()))
->execute();
$this->success = $res !== false;
$this->lastError = $sql->getLastError();
if ($this->success && $token->isConfirmed()) {
// send an email
$settings = $this->user->getConfiguration()->getSettings();
$req = new \Api\Template\Render($this->user);
$this->success = $req->execute([
"file" => "mail/2fa_remove.twig",
"parameters" => [
"username" => $this->user->getFullName() ?? $this->user->getUsername(),
"site_name" => $settings->getSiteName(),
"sender_mail" => $settings->getMailSender()
]
]);
if ($this->success) {
$body = $req->getResult()["html"];
$gpg = $this->user->getGPG();
$req = new \Api\Mail\Send($this->user);
$this->success = $req->execute([
"to" => $this->user->getEmail(),
"subject" => "[Security Lab] 2FA-Authentication removed",
"body" => $body,
"gpgFingerprint" => $gpg ? $gpg->getFingerprint() : null
]);
}
$this->lastError = $req->getLastError();
}
return $this->success;
}
}
// TOTP
class GenerateQR extends TfaAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall);
$this->csrfTokenRequired = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$twoFactorToken = $this->user->getTwoFactorToken();
if ($twoFactorToken && $twoFactorToken->isConfirmed()) {
return $this->createError("You already added a two factor token");
} else if (!($twoFactorToken instanceof TimeBasedTwoFactorToken)) {
$twoFactorToken = new TimeBasedTwoFactorToken(generateRandomString(32, "base32"));
$sql = $this->user->getSQL();
$this->success = $sql->insert("2FA", ["type", "data"])
->addRow("totp", $twoFactorToken->getData())
->returning("uid")
->execute() !== false;
$this->lastError = $sql->getLastError();
if ($this->success) {
$this->success = $sql->update("User")
->set("2fa_id", $sql->getLastInsertId())->where(new Compare("uid", $this->user->getId()))
->execute() !== false;
$this->lastError = $sql->getLastError();
}
if (!$this->success) {
return false;
}
}
header("Content-Type: image/png");
$this->disableCache();
die($twoFactorToken->generateQRCode($this->user));
}
}
class ConfirmTotp extends VerifyTotp {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall);
$this->loginRequired = true;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$twoFactorToken = $this->user->getTwoFactorToken();
if ($twoFactorToken->isConfirmed()) {
return $this->createError("Your two factor token is already confirmed.");
}
$sql = $this->user->getSQL();
$this->success = $sql->update("2FA")
->set("confirmed", true)
->where(new Compare("uid", $twoFactorToken->getId()))
->execute() !== false;
$this->lastError = $sql->getLastError();
return $this->success;
}
}
class VerifyTotp extends TfaAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"code" => new StringType("code", 6)
]);
$this->loginRequired = false;
$this->csrfTokenRequired = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$session = $this->user->getSession();
if (!$session) {
return $this->createError("You are not logged in.");
}
$twoFactorToken = $this->user->getTwoFactorToken();
if (!$twoFactorToken) {
return $this->createError("You did not add a two factor token yet.");
} else if (!($twoFactorToken instanceof TimeBasedTwoFactorToken)) {
return $this->createError("Invalid 2FA-token endpoint");
}
$code = $this->getParam("code");
if (!$twoFactorToken->verify($code)) {
return $this->createError("Code does not match");
}
$twoFactorToken->authenticate();
return $this->success;
}
}
// Key
class RegisterKey extends TfaAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"clientDataJSON" => new StringType("clientDataJSON", 0, true, "{}"),
"attestationObject" => new StringType("attestationObject", 0, true, "")
]);
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$clientDataJSON = json_decode($this->getParam("clientDataJSON"), true);
$attestationObjectRaw = base64_decode($this->getParam("attestationObject"));
$twoFactorToken = $this->user->getTwoFactorToken();
$settings = $this->user->getConfiguration()->getSettings();
$relyingParty = $settings->getSiteName();
$sql = $this->user->getSQL();
// TODO: for react development, localhost / HTTP_HOST is required, otherwise a DOMException is thrown
$domain = parse_url($settings->getBaseUrl(), PHP_URL_HOST);
// $domain = "localhost";
if (!$clientDataJSON || !$attestationObjectRaw) {
if ($twoFactorToken) {
if (!($twoFactorToken instanceof KeyBasedTwoFactorToken) || $twoFactorToken->isConfirmed()) {
return $this->createError("You already added a two factor token");
} else {
$challenge = base64_encode($twoFactorToken->getData());
}
} else {
$challenge = base64_encode(generateRandomString(32, "raw"));
$res = $sql->insert("2FA", ["type", "data"])
->addRow("fido", $challenge)
->returning("uid")
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
$this->success = $sql->update("User")
->set("2fa_id", $sql->getLastInsertId())
->where(new Compare("uid", $this->user->getId()))
->execute() !== false;
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
}
$this->result["data"] = [
"challenge" => $challenge,
"id" => $this->user->getId() . "@" . $domain, // <userId>@<domain>
"relyingParty" => [
"name" => $relyingParty,
"id" => $domain
],
];
} else {
if ($twoFactorToken === null) {
return $this->createError("Request a registration first.");
} else if (!($twoFactorToken instanceof KeyBasedTwoFactorToken)) {
return $this->createError("You already got a 2FA token");
}
if (!$this->verifyClientDataJSON($clientDataJSON, $twoFactorToken)) {
return false;
}
$attestationObject = new AttestationObject($attestationObjectRaw);
$authData = $attestationObject->getAuthData();
if (!$this->verifyAuthData($authData)) {
return false;
}
$publicKey = $authData->getPublicKey();
if ($publicKey->getUsedAlgorithm() !== -7) {
return $this->createError("Unsupported key type. Expected: -7");
}
$data = [
"credentialID" => base64_encode($authData->getCredentialID()),
"publicKey" => $publicKey->jsonSerialize()
];
$this->success = $sql->update("2FA")
->set("data", json_encode($data))
->set("confirmed", true)
->where(new Compare("uid", $twoFactorToken->getId()))
->execute() !== false;
$this->lastError = $sql->getLastError();
}
return $this->success;
}
}
class VerifyKey extends TfaAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"credentialID" => new StringType("credentialID"),
"clientDataJSON" => new StringType("clientDataJSON"),
"authData" => new StringType("authData"),
"signature" => new StringType("signature"),
]);
$this->loginRequired = false;
$this->csrfTokenRequired = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$session = $this->user->getSession();
if (!$session) {
return $this->createError("You are not logged in.");
}
$twoFactorToken = $this->user->getTwoFactorToken();
if (!$twoFactorToken) {
return $this->createError("You did not add a two factor token yet.");
} else if (!($twoFactorToken instanceof KeyBasedTwoFactorToken)) {
return $this->createError("Invalid 2FA-token endpoint");
} else if (!$twoFactorToken->isConfirmed()) {
return $this->createError("2FA-Key not confirmed yet");
}
$credentialID = base64url_decode($this->getParam("credentialID"));
if ($credentialID !== $twoFactorToken->getCredentialId()) {
return $this->createError("credential ID does not match");
}
$jsonData = $this->getParam("clientDataJSON");
if (!$this->verifyClientDataJSON(json_decode($jsonData, true), $twoFactorToken)) {
return false;
}
$authDataRaw = base64_decode($this->getParam("authData"));
$authData = new AuthenticationData($authDataRaw);
if (!$this->verifyAuthData($authData)) {
return false;
}
$clientDataHash = hash("sha256", $jsonData, true);
$signature = base64_decode($this->getParam("signature"));
$this->success = $twoFactorToken->verify($signature, $authDataRaw . $clientDataHash);
if ($this->success) {
$twoFactorToken->authenticate();
} else {
$this->lastError = "Verification failed";
}
return $this->success;
}
}
}

View File

@@ -67,11 +67,11 @@ namespace Api {
$this->checkPasswordRequirements($password, $confirmPassword);
}
protected function insertUser($username, $email, $password, $confirmed) {
protected function insertUser($username, $email, $password, $confirmed, $fullName = null) {
$sql = $this->user->getSQL();
$hash = $this->hashPassword($password);
$res = $sql->insert("User", array("name", "password", "email", "confirmed"))
->addRow($username, $hash, $email, $confirmed)
$res = $sql->insert("User", array("name", "password", "email", "confirmed", "fullName"))
->addRow($username, $hash, $email, $confirmed, $fullName)
->returning("uid")
->execute();
@@ -93,10 +93,13 @@ namespace Api {
$sql = $this->user->getSQL();
$res = $sql->select("User.uid as userId", "User.name", "User.fullName", "User.email",
"User.registered_at", "User.confirmed", "User.last_online", "User.profilePicture",
"User.gpg_id", "GpgKey.confirmed as gpg_confirmed", "GpgKey.fingerprint as gpg_fingerprint",
"GpgKey.expires as gpg_expires", "GpgKey.algorithm as gpg_algorithm",
"Group.uid as groupId", "Group.name as groupName", "Group.color as groupColor")
->from("User")
->leftJoin("UserGroup", "User.uid", "UserGroup.user_id")
->leftJoin("Group", "Group.uid", "UserGroup.group_id")
->leftJoin("GpgKey", "GpgKey.uid", "User.gpg_id")
->where(new Compare("User.uid", $id))
->execute();
@@ -152,6 +155,9 @@ namespace Api\User {
use Driver\SQL\Condition\CondNot;
use Driver\SQL\Expression\JsonArrayAgg;
use ImagickException;
use Objects\GpgKey;
use Objects\TwoFactor\KeyBasedTwoFactorToken;
use Objects\TwoFactor\TwoFactorToken;
use Objects\User;
class Create extends UserAPI {
@@ -350,6 +356,11 @@ namespace Api\User {
return $this->createError("User not found");
} else {
$gpgFingerprint = null;
if ($user[0]["gpg_id"] && $sql->parseBool($user[0]["gpg_confirmed"])) {
$gpgFingerprint = $user[0]["gpg_fingerprint"];
}
$queriedUser = array(
"uid" => $userId,
"name" => $user[0]["name"],
@@ -360,6 +371,7 @@ namespace Api\User {
"profilePicture" => $user[0]["profilePicture"],
"confirmed" => $sql->parseBool($user["0"]["confirmed"]),
"groups" => array(),
"gpgFingerprint" => $gpgFingerprint,
);
foreach($user as $row) {
@@ -371,10 +383,9 @@ namespace Api\User {
}
}
// either we are querying own info or we are internal employees
// as internal employees can add arbitrary users to projects
$canView = ($userId === $this->user->getId() ||
$this->user->hasGroup(USER_GROUP_ADMIN) ||
// either we are querying own info or we are support / admin
$canView = ($userId === $this->user->getId()) ||
($this->user->hasGroup(USER_GROUP_ADMIN) ||
$this->user->hasGroup(USER_GROUP_SUPPORT));
// full info only when we have administrative privileges, or we are querying ourselves
@@ -382,23 +393,17 @@ namespace Api\User {
($this->user->hasGroup(USER_GROUP_ADMIN) || $this->user->hasGroup(USER_GROUP_SUPPORT));
if (!$canView) {
$res = $sql->select(new JsonArrayAgg(new Column("projectId"), "projectIds"))
->from("ProjectMember")
->where(new Compare("userId", $this->user->getId()), new Compare("userId", $userId))
->groupBy("projectId")
->execute();
// check if user posted something publicly
$res = $sql->select(new JsonArrayAgg(new Column("publishedBy"), "publisherIds"))
->from("News")
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success ) {
return false;
} else if (is_array($res)) {
foreach ($res as $row) {
if (count(json_decode($row["projectIds"])) > 1) {
$canView = true;
break;
}
}
} else {
$canView = in_array($userId, json_decode($res[0]["publisherIds"], true));
}
}
@@ -598,6 +603,7 @@ namespace Api\User {
} else if (!$this->updateUser($result["user"]["uid"], $password)) {
return false;
} else {
// Invalidate token
$this->user->getSQL()
->update("UserToken")
@@ -671,7 +677,7 @@ namespace Api\User {
parent::__construct($user, $externalCall, array(
'username' => new StringType('username'),
'password' => new StringType('password'),
'stayLoggedIn' => new Parameter('stayLoggedIn', Parameter::TYPE_BOOLEAN, true, true)
'stayLoggedIn' => new Parameter('stayLoggedIn', Parameter::TYPE_BOOLEAN, true, false)
));
$this->forbidMethod("GET");
}
@@ -701,9 +707,11 @@ namespace Api\User {
$stayLoggedIn = $this->getParam('stayLoggedIn');
$sql = $this->user->getSQL();
$res = $sql->select("User.uid", "User.password", "User.confirmed")
$res = $sql->select("User.uid", "User.password", "User.confirmed",
"User.2fa_id", "2FA.type as 2fa_type", "2FA.confirmed as 2fa_confirmed", "2FA.data as 2fa_data")
->from("User")
->where(new Compare("User.name", $username), new Compare("User.email", $username))
->leftJoin("2FA", "2FA.uid", "User.2fa_id")
->limit(1)
->execute();
@@ -717,6 +725,7 @@ namespace Api\User {
$row = $res[0];
$uid = $row['uid'];
$confirmed = $sql->parseBool($row["confirmed"]);
$token = $row["2fa_id"] ? TwoFactorToken::newInstance($row["2fa_type"], $row["2fa_data"], $row["2fa_id"], $sql->parseBool($row["2fa_confirmed"])) : null;
if (password_verify($password, $row['password'])) {
if (!$confirmed) {
$this->result["emailConfirmed"] = false;
@@ -727,6 +736,14 @@ namespace Api\User {
$this->result["loggedIn"] = true;
$this->result["logoutIn"] = $this->user->getSession()->getExpiresSeconds();
$this->result["csrf_token"] = $this->user->getSession()->getCsrfToken();
if ($token && $token->isConfirmed()) {
$this->result["2fa"] = ["type" => $token->getType()];
if ($token instanceof KeyBasedTwoFactorToken) {
$challenge = base64_encode(generateRandomString(32, "raw"));
$this->result["2fa"]["challenge"] = $challenge;
$_SESSION["challenge"] = $challenge;
}
}
$this->success = true;
}
} else {
@@ -743,8 +760,9 @@ namespace Api\User {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall);
$this->loginRequired = true;
$this->loginRequired = false;
$this->apiKeyAllowed = false;
$this->forbidMethod("GET");
}
public function execute($values = array()): bool {
@@ -752,6 +770,10 @@ namespace Api\User {
return false;
}
if (!$this->user->isLoggedIn()) {
return $this->createError("You are not logged in.");
}
$this->success = $this->user->logout();
$this->lastError = $this->user->getSQL()->getLastError();
return $this->success;
@@ -807,7 +829,6 @@ namespace Api\User {
$email = $this->getParam('email');
$password = $this->getParam("password");
$confirmPassword = $this->getParam("confirmPassword");
if (!$this->userExists($username, $email)) {
return false;
}
@@ -816,16 +837,17 @@ namespace Api\User {
return false;
}
$this->userId = $this->insertUser($username, $email, $password, false);
$fullName = substr($email, 0, strrpos($email, "@"));
$fullName = implode(" ", array_map(function ($part) {
return ucfirst(strtolower($part));
}, explode(".", $fullName))
);
$this->userId = $this->insertUser($username, $email, $password, false, $fullName);
if (!$this->success) {
return false;
}
// add internal group
$this->user->getSQL()->insert("UserGroup", ["user_id", "group_id"])
->addRow($this->userId, USER_GROUP_INTERNAL)
->execute();
$validHours = 48;
$this->token = generateRandomString(36);
if ($this->insertToken($this->userId, $this->token, "email_confirm", $validHours)) {
@@ -924,7 +946,7 @@ namespace Api\User {
class Edit extends UserAPI {
public function __construct(User $user, bool $externalCall) {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
'id' => new Parameter('id', Parameter::TYPE_INT),
'username' => new StringType('username', 32, true, NULL),
@@ -1032,7 +1054,7 @@ namespace Api\User {
class Delete extends UserAPI {
public function __construct(User $user, bool $externalCall) {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
'id' => new Parameter('id', Parameter::TYPE_INT)
));
@@ -1055,6 +1077,7 @@ namespace Api\User {
if (empty($user)) {
return $this->createError("User not found");
} else {
$sql = $this->user->getSQL();
$res = $sql->delete("User")->where(new Compare("uid", $id))->execute();
$this->success = ($res !== FALSE);
@@ -1129,11 +1152,18 @@ namespace Api\User {
if ($this->success) {
$messageBody = $req->getResult()["html"];
$gpgFingerprint = null;
if ($user["gpg_id"] && $user["gpg_confirmed"]) {
$gpgFingerprint = $user["gpg_fingerprint"];
}
$request = new \Api\Mail\Send($this->user);
$this->success = $request->execute(array(
"to" => $email,
"subject" => "[$siteName] Password Reset",
"body" => $messageBody
"body" => $messageBody,
"gpgFingerprint" => $gpgFingerprint
));
$this->lastError = $request->getLastError();
}
@@ -1144,8 +1174,10 @@ namespace Api\User {
private function findUser($email): ?array {
$sql = $this->user->getSQL();
$res = $sql->select("User.uid", "User.name")
$res = $sql->select("User.uid", "User.name",
"User.gpg_id", "GpgKey.confirmed as gpg_confirmed", "GpgKey.fingerprint as gpg_fingerprint")
->from("User")
->leftJoin("GpgKey", "GpgKey.uid", "User.gpg_id")
->where(new Compare("User.email", $email))
->where(new CondBool("User.confirmed"))
->execute();
@@ -1399,6 +1431,321 @@ namespace Api\User {
}
}
class ImportGPG extends UserAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
"pubkey" => new StringType("pubkey")
));
$this->loginRequired = true;
$this->forbidMethod("GET");
}
private function testKey(string $keyString) {
$res = GpgKey::getKeyInfo($keyString);
if (!$res["success"]) {
return $this->createError($res["error"]);
}
$keyData = $res["data"];
$keyType = $keyData["type"];
$expires = $keyData["expires"];
if ($keyType === "sec#") {
return self::createError("ATTENTION! It seems like you've imported a PGP PRIVATE KEY instead of a public key.
It is recommended to immediately revoke your private key and create a new key pair.");
} else if ($keyType !== "pub") {
return self::createError("Unknown key type: $keyType");
} else if (isInPast($expires)) {
return self::createError("It seems like the gpg key is already expired.");
} else {
return $keyData;
}
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$gpgKey = $this->user->getGPG();
if ($gpgKey) {
return $this->createError("You already added a GPG key to your account.");
}
// fix key first, enforce a newline after
$keyString = $this->getParam("pubkey");
$keyString = preg_replace("/(-{2,})\n([^\n])/", "$1\n\n$2", $keyString);
$keyData = $this->testKey($keyString);
if ($keyData === false) {
return false;
}
$res = GpgKey::importKey($keyString);
if (!$res["success"]) {
return $this->createError($res["error"]);
}
$sql = $this->user->getSQL();
$res = $sql->insert("GpgKey", ["fingerprint", "algorithm", "expires"])
->addRow($keyData["fingerprint"], $keyData["algorithm"], $keyData["expires"])
->returning("uid")
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
$gpgKeyId = $sql->getLastInsertId();
$res = $sql->update("User")
->set("gpg_id", $gpgKeyId)
->where(new Compare("uid", $this->user->getId()))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
$token = generateRandomString(36);
$res = $sql->insert("UserToken", ["user_id", "token", "token_type", "valid_until"])
->addRow($this->user->getId(), $token, "gpg_confirm", (new DateTime())->modify("+1 hour"))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
$name = htmlspecialchars($this->user->getFullName());
if (!$name) {
$name = htmlspecialchars($this->user->getUsername());
}
$settings = $this->user->getConfiguration()->getSettings();
$baseUrl = htmlspecialchars($settings->getBaseUrl());
$token = htmlspecialchars(urlencode($token));
$mailBody = "Hello $name,<br><br>" .
"you imported a GPG public key for end-to-end encrypted mail communication. " .
"To confirm the key and verify, you own the corresponding private key, please click on the following link. " .
"The link is active for one hour.<br><br>" .
"<a href='$baseUrl/confirmGPG?token=$token'>$baseUrl/settings?confirmGPG&token=$token</a><br>
Best Regards<br>
ilum:e Security Lab";
$sendMail = new \Api\Mail\Send($this->user);
$this->success = $sendMail->execute(array(
"to" => $this->user->getEmail(),
"subject" => "Security Lab - Confirm GPG-Key",
"body" => $mailBody,
"gpgFingerprint" => $keyData["fingerprint"]
));
$this->lastError = $sendMail->getLastError();
if ($this->success) {
$this->result["gpg"] = array(
"fingerprint" => $keyData["fingerprint"],
"confirmed" => false,
"algorithm" => $keyData["algorithm"],
"expires" => $keyData["expires"]->getTimestamp()
);
}
return $this->success;
}
}
class RemoveGPG extends UserAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
"password" => new StringType("password")
));
$this->loginRequired = true;
$this->forbidMethod("GET");
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$gpgKey = $this->user->getGPG();
if (!$gpgKey) {
return $this->createError("You have not added a GPG public key to your account yet.");
}
$sql = $this->user->getSQL();
$res = $sql->select("password")
->from("User")
->where(new Compare("User.uid", $this->user->getId()))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if ($this->success && is_array($res)) {
$hash = $res[0]["password"];
$password = $this->getParam("password");
if (!password_verify($password, $hash)) {
return $this->createError("Incorrect password.");
} else {
$res = $sql->delete("GpgKey")
->where(new Compare("uid",
$sql->select("User.gpg_id")
->from("User")
->where(new Compare("User.uid", $this->user->getId()))
))->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
}
}
return $this->success;
}
}
class ConfirmGPG extends UserAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [
"token" => new StringType("token", 36)
]);
$this->loginRequired = true;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$gpgKey = $this->user->getGPG();
if (!$gpgKey) {
return $this->createError("You have not added a GPG key yet.");
} else if ($gpgKey->isConfirmed()) {
return $this->createError("Your GPG key is already confirmed");
}
$token = $this->getParam("token");
$sql = $this->user->getSQL();
$res = $sql->select($sql->count())
->from("UserToken")
->where(new Compare("token", $token))
->where(new Compare("valid_until", $sql->now(), ">="))
->where(new Compare("user_id", $this->user->getId()))
->where(new Compare("token_type", "gpg_confirm"))
->where(new CondNot(new CondBool("used")))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if ($this->success && is_array($res)) {
if ($res[0]["count"] === 0) {
return $this->createError("Invalid token");
} else {
$res = $sql->update("GpgKey")
->set("confirmed", 1)
->where(new Compare("uid", $gpgKey->getId()))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
if (!$this->success) {
return false;
}
$res = $sql->update("UserToken")
->set("used", 1)
->where(new Compare("token", $token))
->execute();
$this->success = ($res !== false);
$this->lastError = $sql->getLastError();
}
}
return $this->success;
}
}
class DownloadGPG extends UserAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, array(
"id" => new Parameter("id", Parameter::TYPE_INT, true, null),
"format" => new StringType("format", 16, true, "ascii")
));
$this->loginRequired = true;
$this->csrfTokenRequired = false;
}
public function execute($values = array()): bool {
if (!parent::execute($values)) {
return false;
}
$allowedFormats = ["json", "ascii", "gpg"];
$format = $this->getParam("format");
if (!in_array($format, $allowedFormats)) {
return $this->getParam("Invalid requested format. Allowed formats: " . implode(",", $allowedFormats));
}
$userId = $this->getParam("id");
if ($userId === null || $userId == $this->user->getId()) {
$gpgKey = $this->user->getGPG();
if (!$gpgKey) {
return $this->createError("You did not add a gpg key yet.");
}
$email = $this->user->getEmail();
$gpgFingerprint = $gpgKey->getFingerprint();
} else {
$req = new Get($this->user);
$this->success = $req->execute(["id" => $userId]);
$this->lastError = $req->getLastError();
if (!$this->success) {
return false;
}
$res = $req->getResult()["user"];
$email = $res["email"];
$gpgFingerprint = $res["gpgFingerprint"];
if (!$gpgFingerprint) {
return $this->createError("This user has not added a gpg key yet");
}
}
$res = GpgKey::export($gpgFingerprint, $format !== "gpg");
if (!$res["success"]) {
return $this->createError($res["error"]);
}
$key = $res["data"];
if ($format === "json") {
$this->result["key"] = $key;
return true;
} else if ($format === "ascii") {
$contentType = "application/pgp-keys";
$ext = "asc";
} else if ($format === "gpg") {
$contentType = "application/octet-stream";
$ext = "gpg";
} else {
die("Invalid format");
}
$fileName = "$email.$ext";
header("Content-Type: $contentType");
header("Content-Length: " . strlen($key));
header("Content-Disposition: attachment; filename=\"$fileName\"");
die($key);
}
}
class UploadPicture extends UserAPI {
public function __construct(User $user, bool $externalCall = false) {
parent::__construct($user, $externalCall, [

View File

@@ -2,8 +2,12 @@
namespace Api {
abstract class VisitorsAPI extends Request {
use Objects\User;
abstract class VisitorsAPI extends Request {
public function __construct(User $user, bool $externalCall = false, array $params = []) {
parent::__construct($user, $externalCall, $params);
}
}
}