web-base/Core/API/UserAPI.class.php

1493 lines
49 KiB
PHP
Raw Normal View History

2020-06-20 20:13:51 +02:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\API {
2020-06-20 20:13:51 +02:00
use Core\Driver\SQL\Column\Column;
2022-11-18 18:06:46 +01:00
use Core\Driver\SQL\Condition\Compare;
use Core\Driver\SQL\Condition\CondIn;
2022-11-18 18:06:46 +01:00
use Core\Objects\Context;
use Core\Objects\DatabaseEntity\Group;
2022-11-18 18:06:46 +01:00
use Core\Objects\DatabaseEntity\Language;
2022-11-19 01:15:34 +01:00
use Core\Objects\DatabaseEntity\User;
use Core\Objects\DatabaseEntity\UserToken;
2020-06-22 21:50:58 +02:00
abstract class UserAPI extends Request {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false, array $params = array()) {
parent::__construct($context, $externalCall, $params);
}
2022-03-08 11:50:18 +01:00
protected function checkUserExists(?string $username, ?string $email = null): bool {
2020-06-23 17:55:52 +02:00
$conditions = array();
2021-04-02 21:58:06 +02:00
if ($username) {
2020-06-23 17:55:52 +02:00
$conditions[] = new Compare("User.name", $username);
}
2021-04-02 21:58:06 +02:00
if ($email) {
2020-06-23 17:55:52 +02:00
$conditions[] = new Compare("User.email", $email);
}
if (empty($conditions)) {
return true;
}
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2020-06-22 21:50:58 +02:00
$res = $sql->select("User.name", "User.email")
->from("User")
2020-06-23 17:55:52 +02:00
->where(...$conditions)
2020-06-22 21:50:58 +02:00
->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.");
2020-07-01 22:13:50 +02:00
} else if (strcasecmp($email, $row['email']) === 0) {
2020-06-22 21:50:58 +02:00
return $this->createError("This email address is already in use.");
}
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
return $this->success;
2020-06-20 20:13:51 +02:00
}
2021-12-08 16:53:43 +01:00
protected function checkPasswordRequirements($password, $confirmPassword): bool {
if ((($password === null) !== ($confirmPassword === null)) || strcmp($password, $confirmPassword) !== 0) {
2020-06-29 16:47:02 +02:00
return $this->createError("The given passwords do not match");
2022-06-20 19:52:31 +02:00
} else if (strlen($password) < 6) {
2020-06-29 16:47:02 +02:00
return $this->createError("The password should be at least 6 characters long");
}
return true;
}
2021-11-11 14:25:26 +01:00
protected function checkUsernameRequirements($username): bool {
if (strlen($username) < 5 || strlen($username) > 32) {
2020-06-29 16:47:02 +02:00
return $this->createError("The username should be between 5 and 32 characters long");
2021-11-11 14:25:26 +01:00
} else if (!preg_match("/[a-zA-Z0-9_\-]+/", $username)) {
return $this->createError("The username should only contain the following characters: a-z A-Z 0-9 _ -");
2020-06-29 16:47:02 +02:00
}
2021-11-11 14:25:26 +01:00
return true;
}
protected function checkRequirements($username, $password, $confirmPassword): bool {
return $this->checkUsernameRequirements($username) &&
$this->checkPasswordRequirements($password, $confirmPassword);
2020-06-29 16:47:02 +02:00
}
protected function checkGroups(array &$groups): bool {
$sql = $this->context->getSQL();
$currentUser = $this->context->getUser();
$requestedGroups = array_unique($this->getParam("groups"));
if (!empty($requestedGroups)) {
$availableGroups = Group::findAll($sql, new CondIn(new Column("id"), $requestedGroups));
foreach ($requestedGroups as $groupId) {
if (!isset($availableGroups[$groupId])) {
return $this->createError("Group with id=$groupId does not exist.");
} else if ($this->isExternalCall() && $groupId === Group::ADMIN && !$currentUser->hasGroup(Group::ADMIN)) {
return $this->createError("You cannot create users with administrator groups.");
} else {
$groups[] = $groupId;
}
}
}
return true;
}
2022-11-20 17:13:53 +01:00
protected function insertUser(string $username, ?string $email, string $password, bool $confirmed, string $fullName = "", array $groups = []): bool|User {
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2022-11-19 01:15:34 +01:00
$user = new User();
2024-05-06 15:30:43 +02:00
$user->language = Language::DEFAULT_LANGUAGE();
2022-06-20 19:52:31 +02:00
$user->registeredAt = new \DateTime();
$user->password = $this->hashPassword($password);
$user->name = $username;
$user->email = $email;
$user->confirmed = $confirmed;
$user->fullName = $fullName ?? "";
2022-11-20 17:13:53 +01:00
$user->groups = $groups;
2022-06-20 19:52:31 +02:00
$this->success = ($user->save($sql) !== FALSE);
2020-06-22 21:50:58 +02:00
$this->lastError = $sql->getLastError();
2020-06-20 20:13:51 +02:00
2022-11-19 01:15:34 +01:00
return $this->success ? $user : false;
2020-06-20 20:13:51 +02:00
}
2022-06-20 19:52:31 +02:00
protected function hashPassword($password): string {
2020-06-23 18:40:43 +02:00
return password_hash($password, PASSWORD_BCRYPT);
2020-06-22 21:50:58 +02:00
}
2022-11-19 01:15:34 +01:00
protected function checkToken(string $token) : UserToken|bool {
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2022-11-20 17:13:53 +01:00
$userToken = UserToken::findBy(UserToken::createBuilder($sql, true)
->whereEq("UserToken.token", $token)
->whereGt("UserToken.valid_until", $sql->now())
->whereFalse("UserToken.used")
2022-11-20 17:13:53 +01:00
->fetchEntities());
2021-11-11 14:25:26 +01:00
2022-11-19 01:15:34 +01:00
if ($userToken === false) {
return $this->createError("Error verifying token: " . $sql->getLastError());
} else if ($userToken === null) {
return $this->createError("This token does not exist or is no longer valid");
2021-12-08 16:53:43 +01:00
} else {
2022-11-19 01:15:34 +01:00
return $userToken;
2021-12-08 16:53:43 +01:00
}
}
2020-06-20 20:13:51 +02:00
}
}
2022-11-18 18:06:46 +01:00
namespace Core\API\User {
2020-06-20 20:13:51 +02:00
2022-11-20 17:13:53 +01:00
use Core\API\Parameter\ArrayType;
2024-05-03 20:22:58 +02:00
use Core\API\Parameter\FloatType;
use Core\API\Parameter\IntegerType;
2022-11-18 18:06:46 +01:00
use Core\API\Parameter\Parameter;
use Core\API\Parameter\StringType;
use Core\API\Template\Render;
2024-05-03 19:05:43 +02:00
use Core\API\Traits\Captcha;
use Core\API\Traits\Pagination;
2022-11-18 18:06:46 +01:00
use Core\API\UserAPI;
2022-11-20 17:13:53 +01:00
use Core\Driver\SQL\Condition\CondBool;
use Core\Driver\SQL\Condition\CondLike;
2022-11-20 17:13:53 +01:00
use Core\Driver\SQL\Condition\CondOr;
use Core\Driver\SQL\Expression\Alias;
2022-11-20 17:13:53 +01:00
use Core\Objects\DatabaseEntity\Group;
2022-11-19 01:15:34 +01:00
use Core\Objects\DatabaseEntity\UserToken;
2022-11-18 18:06:46 +01:00
use Core\Driver\SQL\Column\Column;
use Core\Driver\SQL\Condition\Compare;
use Core\Driver\SQL\Condition\CondIn;
use Core\Driver\SQL\Expression\JsonArrayAgg;
2024-04-23 20:14:32 +02:00
use Core\Objects\RateLimiting;
use Core\Objects\RateLimitRule;
2024-04-07 18:29:33 +02:00
use Core\Objects\TwoFactor\KeyBasedTwoFactorToken;
2021-12-08 16:53:43 +01:00
use ImagickException;
2022-11-18 18:06:46 +01:00
use Core\Objects\Context;
use Core\Objects\DatabaseEntity\User;
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
class Create extends UserAPI {
2020-06-20 20:13:51 +02:00
2022-11-20 17:13:53 +01:00
private User $user;
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-22 21:50:58 +02:00
'username' => new StringType('username', 32),
'fullName' => new StringType('fullName', 64, true, ""),
2020-06-24 01:09:08 +02:00
'email' => new Parameter('email', Parameter::TYPE_EMAIL, true, NULL),
2020-06-22 21:50:58 +02:00
'password' => new StringType('password'),
'confirmPassword' => new StringType('confirmPassword'),
2022-11-20 17:13:53 +01:00
'groups' => new ArrayType("groups", Parameter::TYPE_INT, true, true, [])
2020-06-22 21:50:58 +02:00
));
2020-06-22 21:50:58 +02:00
$this->loginRequired = true;
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
$username = $this->getParam('username');
$fullName = $this->getParam('fullName');
2020-06-22 21:50:58 +02:00
$email = $this->getParam('email');
2020-06-23 18:40:43 +02:00
$password = $this->getParam('password');
$confirmPassword = $this->getParam('confirmPassword');
2020-06-29 16:47:02 +02:00
if (!$this->checkRequirements($username, $password, $confirmPassword)) {
return false;
2020-06-23 18:40:43 +02:00
}
$groups = [];
if (!$this->checkGroups($groups)) {
2020-06-22 21:50:58 +02:00
return false;
}
2020-06-20 20:13:51 +02:00
if (!$this->checkUserExists($username, $email)) {
return false;
2022-11-20 17:13:53 +01:00
}
2020-06-23 21:18:45 +02:00
// prevent duplicate keys
$email = (!is_null($email) && empty($email)) ? null : $email;
$user = $this->insertUser($username, $email, $password, true, $fullName, $groups);
2022-11-19 01:15:34 +01:00
if ($user !== false) {
2022-11-20 17:13:53 +01:00
$this->user = $user;
2022-11-19 01:15:34 +01:00
$this->result["userId"] = $user->getId();
2024-04-10 19:04:37 +02:00
$this->logger->info("A new user with username='$username' and email='$email' was created by " . $this->logUserId());
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2020-06-23 18:40:43 +02:00
return $this->success;
2020-06-22 21:50:58 +02:00
}
2022-11-20 17:13:53 +01:00
public function getUser(): User {
return $this->user;
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to create new users";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN];
2023-01-16 21:47:23 +01:00
}
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
class Fetch extends UserAPI {
2020-06-20 20:13:51 +02:00
use Pagination;
2020-06-20 20:13:51 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall,
2024-04-04 12:46:58 +02:00
self::getPaginationParameters(['id', 'name', 'fullName', 'email', 'groups', 'registeredAt', 'active', 'confirmed'],
'id', 'asc')
);
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
$currentUser = $this->context->getUser();
$fullInfo = ($currentUser->hasGroup(Group::ADMIN) ||
$currentUser->hasGroup(Group::SUPPORT));
2020-06-20 20:13:51 +02:00
$orderBy = $this->getParam("orderBy");
2022-11-20 17:13:53 +01:00
$condition = null;
if (!$fullInfo) {
$condition = new CondOr(
new Compare("User.id", $currentUser->getId()),
new CondBool("User.confirmed")
);
2023-01-07 15:34:05 +01:00
if ($orderBy && !$currentUser->canAccess(User::class, $orderBy)) {
return $this->createError("Insufficient permissions for sorting by field '$orderBy'");
}
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2022-11-20 17:13:53 +01:00
$sql = $this->context->getSQL();
if (!$this->initPagination($sql, User::class, $condition)) {
return false;
}
$groupNames = new Alias(
$sql->select(new JsonArrayAgg("name"))->from("Group")
->leftJoin("NM_User_groups", "NM_User_groups.group_id", "Group.id")
->whereEq("NM_User_groups.user_id", new Column("User.id")),
"groups"
);
2020-06-22 21:50:58 +02:00
$userQuery = $this->createPaginationQuery($sql, [$groupNames]);
2022-11-20 17:13:53 +01:00
$users = User::findBy($userQuery);
if ($users !== false && $users !== null) {
2022-11-20 17:13:53 +01:00
$this->result["users"] = [];
2023-01-07 15:34:05 +01:00
foreach ($users as $user) {
$this->result["users"][] = $user->jsonSerialize();
2020-06-22 21:50:58 +02:00
}
2022-11-20 17:13:53 +01:00
} else {
return $this->createError("Error fetching users: " . $sql->getLastError());
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
return $this->success;
2020-06-20 20:13:51 +02:00
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to fetch all users";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN, Group::SUPPORT];
2023-01-16 21:47:23 +01:00
}
2020-06-22 21:50:58 +02:00
}
2020-06-23 16:26:04 +02:00
class Get extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-23 16:26:04 +02:00
'id' => new Parameter('id', Parameter::TYPE_INT)
));
2021-12-08 16:53:43 +01:00
$this->loginRequired = true;
2020-06-23 16:26:04 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-23 16:26:04 +02:00
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2021-12-08 16:53:43 +01:00
$userId = $this->getParam("id");
2022-11-19 01:15:34 +01:00
$user = User::find($sql, $userId, true);
if ($user === false) {
return $this->createError("Error querying user: " . $sql->getLastError());
} else if ($user === null) {
return $this->createError("User not found");
} else {
2021-12-08 16:53:43 +01:00
2022-11-19 01:15:34 +01:00
$queriedUser = $user->jsonSerialize();
$currentUser = $this->context->getUser();
2021-12-08 16:53:43 +01:00
2022-11-19 01:15:34 +01:00
// full info only when we have administrative privileges, or we are querying ourselves
$fullInfo = ($userId === $currentUser->getId() ||
2022-11-20 17:13:53 +01:00
$currentUser->hasGroup(Group::ADMIN) ||
$currentUser->hasGroup(Group::SUPPORT));
2021-12-08 16:53:43 +01:00
2023-01-07 15:34:05 +01:00
if (!$fullInfo && !$queriedUser["confirmed"]) {
return $this->createError("No permissions to access this user");
2020-06-23 16:26:04 +02:00
}
2022-11-19 01:15:34 +01:00
$this->result["user"] = $queriedUser;
2020-06-23 16:26:04 +02:00
}
return $this->success;
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to get details about a user";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN, Group::SUPPORT];
2023-01-16 21:47:23 +01:00
}
2020-06-23 16:26:04 +02:00
}
class Search extends UserAPI {
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, [
"query" => new StringType("query", 64)
]);
}
protected function _execute(): bool {
$sql = $this->context->getSQL();
$query = $this->getParam("query");
$users = User::findBy(User::createBuilder($sql, false)
->where(new CondOr(
new CondLike(new Column("name"), "%$query%"),
new CondLike(new Column("full_name"), "%$query%"),
new CondLike(new Column("email"), "%$query%"),
))
->whereTrue("active")
);
if ($users === false) {
return $this->createError($sql->getLastError());
}
$this->result["users"] = $users;
return true;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to search other users";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN, Group::SUPPORT];
}
}
2020-06-22 21:50:58 +02:00
class Info extends UserAPI {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array());
$this->csrfTokenRequired = false;
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
$currentUser = $this->context->getUser();
2023-01-16 21:47:23 +01:00
$language = $this->context->getLanguage();
$this->result["language"] = $language->jsonSerialize();
2022-06-20 19:52:31 +02:00
if (!$currentUser) {
2020-06-22 21:50:58 +02:00
$this->result["loggedIn"] = false;
2023-01-16 21:47:23 +01:00
$userGroups = [];
2020-06-22 21:50:58 +02:00
} else {
2024-04-07 18:29:33 +02:00
$twoFactorToken = $currentUser->getTwoFactorToken();
if ($twoFactorToken instanceof KeyBasedTwoFactorToken && !$twoFactorToken->hasChallenge()) {
$twoFactorToken->generateChallenge();
}
2020-06-22 21:50:58 +02:00
$this->result["loggedIn"] = true;
2022-06-20 19:52:31 +02:00
$userGroups = array_keys($currentUser->getGroups());
$this->result["user"] = $currentUser->jsonSerialize();
2023-03-05 15:30:06 +01:00
$this->result["session"] = $this->context->getSession()->jsonSerialize([
"id", "expires", "stayLoggedIn", "data", "csrfToken"
]);
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2023-01-16 21:47:23 +01:00
$sql = $this->context->getSQL();
$res = $sql->select("method", "groups")
->from("ApiPermission")
->execute();
$this->result["permissions"] = [];
if (is_array($res)) {
foreach ($res as $row) {
$requiredGroups = json_decode($row["groups"], true);
if (empty($requiredGroups) || !empty(array_intersect($requiredGroups, $userGroups))) {
$this->result["permissions"][] = $row["method"];
}
}
}
2020-06-22 21:50:58 +02:00
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Retrieves information about the current session";
}
public static function hasConfigurablePermissions(): bool {
return false;
}
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
class Invite extends UserAPI {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-22 21:50:58 +02:00
'username' => new StringType('username', 32),
'fullName' => new StringType('fullName', 64, true, ""),
2020-06-22 21:50:58 +02:00
'email' => new StringType('email', 64),
'groups' => new ArrayType("groups", Parameter::TYPE_INT, true, true, [])
2020-06-22 21:50:58 +02:00
));
2020-06-22 21:50:58 +02:00
$this->loginRequired = true;
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-22 21:50:58 +02:00
$sql = $this->context->getSQL();
$settings = $this->context->getSettings();
$currentUser = $this->context->getUser();
if (!$settings->isMailEnabled()) {
return $this->createError("An invitation cannot be sent because mailing is not enabled.");
}
2020-06-22 21:50:58 +02:00
$username = $this->getParam('username');
$fullName = $this->getParam('fullName');
2020-06-22 21:50:58 +02:00
$email = $this->getParam('email');
$groups = [];
if (!$this->checkGroups($groups)) {
return false;
}
2022-03-08 11:50:18 +01:00
if (!$this->checkUserExists($username, $email)) {
2020-06-22 21:50:58 +02:00
return false;
}
2020-06-29 16:47:02 +02:00
// Create user
$user = $this->insertUser($username, $email, "", false, $fullName, $groups);
2022-11-19 01:15:34 +01:00
if ($user === false) {
2020-06-29 16:47:02 +02:00
return false;
}
$this->result["userId"] = $user->getId();
2024-04-10 19:04:37 +02:00
$this->logger->info("A new user with username='$username' and email='$email' was invited by " . $this->logUserId());
2024-04-05 14:17:50 +02:00
2020-06-29 16:47:02 +02:00
// Create Token
2020-06-22 21:50:58 +02:00
$token = generateRandomString(36);
2021-12-08 16:53:43 +01:00
$validDays = 7;
2022-11-19 01:15:34 +01:00
$userToken = new UserToken($user, $token, UserToken::TYPE_INVITE, $validDays * 24);
2020-06-26 18:24:23 +02:00
2022-11-19 01:15:34 +01:00
if ($userToken->save($sql)) {
//send validation mail
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
2021-12-08 16:53:43 +01:00
$baseUrl = $settings->getBaseUrl();
$siteName = $settings->getSiteName();
2022-06-20 19:52:31 +02:00
$req = new Render($this->context);
2021-12-08 16:53:43 +01:00
$this->success = $req->execute([
"file" => "mail/accept_invite.twig",
"parameters" => [
"link" => "$baseUrl/acceptInvite?token=$token",
"site_name" => $siteName,
"base_url" => $baseUrl,
"username" => $username,
"valid_time" => $this->formatDuration($validDays, "day")
]
]);
$this->lastError = $req->getLastError();
2020-06-26 18:24:23 +02:00
2021-12-08 16:53:43 +01:00
if ($this->success) {
$messageBody = $req->getResult()["html"];
2022-11-18 18:06:46 +01:00
$request = new \Core\API\Mail\Send($this->context);
2021-12-08 16:53:43 +01:00
$this->success = $request->execute(array(
"to" => $email,
"subject" => "[$siteName] Account Invitation",
"body" => $messageBody
));
2020-06-26 18:24:23 +02:00
2021-12-08 16:53:43 +01:00
$this->lastError = $request->getLastError();
2020-06-29 16:47:02 +02:00
}
2020-06-26 18:24:23 +02:00
if (!$this->success) {
2022-05-31 16:14:49 +02:00
$this->logger->error("Could not deliver email to=$email type=invite reason=" . $this->lastError);
2020-06-26 18:24:23 +02:00
$this->lastError = "The invitation was created but the confirmation email could not be sent. " .
2022-05-31 16:14:49 +02:00
"Please contact the server administration. This issue has been automatically logged. Reason: " . $this->lastError;
2020-06-26 18:24:23 +02:00
}
2020-06-22 21:50:58 +02:00
}
2020-06-29 16:47:02 +02:00
2022-11-19 01:15:34 +01:00
$this->logger->info("Created new user with id=" . $user->getId());
2020-06-29 16:47:02 +02:00
return $this->success;
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to invite new users";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN, Group::SUPPORT, Group::MODERATOR];
2023-01-16 21:47:23 +01:00
}
2020-06-29 16:47:02 +02:00
}
class AcceptInvite extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-29 16:47:02 +02:00
'token' => new StringType('token', 36),
'password' => new StringType('password'),
'confirmPassword' => new StringType('confirmPassword'),
));
2020-07-02 00:47:45 +02:00
$this->csrfTokenRequired = false;
2020-06-29 16:47:02 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-29 16:47:02 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-29 16:47:02 +02:00
return $this->createError("You are already logged in.");
}
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
2020-06-29 16:47:02 +02:00
$token = $this->getParam("token");
$password = $this->getParam("password");
$confirmPassword = $this->getParam("confirmPassword");
2022-11-19 01:15:34 +01:00
$userToken = $this->checkToken($token);
if ($userToken === false) {
2020-06-29 16:47:02 +02:00
return false;
2022-11-19 01:15:34 +01:00
} else if ($userToken->getType() !== UserToken::TYPE_INVITE) {
return $this->createError("Invalid token type");
2020-06-29 16:47:02 +02:00
}
2022-11-19 01:15:34 +01:00
$user = $userToken->getUser();
if ($user->confirmed) {
2020-06-29 16:47:02 +02:00
return $this->createError("Your email address is already confirmed.");
} else if (!$this->checkPasswordRequirements($password, $confirmPassword)) {
return false;
} else {
2022-11-19 01:15:34 +01:00
$user->password = $this->hashPassword($password);
$user->confirmed = true;
2022-11-29 14:17:11 +01:00
if ($user->save($sql, ["password", "confirmed"])) {
2022-11-19 01:15:34 +01:00
$userToken->invalidate($sql);
return true;
} else {
return $this->createError("Unable to update user details: " . $sql->getLastError());
}
2020-06-29 16:47:02 +02:00
}
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to accept invitations and register an account";
}
2020-06-29 16:47:02 +02:00
}
class ConfirmEmail extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-29 16:47:02 +02:00
'token' => new StringType('token', 36)
));
2021-11-11 14:25:26 +01:00
$this->csrfTokenRequired = false;
2024-04-23 20:14:32 +02:00
$this->rateLimiting = new RateLimiting(
new RateLimitRule(5, 1, RateLimitRule::MINUTE)
);
2020-06-29 16:47:02 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-29 16:47:02 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-29 16:47:02 +02:00
return $this->createError("You are already logged in.");
}
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
2020-06-29 16:47:02 +02:00
$token = $this->getParam("token");
2022-11-19 01:15:34 +01:00
$userToken = $this->checkToken($token);
if ($userToken === false) {
return false;
} else if ($userToken->getType() !== UserToken::TYPE_EMAIL_CONFIRM) {
return $this->createError("Invalid token type");
}
2020-06-29 16:47:02 +02:00
2022-11-19 01:15:34 +01:00
$user = $userToken->getUser();
if ($user->confirmed) {
return $this->createError("Your email address is already confirmed.");
} else {
$user->confirmed = true;
2022-11-29 14:17:11 +01:00
if ($user->save($sql, ["confirmed"])) {
2022-11-19 01:15:34 +01:00
$userToken->invalidate($sql);
2020-07-01 23:07:00 +02:00
return true;
2022-11-19 01:15:34 +01:00
} else {
return $this->createError("Unable to update user details: " . $sql->getLastError());
2020-07-01 23:07:00 +02:00
}
2020-06-29 16:47:02 +02:00
}
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to confirm their email";
}
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
class Login extends UserAPI {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall, array(
2021-12-08 16:53:43 +01:00
'username' => new StringType('username'),
2020-06-22 21:50:58 +02:00
'password' => new StringType('password'),
2022-02-20 16:53:26 +01:00
'stayLoggedIn' => new Parameter('stayLoggedIn', Parameter::TYPE_BOOLEAN, true, false)
2020-06-22 21:50:58 +02:00
));
$this->forbidMethod("GET");
2024-04-23 20:14:32 +02:00
$this->rateLimiting = new RateLimiting(
new RateLimitRule(10, 30, RateLimitRule::SECOND)
);
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-22 21:50:58 +02:00
$this->lastError = L('You are already logged in');
$this->success = true;
2023-01-16 21:47:23 +01:00
$tfaToken = $this->context->getUser()->getTwoFactorToken();
if ($tfaToken && $tfaToken->isConfirmed() && !$tfaToken->isAuthenticated()) {
$this->result["twoFactorToken"] = $tfaToken->jsonSerialize([
"type", "challenge", "authenticated", "confirmed", "credentialID"
]);
}
2020-06-22 21:50:58 +02:00
return true;
}
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
$this->success = false;
$username = $this->getParam('username');
$password = $this->getParam('password');
$stayLoggedIn = $this->getParam('stayLoggedIn');
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2022-11-20 17:13:53 +01:00
$user = User::findBy(User::createBuilder($sql, true)
2021-12-08 16:53:43 +01:00
->where(new Compare("User.name", $username), new Compare("User.email", $username))
2022-11-20 17:13:53 +01:00
->fetchEntities());
2020-06-22 21:50:58 +02:00
2022-11-19 01:15:34 +01:00
if ($user !== false) {
if ($user === null) {
2024-04-23 20:14:32 +02:00
return $this->createError(L('Wrong username or password'));
} else if (!$user->isActive()) {
return $this->createError("This user is currently disabled. Contact the server administrator, if you believe this is a mistake.");
} else if (password_verify($password, $user->password)) {
if (!$user->confirmed) {
$this->result["emailConfirmed"] = false;
return $this->createError("Your email address has not been confirmed yet.");
} else if (!($session = $this->context->createSession($user, $stayLoggedIn))) {
return $this->createError("Error creating Session: " . $sql->getLastError());
2020-06-20 20:13:51 +02:00
} else {
$tfaToken = $user->getTwoFactorToken();
$this->result["loggedIn"] = true;
$this->result["user"] = $user->jsonSerialize();
2024-04-07 18:29:33 +02:00
$this->result["session"] = $session->jsonSerialize(["expires", "csrfToken"]);
$this->result["logoutIn"] = $session->getExpiresSeconds();
$this->check2FA($tfaToken);
$this->success = true;
2020-06-20 20:13:51 +02:00
}
} else {
2024-04-23 20:14:32 +02:00
return $this->createError(L('Wrong username or password'));
2020-06-20 20:13:51 +02:00
}
2022-11-19 01:15:34 +01:00
} else {
return $this->createError("Error fetching user details: " . $sql->getLastError());
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Creates a new session identified by the session cookie";
}
public static function hasConfigurablePermissions(): bool {
return false;
}
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
class Logout extends UserAPI {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
parent::__construct($context, $externalCall);
2022-02-20 16:53:26 +01:00
$this->loginRequired = false;
2020-06-22 21:50:58 +02:00
$this->apiKeyAllowed = false;
2022-02-20 16:53:26 +01:00
$this->forbidMethod("GET");
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
$session = $this->context->getSession();
if (!$session) {
2022-02-20 16:53:26 +01:00
return $this->createError("You are not logged in.");
}
2022-06-20 19:52:31 +02:00
$this->success = $session->destroy();
$this->lastError = $this->context->getSQL()->getLastError();
2020-06-22 21:50:58 +02:00
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Destroys the current session and logs the user out";
}
public static function hasConfigurablePermissions(): bool {
return false;
}
2020-06-20 20:13:51 +02:00
}
2020-06-22 21:50:58 +02:00
class Register extends UserAPI {
2020-06-20 20:13:51 +02:00
2024-05-03 19:05:43 +02:00
use Captcha;
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
2020-06-26 23:32:45 +02:00
$parameters = array(
2020-06-22 21:50:58 +02:00
"username" => new StringType("username", 32),
2024-03-27 20:50:57 +01:00
"email" => new Parameter("email", Parameter::TYPE_EMAIL),
2020-06-22 21:50:58 +02:00
"password" => new StringType("password"),
"confirmPassword" => new StringType("confirmPassword"),
2020-06-26 23:32:45 +02:00
);
$this->addCaptchaParameters($context, $parameters);
2022-06-20 19:52:31 +02:00
parent::__construct($context, $externalCall, $parameters);
2020-07-01 22:13:50 +02:00
$this->csrfTokenRequired = false;
2020-06-20 20:13:51 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-26 01:47:43 +02:00
return $this->createError(L('You are already logged in'));
}
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
$registrationAllowed = $settings->isRegistrationAllowed();
if (!$registrationAllowed) {
2020-06-26 01:47:43 +02:00
return $this->createError("User Registration is not enabled.");
}
2024-05-03 19:05:43 +02:00
if (!$this->checkCaptcha("register")) {
return false;
2020-06-26 23:32:45 +02:00
}
2020-06-22 21:50:58 +02:00
$username = $this->getParam("username");
$email = $this->getParam('email');
2020-06-29 16:47:02 +02:00
$password = $this->getParam("password");
$confirmPassword = $this->getParam("confirmPassword");
2022-03-08 11:50:18 +01:00
if (!$this->checkUserExists($username, $email)) {
2020-06-22 21:50:58 +02:00
return false;
}
2020-06-20 20:13:51 +02:00
2022-06-20 19:52:31 +02:00
if (!$this->checkRequirements($username, $password, $confirmPassword)) {
2020-06-29 16:47:02 +02:00
return false;
2020-06-22 21:50:58 +02:00
}
2022-02-20 16:53:26 +01:00
$fullName = substr($email, 0, strrpos($email, "@"));
$fullName = implode(" ", array_map(function ($part) {
2022-06-20 19:52:31 +02:00
return ucfirst(strtolower($part));
2022-02-20 16:53:26 +01:00
}, explode(".", $fullName))
);
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
$user = $this->insertUser($username, $email, $password, false, $fullName);
if ($user === false) {
2020-06-22 21:50:58 +02:00
return false;
}
2024-04-05 14:17:50 +02:00
$this->logger->info("A new user with username='$username' and email='$email' was created");
2021-12-08 16:53:43 +01:00
$validHours = 48;
2022-11-19 01:15:34 +01:00
$token = generateRandomString(36);
$userToken = new UserToken($user, $token, UserToken::TYPE_EMAIL_CONFIRM, $validHours);
if ($userToken->save($sql)) {
2020-06-26 18:24:23 +02:00
2021-12-08 16:53:43 +01:00
$baseUrl = $settings->getBaseUrl();
$siteName = $settings->getSiteName();
2022-06-20 19:52:31 +02:00
$req = new Render($this->context);
2021-12-08 16:53:43 +01:00
$this->success = $req->execute([
"file" => "mail/confirm_email.twig",
"parameters" => [
2022-11-19 01:15:34 +01:00
"link" => "$baseUrl/confirmEmail?token=$token",
2020-07-01 22:13:50 +02:00
"site_name" => $siteName,
"base_url" => $baseUrl,
2021-12-08 16:53:43 +01:00
"username" => $username,
"valid_time" => $this->formatDuration($validHours, "hour")
]
]);
$this->lastError = $req->getLastError();
2020-06-26 18:24:23 +02:00
2021-12-08 16:53:43 +01:00
if ($this->success) {
$messageBody = $req->getResult()["html"];
2022-11-18 18:06:46 +01:00
$request = new \Core\API\Mail\Send($this->context);
2020-07-01 22:13:50 +02:00
$this->success = $request->execute(array(
2020-06-26 18:24:23 +02:00
"to" => $email,
"subject" => "[$siteName] E-Mail Confirmation",
2022-05-31 16:14:49 +02:00
"body" => $messageBody,
2020-07-01 22:13:50 +02:00
));
$this->lastError = $request->getLastError();
}
2022-11-19 01:15:34 +01:00
} else {
2024-04-05 14:17:50 +02:00
$this->lastError = "Could not create user token: " . $sql->getLastError();
2022-11-19 01:15:34 +01:00
$this->success = false;
2020-06-26 18:24:23 +02:00
}
2020-06-20 20:13:51 +02:00
2020-06-22 21:50:58 +02:00
if (!$this->success) {
2024-04-05 14:17:50 +02:00
$this->logger->error("Could not deliver email to='$email' type='register' reason='" . $this->lastError . "'");
2020-06-22 21:50:58 +02:00
$this->lastError = "Your account was registered but the confirmation email could not be sent. " .
2022-05-31 16:14:49 +02:00
"Please contact the server administration. This issue has been automatically logged. Reason: " . $this->lastError;
2020-06-22 21:50:58 +02:00
}
2020-06-20 20:13:51 +02:00
2022-11-19 01:15:34 +01:00
$this->logger->info("Registered new user with id=" . $user->getId());
2020-06-22 21:50:58 +02:00
return $this->success;
2020-06-22 21:03:30 +02:00
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to register a new account";
}
2020-06-22 21:50:58 +02:00
}
2020-06-22 21:03:30 +02:00
2020-06-23 17:55:52 +02:00
class Edit extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-23 17:55:52 +02:00
'id' => new Parameter('id', Parameter::TYPE_INT),
'username' => new StringType('username', 32, true, NULL),
2021-12-08 16:53:43 +01:00
'fullName' => new StringType('fullName', 64, true, NULL),
2020-06-24 01:09:08 +02:00
'email' => new Parameter('email', Parameter::TYPE_EMAIL, true, NULL),
2020-06-23 17:55:52 +02:00
'password' => new StringType('password', -1, true, NULL),
2024-03-27 20:50:57 +01:00
'groups' => new ArrayType('groups', Parameter::TYPE_INT, true, true, NULL),
2024-05-03 19:05:43 +02:00
'confirmed' => new Parameter('confirmed', Parameter::TYPE_BOOLEAN, true, NULL),
'active' => new Parameter('active', Parameter::TYPE_BOOLEAN, true, NULL)
2020-06-23 17:55:52 +02:00
));
$this->loginRequired = true;
2021-11-11 14:25:26 +01:00
$this->forbidMethod("GET");
2020-06-23 17:55:52 +02:00
}
2020-06-22 21:15:41 +02:00
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-23 17:55:52 +02:00
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
$currentUser = $this->context->getUser();
2020-06-23 17:55:52 +02:00
$id = $this->getParam("id");
2022-11-19 01:15:34 +01:00
$user = User::find($sql, $id, true);
2020-06-23 17:55:52 +02:00
2022-11-19 01:15:34 +01:00
if ($user !== false) {
if ($user === null) {
2020-06-23 17:55:52 +02:00
return $this->createError("User not found");
}
2024-05-04 11:18:28 +02:00
$columnsToUpdate = [];
2020-06-23 17:55:52 +02:00
$username = $this->getParam("username");
2021-12-08 16:53:43 +01:00
$fullName = $this->getParam("fullName");
2020-06-23 17:55:52 +02:00
$email = $this->getParam("email");
$password = $this->getParam("password");
$groups = $this->getParam("groups");
2020-07-02 00:47:45 +02:00
$confirmed = $this->getParam("confirmed");
2024-05-03 19:05:43 +02:00
$active = $this->getParam("active");
2020-06-23 21:18:45 +02:00
$email = (!is_null($email) && empty($email)) ? null : $email;
2020-06-23 17:55:52 +02:00
if (!is_null($groups)) {
2024-03-27 20:50:57 +01:00
$groupIds = array_unique($groups);
2022-11-20 17:13:53 +01:00
if ($id === $currentUser->getId() && !in_array(Group::ADMIN, $groupIds)) {
2020-06-23 17:55:52 +02:00
return $this->createError("Cannot remove Administrator group from own user.");
2024-03-27 20:50:57 +01:00
} else if (in_array(Group::ADMIN, $groupIds) && !$currentUser->hasGroup(Group::ADMIN)) {
return $this->createError("You cannot add the administrator group to other users.");
}
$availableGroups = Group::findAll($sql, new CondIn(new Column("id"), $groupIds));
foreach ($groupIds as $groupId) {
if (!isset($availableGroups[$groupId])) {
return $this->createError("Group with id=$groupId does not exist.");
}
2020-06-23 17:55:52 +02:00
}
2024-05-04 11:18:28 +02:00
$user->groups = $groupIds;
$columnsToUpdate[] = "groups";
2020-06-23 17:55:52 +02:00
}
// Check for duplicate username, email
2022-11-19 01:15:34 +01:00
$usernameChanged = !is_null($username) && strcasecmp($username, $user->name) !== 0;
$fullNameChanged = !is_null($fullName) && strcasecmp($fullName, $user->fullName) !== 0;
$emailChanged = !is_null($email) && strcasecmp($email, $user->email) !== 0;
2022-06-20 19:52:31 +02:00
if ($usernameChanged || $emailChanged) {
2022-03-08 11:50:18 +01:00
if (!$this->checkUserExists($usernameChanged ? $username : NULL, $emailChanged ? $email : NULL)) {
2020-06-23 17:55:52 +02:00
return false;
}
}
2022-11-29 14:17:11 +01:00
if ($usernameChanged) {
$user->name = $username;
$columnsToUpdate[] = "name";
}
if ($fullNameChanged) {
$user->fullName = $fullName;
$columnsToUpdate[] = "full_name";
}
if ($emailChanged) {
$user->email = $email;
$columnsToUpdate[] = "email";
}
if (!is_null($password)) {
$user->password = $this->hashPassword($password);
$columnsToUpdate[] = "password";
}
2020-06-23 17:55:52 +02:00
2020-07-02 00:47:45 +02:00
if (!is_null($confirmed)) {
2022-11-19 01:15:34 +01:00
if ($id === $currentUser->getId() && $confirmed === false) {
2024-05-03 19:05:43 +02:00
return $this->createError("Cannot change confirmed flag on own account.");
2020-07-02 00:47:45 +02:00
} else {
2022-11-19 01:15:34 +01:00
$user->confirmed = $confirmed;
2022-11-29 14:17:11 +01:00
$columnsToUpdate[] = "confirmed";
2020-07-02 00:47:45 +02:00
}
}
2024-05-03 19:05:43 +02:00
if (!is_null($active)) {
if ($id === $currentUser->getId() && $active === false) {
return $this->createError("Cannot change active flag on own account.");
} else {
$user->active = $active;
$columnsToUpdate[] = "active";
}
}
2024-05-04 11:18:28 +02:00
if (!empty($columnsToUpdate)) {
$this->success = $user->save($sql, $columnsToUpdate, in_array("groups", $columnsToUpdate)) !== FALSE;
2020-06-23 17:55:52 +02:00
$this->lastError = $sql->getLastError();
}
2024-05-04 11:18:28 +02:00
2022-11-19 01:15:34 +01:00
} else {
return $this->createError("Error fetching user details: " . $sql->getLastError());
2020-06-23 17:55:52 +02:00
}
return $this->success;
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to modify other user's details";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN];
2023-01-16 21:47:23 +01:00
}
2020-06-23 17:55:52 +02:00
}
class Delete extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, array(
'id' => new Parameter('id', Parameter::TYPE_INT)
));
$this->loginRequired = true;
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2022-11-19 01:15:34 +01:00
$currentUser = $this->context->getUser();
$id = $this->getParam("id");
2022-11-19 01:15:34 +01:00
if ($id === $currentUser->getId()) {
return $this->createError("You cannot delete your own user.");
}
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
$user = User::find($sql, $id);
if ($user !== false) {
if ($user === null) {
return $this->createError("User not found");
} else {
2022-06-20 19:52:31 +02:00
$this->success = ($user->delete($sql) !== FALSE);
$this->lastError = $sql->getLastError();
}
}
return $this->success;
}
2023-01-16 21:47:23 +01:00
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to delete other users";
}
public static function getDefaultPermittedGroups(): array {
return [Group::ADMIN];
2023-01-16 21:47:23 +01:00
}
}
2020-06-29 16:47:02 +02:00
2020-07-02 00:47:45 +02:00
class RequestPasswordReset extends UserAPI {
2024-05-03 19:05:43 +02:00
use Captcha;
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
2024-05-03 19:05:43 +02:00
$parameters = [
2020-06-29 16:47:02 +02:00
'email' => new Parameter('email', Parameter::TYPE_EMAIL),
2024-05-03 19:05:43 +02:00
];
2020-06-29 16:47:02 +02:00
$this->addCaptchaParameters($context, $parameters);
2022-06-20 19:52:31 +02:00
parent::__construct($context, $externalCall, $parameters);
2020-06-29 16:47:02 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-29 16:47:02 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-29 16:47:02 +02:00
return $this->createError("You already logged in.");
}
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
2022-06-01 09:47:31 +02:00
if (!$settings->isMailEnabled()) {
return $this->createError("The mail service is not enabled, please contact the server administration.");
}
2024-05-03 19:05:43 +02:00
if (!$this->checkCaptcha("resetPassword")) {
return false;
2020-06-29 16:47:02 +02:00
}
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
2020-06-29 16:47:02 +02:00
$email = $this->getParam("email");
2022-11-20 17:13:53 +01:00
$user = User::findBy(User::createBuilder($sql, true)
->whereEq("email", $email)
2022-11-20 17:13:53 +01:00
->fetchEntities());
2022-11-19 01:15:34 +01:00
if ($user === false) {
return $this->createError("Could not fetch user details: " . $sql->getLastError());
} else if ($user !== null) {
if (!$user->isActive()) {
return $this->createError("This user is currently disabled. Contact the server administrator, if you believe this is a mistake.");
} else {
$validHours = 1;
$token = generateRandomString(36);
$userToken = new UserToken($user, $token, UserToken::TYPE_PASSWORD_RESET, $validHours);
if (!$userToken->save($sql)) {
return $this->createError("Could not create user token: " . $sql->getLastError());
}
2022-02-20 16:53:26 +01:00
$baseUrl = $settings->getBaseUrl();
$siteName = $settings->getSiteName();
$req = new Render($this->context);
$this->success = $req->execute([
"file" => "mail/reset_password.twig",
"parameters" => [
"link" => "$baseUrl/resetPassword?token=$token",
"site_name" => $siteName,
"base_url" => $baseUrl,
"username" => $user->name,
"valid_time" => $this->formatDuration($validHours, "hour")
]
]);
$this->lastError = $req->getLastError();
if ($this->success) {
$messageBody = $req->getResult()["html"];
$gpgKey = $user->getGPG();
$gpgFingerprint = ($gpgKey && $gpgKey->isConfirmed()) ? $gpgKey->getFingerprint() : null;
$request = new \Core\API\Mail\Send($this->context);
$this->success = $request->execute(array(
"to" => $email,
"subject" => "[$siteName] Password Reset",
"body" => $messageBody,
"gpgFingerprint" => $gpgFingerprint
));
$this->lastError = $request->getLastError();
2024-04-05 14:17:50 +02:00
$this->logger->info("Requested password reset for user id='" . $user->getId() . "' by ip_address='" . $_SERVER["REMOTE_ADDR"] . "'");
}
2020-06-29 16:47:02 +02:00
}
}
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to request a password reset link";
}
2021-11-11 14:25:26 +01:00
}
class ResendConfirmEmail extends UserAPI {
2024-05-03 19:05:43 +02:00
use Captcha;
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
2021-11-11 14:25:26 +01:00
$parameters = array(
'email' => new Parameter('email', Parameter::TYPE_EMAIL),
);
$this->addCaptchaParameters($context, $parameters);
2022-06-20 19:52:31 +02:00
parent::__construct($context, $externalCall, $parameters);
2021-11-11 14:25:26 +01:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2021-11-11 14:25:26 +01:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2021-11-11 14:25:26 +01:00
return $this->createError("You already logged in.");
}
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
2024-05-03 19:05:43 +02:00
if (!$this->checkCaptcha("resendConfirmation")) {
return false;
2021-11-11 14:25:26 +01:00
}
$email = $this->getParam("email");
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2022-11-20 17:13:53 +01:00
$user = User::findBy(User::createBuilder($sql, true)
->whereEq("User.email", $email)
->whereFalse("User.confirmed"));
2020-06-29 16:47:02 +02:00
2022-11-19 01:15:34 +01:00
if ($user === false) {
return $this->createError("Error retrieving user details: " . $sql->getLastError());
} else if ($user === null) {
// token does not exist: ignore!
2021-11-11 14:25:26 +01:00
return true;
}
2022-11-20 17:13:53 +01:00
$userToken = UserToken::findBy(UserToken::createBuilder($sql, true)
->whereFalse("used")
2023-03-05 15:30:06 +01:00
->whereEq("token_type", UserToken::TYPE_EMAIL_CONFIRM)
->whereEq("user_id", $user->getId()));
2021-11-11 14:25:26 +01:00
2021-12-08 16:53:43 +01:00
$validHours = 48;
2022-11-19 01:15:34 +01:00
if ($userToken === false) {
return $this->createError("Error retrieving token details: " . $sql->getLastError());
} else if ($userToken === null) {
2021-11-11 14:25:26 +01:00
// no token generated yet, let's generate one
$token = generateRandomString(36);
2022-11-19 01:15:34 +01:00
$userToken = new UserToken($user, $token, UserToken::TYPE_EMAIL_CONFIRM, $validHours);
if (!$userToken->save($sql)) {
return $this->createError("Error generating new token: " . $sql->getLastError());
2021-11-11 14:25:26 +01:00
}
2021-12-08 16:53:43 +01:00
} else {
2022-11-19 01:15:34 +01:00
$userToken->updateDurability($sql, $validHours);
2021-11-11 14:25:26 +01:00
}
2022-11-19 01:15:34 +01:00
$username = $user->name;
2021-12-08 16:53:43 +01:00
$baseUrl = $settings->getBaseUrl();
$siteName = $settings->getSiteName();
2022-06-20 19:52:31 +02:00
$req = new Render($this->context);
2021-12-08 16:53:43 +01:00
$this->success = $req->execute([
"file" => "mail/confirm_email.twig",
"parameters" => [
2022-11-19 01:15:34 +01:00
"link" => "$baseUrl/confirmEmail?token=" . $userToken->getToken(),
2021-12-08 16:53:43 +01:00
"site_name" => $siteName,
"base_url" => $baseUrl,
"username" => $username,
"valid_time" => $this->formatDuration($validHours, "hour")
]
]);
$this->lastError = $req->getLastError();
2021-11-11 14:25:26 +01:00
2021-12-08 16:53:43 +01:00
if ($this->success) {
$messageBody = $req->getResult()["html"];
2022-11-18 18:06:46 +01:00
$request = new \Core\API\Mail\Send($this->context);
2021-12-08 16:53:43 +01:00
$this->success = $request->execute(array(
"to" => $email,
"subject" => "[$siteName] E-Mail Confirmation",
"body" => $messageBody
));
2021-11-11 14:25:26 +01:00
2021-12-08 16:53:43 +01:00
$this->lastError = $request->getLastError();
}
2021-11-11 14:25:26 +01:00
2020-06-29 16:47:02 +02:00
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to request a new e-mail confirmation link";
}
2020-06-29 16:47:02 +02:00
}
class ResetPassword extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, $externalCall = false) {
2024-04-23 20:14:32 +02:00
parent::__construct($context, $externalCall, [
2020-06-29 16:47:02 +02:00
'token' => new StringType('token', 36),
'password' => new StringType('password'),
'confirmPassword' => new StringType('confirmPassword'),
2024-04-23 20:14:32 +02:00
]);
2020-07-02 00:47:45 +02:00
2024-04-23 20:14:32 +02:00
$this->forbidMethod("GET");
2020-07-02 00:47:45 +02:00
$this->csrfTokenRequired = false;
2024-04-23 12:14:28 +02:00
$this->apiKeyAllowed = false;
2024-04-23 20:14:32 +02:00
$this->rateLimiting = new RateLimiting(
new RateLimitRule(5, 1, RateLimitRule::MINUTE)
);
2020-06-29 16:47:02 +02:00
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2020-06-29 16:47:02 +02:00
2022-06-20 19:52:31 +02:00
if ($this->context->getUser()) {
2020-06-29 16:47:02 +02:00
return $this->createError("You are already logged in.");
}
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
2020-06-29 16:47:02 +02:00
$token = $this->getParam("token");
$password = $this->getParam("password");
$confirmPassword = $this->getParam("confirmPassword");
2022-11-19 01:15:34 +01:00
$userToken = $this->checkToken($token);
if ($userToken === false) {
2020-06-29 16:47:02 +02:00
return false;
2022-11-19 01:15:34 +01:00
} else if ($userToken->getType() !== UserToken::TYPE_PASSWORD_RESET) {
return $this->createError("Invalid token type");
2020-06-29 16:47:02 +02:00
}
2022-11-19 01:15:34 +01:00
$user = $token->getUser();
if (!$this->checkPasswordRequirements($password, $confirmPassword)) {
2020-06-29 16:47:02 +02:00
return false;
} else {
2022-11-19 01:15:34 +01:00
$user->password = $this->hashPassword($password);
if ($user->save($sql)) {
$this->logger->info("Issued password reset for user id=" . $user->getId());
$userToken->invalidate($sql);
$this->context->invalidateSessions(false);
2022-11-19 01:15:34 +01:00
return true;
} else {
return $this->createError("Error updating user details: " . $sql->getLastError());
}
2020-06-29 16:47:02 +02:00
}
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to reset their password with a token received by a password reset email";
}
2020-06-29 16:47:02 +02:00
}
2021-11-11 14:25:26 +01:00
class UpdateProfile extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, array(
2021-11-11 14:25:26 +01:00
'username' => new StringType('username', 32, true, NULL),
2021-12-08 16:53:43 +01:00
'fullName' => new StringType('fullName', 64, true, NULL),
2021-11-11 14:25:26 +01:00
'password' => new StringType('password', -1, true, NULL),
2021-12-08 16:53:43 +01:00
'confirmPassword' => new StringType('confirmPassword', -1, true, NULL),
'oldPassword' => new StringType('oldPassword', -1, true, NULL),
2021-11-11 14:25:26 +01:00
));
$this->loginRequired = true;
$this->csrfTokenRequired = true;
2024-04-23 12:14:28 +02:00
$this->apiKeyAllowed = false; // prevent account takeover when an API-key is stolen
2021-11-11 14:25:26 +01:00
$this->forbidMethod("GET");
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2021-11-11 14:25:26 +01:00
$newUsername = $this->getParam("username");
2021-12-08 16:53:43 +01:00
$oldPassword = $this->getParam("oldPassword");
2021-11-11 14:25:26 +01:00
$newPassword = $this->getParam("password");
2021-12-08 16:53:43 +01:00
$newPasswordConfirm = $this->getParam("confirmPassword");
$newFullName = $this->getParam("fullName");
2021-11-11 14:25:26 +01:00
2021-12-08 16:53:43 +01:00
if ($newUsername === null && $newPassword === null && $newPasswordConfirm === null && $newFullName === null) {
return $this->createError("You must either provide an updated username, fullName or password");
2021-11-11 14:25:26 +01:00
}
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
$updateFields = [];
2022-11-19 01:15:34 +01:00
$currentUser = $this->context->getUser();
2021-11-11 14:25:26 +01:00
if ($newUsername !== null) {
2022-03-08 11:50:18 +01:00
if (!$this->checkUsernameRequirements($newUsername) || !$this->checkUserExists($newUsername)) {
2021-11-11 14:25:26 +01:00
return false;
} else {
2022-11-19 01:15:34 +01:00
$currentUser->name = $newUsername;
$updateFields[] = "name";
2021-11-11 14:25:26 +01:00
}
}
2021-12-08 16:53:43 +01:00
if ($newFullName !== null) {
2022-11-19 01:15:34 +01:00
$currentUser->fullName = $newFullName;
$updateFields[] = "fullName";
2021-12-08 16:53:43 +01:00
}
if ($newPassword !== null || $newPasswordConfirm !== null) {
if (!$this->checkPasswordRequirements($newPassword, $newPasswordConfirm)) {
2021-11-11 14:25:26 +01:00
return false;
} else {
2022-11-19 01:15:34 +01:00
if (!password_verify($oldPassword, $currentUser->password)) {
2021-12-08 16:53:43 +01:00
return $this->createError("Wrong password");
}
2022-11-19 01:15:34 +01:00
$currentUser->password = $this->hashPassword($newPassword);
$updateFields[] = "password";
2021-11-11 14:25:26 +01:00
}
}
if (!empty($updateFields)) {
$this->success = $currentUser->save($sql, $updateFields) !== false;
$this->lastError = $sql->getLastError();
if ($this->success && in_array("password", $updateFields)) {
$this->context->invalidateSessions(true);
}
}
2021-11-11 14:25:26 +01:00
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to update their profiles.";
}
2021-11-11 14:25:26 +01:00
}
2021-12-08 16:53:43 +01:00
class UploadPicture extends UserAPI {
2024-05-03 20:22:58 +02:00
const MIN_SIZE = 150;
const MAX_SIZE = 800;
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, [
2024-05-03 20:22:58 +02:00
"x" => new FloatType("x", 0, PHP_FLOAT_MAX, true, NULL),
"y" => new FloatType("y", 0, PHP_FLOAT_MAX, true, NULL),
"size" => new FloatType("size", self::MIN_SIZE, self::MAX_SIZE, true, NULL),
2021-12-08 16:53:43 +01:00
]);
$this->loginRequired = true;
$this->forbidMethod("GET");
}
/**
* @throws ImagickException
*/
protected function onTransform(\Imagick $im, $uploadDir): bool|string {
2021-12-08 16:53:43 +01:00
$width = $im->getImageWidth();
$height = $im->getImageHeight();
2024-05-03 20:22:58 +02:00
$maxPossibleSize = min($width, $height);
$cropX = $this->getParam("x");
$cropY = $this->getParam("y");
$cropSize = $this->getParam("size") ?? $maxPossibleSize;
if ($maxPossibleSize < self::MIN_SIZE) {
return $this->createError("Image must be at least " . self::MIN_SIZE . "x" . self::MIN_SIZE);
} else if ($cropSize > self::MAX_SIZE) {
return $this->createError("Crop must be at most " . self::MAX_SIZE . "x" . self::MAX_SIZE);
} else if ($cropSize > $maxPossibleSize) {
return $this->createError("Invalid crop size");
2021-12-08 16:53:43 +01:00
}
2024-05-03 20:22:58 +02:00
if ($cropX === null) {
$cropX = ($width > $height) ? ($width - $height) / 2 : 0;
2021-12-08 16:53:43 +01:00
}
2024-05-03 20:22:58 +02:00
if ($cropY === null) {
$cropY = ($height > $width) ? ($height - $width) / 2 : 0;
2021-12-08 16:53:43 +01:00
}
2024-05-03 20:22:58 +02:00
$im->cropImage($cropSize, $cropSize, $cropX, $cropY);
2021-12-08 16:53:43 +01:00
$fileName = uuidv4() . ".jpg";
$im->writeImage("$uploadDir/$fileName");
$im->destroy();
return $fileName;
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2021-12-08 16:53:43 +01:00
2022-06-20 19:52:31 +02:00
$currentUser = $this->context->getUser();
$userId = $currentUser->getId();
2021-12-08 16:53:43 +01:00
$uploadDir = WEBROOT . "/img/uploads/user/$userId";
2022-06-20 19:52:31 +02:00
list ($fileName, $imageName) = $this->processImageUpload($uploadDir, ["png", "jpg", "jpeg"], "onTransform");
2021-12-08 16:53:43 +01:00
if (!$this->success) {
return false;
}
2022-06-20 19:52:31 +02:00
$oldPfp = $currentUser->getProfilePicture();
2024-05-04 11:18:28 +02:00
if ($oldPfp && preg_match("/[a-fA-F0-9-]+\.(jpg|jpeg|png|gif)/", $oldPfp)) {
2021-12-08 16:53:43 +01:00
$path = "$uploadDir/$oldPfp";
if (is_file($path)) {
@unlink($path);
}
}
2022-06-20 19:52:31 +02:00
$sql = $this->context->getSQL();
2022-11-19 01:15:34 +01:00
$currentUser->profilePicture = $fileName;
2023-01-09 14:21:11 +01:00
if ($currentUser->save($sql, ["profilePicture"])) {
2021-12-08 16:53:43 +01:00
$this->result["profilePicture"] = $fileName;
2022-11-19 01:15:34 +01:00
} else {
return $this->createError("Error updating user details: " . $sql->getLastError());
2021-12-08 16:53:43 +01:00
}
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to upload and change their profile pictures.";
}
2021-12-08 16:53:43 +01:00
}
class RemovePicture extends UserAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, []);
2021-12-08 16:53:43 +01:00
$this->loginRequired = true;
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2021-12-08 16:53:43 +01:00
2022-11-19 01:15:34 +01:00
$sql = $this->context->getSQL();
2022-06-20 19:52:31 +02:00
$currentUser = $this->context->getUser();
2022-11-19 01:15:34 +01:00
$userId = $currentUser->getId();
2022-06-20 19:52:31 +02:00
$pfp = $currentUser->getProfilePicture();
2021-12-08 16:53:43 +01:00
if (!$pfp) {
return $this->createError("You did not upload a profile picture yet");
}
2022-11-19 01:15:34 +01:00
$currentUser->profilePicture = null;
2023-01-09 14:21:11 +01:00
if (!$currentUser->save($sql, ["profilePicture"])) {
2022-11-19 01:15:34 +01:00
return $this->createError("Error updating user details: " . $sql->getLastError());
}
2021-12-08 16:53:43 +01:00
2024-05-04 11:18:28 +02:00
if (preg_match("/[a-fA-F0-9-]+\.(jpg|jpeg|png|gif)/", $pfp)) {
$path = WEBROOT . "/img/uploads/user/$userId/$pfp";
if (is_file($path)) {
@unlink($path);
}
2021-12-08 16:53:43 +01:00
}
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to remove their profile pictures.";
}
2021-12-08 16:53:43 +01:00
}
2022-11-30 16:42:24 +01:00
class CheckToken extends UserAPI {
private ?UserToken $userToken;
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
'token' => new StringType('token', 36),
));
$this->userToken = null;
2024-04-24 16:02:16 +02:00
$this->rateLimiting = new RateLimiting(
new RateLimitRule(10, 30, RateLimitRule::SECOND),
new RateLimitRule(30, 1, RateLimitRule::MINUTE),
);
2022-11-30 16:42:24 +01:00
}
public function getToken(): ?UserToken {
return $this->userToken;
}
public function _execute(): bool {
$token = $this->getParam('token');
$userToken = $this->checkToken($token);
if ($userToken === false) {
return false;
}
$this->userToken = $userToken;
$this->result["token"] = $userToken->jsonSerialize();
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Allows users to validate a token received in an e-mail for various purposes";
}
2022-11-30 16:42:24 +01:00
}
2020-06-20 20:13:51 +02:00
}