Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use baraja-core/cas #63

Merged
merged 9 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
"require": {
"php": "^8.0",
"composer-runtime-api": "^2.0.0",
"baraja-core/cas": "^1.0",
"baraja-core/dynamic-configuration": "^2.1",
"baraja-core/doctrine": "^3.0",
"baraja-core/structured-api": "^4.0 <4.1",
"baraja-core/structured-api": "^4.1",
"baraja-core/admin-bar": "^2.3",
"baraja-core/plugin-system": "^2.3",
"baraja-core/localization": "^2.0",
Expand All @@ -29,7 +30,6 @@
"guzzlehttp/psr7": "^2.0",
"nette/di": "^3.0",
"latte/latte": "^2.5",
"nette/security": "^3.1",
"nette/utils": "^3.0",
"nette/http": "^3.1",
"nette/caching": "^3.0",
Expand All @@ -50,7 +50,6 @@
"roave/security-advisories": "dev-master"
},
"conflict": {
"nette/security": "<3.1.2",
"nette/http": "<3.1",
"baraja-core/admin-bar": "<2.1"
},
Expand Down
16 changes: 3 additions & 13 deletions src/Admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@

final class Admin
{
/** @deprecated since 2021-10-20, use Configuration::get()->getSupportedLocales() instead. */
public const SUPPORTED_LOCALES = ['cs', 'en'];

private Application $application;


Expand All @@ -42,7 +39,7 @@ public function __construct(
Debugger::getBar()->addPanel($context->getContainer()->getPluginPanel());
}
if (function_exists('Sentry\configureScope')) {
(new SentryBridge($context->getUserManager()->get(), $this->context))->register();
(new SentryBridge($context->getUser(), $this->context))->register();
}
}

Expand All @@ -59,19 +56,12 @@ public static function isAdminRequest(): bool
/**
* @return never-return
*/
public function run(?string $locale = null, ?string $path = null): void
public function run(): void
{
if (PHP_SAPI === 'cli') {
throw new \RuntimeException('CMS is not available in CLI.');
}
if ($locale !== null) {
trigger_error('Argument $locale is deprecated. Please remove it from your implementation.');
}
if ($path !== null) {
trigger_error('Argument $path is deprecated. Please remove it from your implementation.');
} else {
$path = Url::get()->getRelativeUrl();
}
$path = Url::get()->getRelativeUrl();
if (self::isAdminRequest() === false) {
throw new \LogicException(sprintf('Path "%s" is not a admin request.', $path));
}
Expand Down
10 changes: 5 additions & 5 deletions src/Announcement/Entity/Announcement.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace Baraja\Cms\Announcement\Entity;


use Baraja\Cms\User\Entity\User;
use Baraja\CAS\Entity\User;
use Baraja\Localization\Localization;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
Expand All @@ -26,9 +26,9 @@ class Announcement
#[ORM\ManyToOne(targetEntity: self::class, inversedBy: 'children')]
private ?self $parent;

/** @var self[]|Collection */
/** @var Collection<self> */
#[ORM\OneToMany(mappedBy: 'parent', targetEntity: self::class)]
private $children;
private Collection $children;

#[ORM\Column(type: 'string', length: 2, nullable: true)]
private ?string $locale;
Expand Down Expand Up @@ -79,9 +79,9 @@ public function getParent(): ?self


/**
* @return self[]|Collection
* @return Collection<self>
*/
public function getChildren()
public function getChildren(): Collection
{
return $this->children;
}
Expand Down
56 changes: 26 additions & 30 deletions src/Api/CmsDashboardEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,62 +5,58 @@
namespace Baraja\Cms\Api;


use Baraja\CAS\User;
use Baraja\Cms\Announcement\Entity\Announcement;
use Baraja\Cms\Announcement\Entity\AnnouncementRepository;
use Baraja\Cms\User\Entity\User;
use Baraja\Cms\User\UserManager;
use Baraja\Localization\Localization;
use Baraja\StructuredApi\BaseEndpoint;
use Doctrine\ORM\EntityManagerInterface;

final class CmsDashboardEndpoint extends BaseEndpoint
{
private AnnouncementRepository $repository;


public function __construct(
private EntityManagerInterface $entityManager,
private UserManager $userManager,
private User $userService,
private Localization $localization,
) {
$repository = $this->entityManager->getRepository(Announcement::class);
assert($repository instanceof AnnouncementRepository);
$this->repository = $repository;
}


public function actionFeed(): void
{
/** @var AnnouncementRepository $repository */
$repository = $this->entityManager->getRepository(Announcement::class);

$this->sendJson(
[
'feed' => $repository->getFeed(),
],
);
$this->sendJson([
'feed' => $this->repository->getFeed(),
]);
}


public function postPostTopic(string $message): void
public function postPostTopic(string $message, ?int $parentId = null): void
{
try {
$topic = new Announcement(
user: $this->getUserIdentity(),
locale: $this->localization->getLocale(),
message: $message,
);
} catch (\InvalidArgumentException $e) {
$this->flashMessage($e->getMessage());
$this->sendError($e->getMessage());
$identity = $this->userService->getIdentityEntity();
assert($identity !== null);

$parent = null;
if ($parentId !== null) {
$parent = $this->repository->find($parentId);
assert($parent instanceof Announcement);
}

$topic = new Announcement(
user: $identity,
locale: $this->localization->getLocale(),
message: $message,
parent: $parent,
);

$topic->setActive();
$this->entityManager->persist($topic);
$this->entityManager->flush();
$this->sendOk();
}


private function getUserIdentity(): User
{
$identity = $this->userManager->getIdentity();
assert($identity instanceof User);

return $identity;
}
}
59 changes: 21 additions & 38 deletions src/Api/CmsEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

use Baraja\AdminBar\AdminBar;
use Baraja\BarajaCloud\CloudManager;
use Baraja\CAS\AuthenticationException;
use Baraja\CAS\Authenticator;
use Baraja\CAS\Entity\User;
use Baraja\CAS\Entity\UserResetPasswordRequest;
use Baraja\CAS\Repository\UserResetPasswordRequestRepository;
use Baraja\Cms\Api\DTO\CmsGlobalSettingsResponse;
use Baraja\Cms\Api\DTO\CmsPluginResponse;
use Baraja\Cms\Api\DTO\CmsSettingsResponse;
Expand All @@ -18,11 +23,6 @@
use Baraja\Cms\Proxy\GlobalAsset\CmsSimpleStaticAsset;
use Baraja\Cms\Session;
use Baraja\Cms\Settings;
use Baraja\Cms\User\Entity\CmsUser;
use Baraja\Cms\User\Entity\User;
use Baraja\Cms\User\Entity\UserResetPasswordRequest;
use Baraja\Cms\User\Entity\UserResetPasswordRequestRepository;
use Baraja\Cms\User\UserManager;
use Baraja\Markdown\CommonMarkRenderer;
use Baraja\Plugin\BasePlugin;
use Baraja\StructuredApi\Attributes\PublicEndpoint;
Expand All @@ -31,14 +31,11 @@
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Nette\Security\AuthenticationException;
use Nette\Security\Authenticator;

#[PublicEndpoint]
final class CmsEndpoint extends BaseEndpoint
{
public function __construct(
private UserManager $userManager,
private CloudManager $cloudManager,
private Settings $settings,
private MenuManager $menuManager,
Expand Down Expand Up @@ -123,12 +120,12 @@ public function postSign(string $locale, string $username, string $password, boo
$this->sendError('Empty username or password.');
}
try {
$this->userManager->authenticate($username, $password, $remember);
$this->getUser()->getAuthenticator()->authentication($username, $password, $remember);
} catch (AuthenticationException $e) {
$code = $e->getCode();
if (in_array($code, [Authenticator::IDENTITY_NOT_FOUND, Authenticator::INVALID_CREDENTIAL, Authenticator::FAILURE], true)) {
if (in_array($code, [Authenticator::IdentityNotFound, Authenticator::InvalidCredential, Authenticator::Failure], true)) {
$this->sendError($e->getMessage());
} elseif ($code === Authenticator::NOT_APPROVED) {
} elseif ($code === Authenticator::NotApproved) {
$reason = $e->getMessage();
$this->sendError(
'The user has been assigned a permanent block. Please contact your administrator.'
Expand All @@ -155,10 +152,8 @@ public function postCheckOtpCode(string $locale, string $code): void
$this->sendError('User is not logged in.');
}
$id = $userEntity->getId();
assert(is_numeric($id));
$id = (int) $id;
try {
$user = $this->userManager->getUserById($id);
$user = $this->getUser()->getUserStorage()->getUserById($id);
} catch (NoResultException | NonUniqueResultException) {
$this->sendError(sprintf('User "%d" does not exist.', $id));
}
Expand All @@ -177,20 +172,17 @@ public function postCheckOtpCode(string $locale, string $code): void
public function postForgotPassword(string $locale, string $username): void
{
try {
/** @var CmsUser $user */
$user = $this->userManager->getDefaultUserRepository()
$user = $this->getUser()->getUserStorage()->getUserRepository()
->createQueryBuilder('user')
->leftJoin('user.email', 'email')
->where('user.username = :username')
->orWhere('user.email = :email')
->orWhere('email.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->setMaxResults(1)
->getQuery()
->getSingleResult();

if (!$user instanceof User) {
$this->sendError('Reset password is available only for system CMS Users. Please contact your administrator');
}
assert($user instanceof User);

$request = new UserResetPasswordRequest($user, '3 hours');
$this->entityManager->persist($request);
Expand All @@ -205,7 +197,7 @@ public function postForgotPassword(string $locale, string $username): void
'expireDate' => $request->getExpireDate()->format('d. m. Y, H:i:s'),
]);
} catch (NoResultException | NonUniqueResultException) {
// Silence is golden.
$this->sendError('Reset password is available only for system CMS Users. Please contact your administrator');
}

$this->sendOk();
Expand All @@ -216,8 +208,7 @@ public function postForgotUsername(string $locale, string $realName): void
{
if (preg_match('/^(\S+)\s+(\S+)$/', trim($realName), $parser) === 1) {
try {
/** @var CmsUser $user */
$user = $this->userManager->getDefaultUserRepository()
$user = $this->getUser()->getUserStorage()->getUserRepository()
->createQueryBuilder('user')
->where('user.firstName = :firstName')
->andWhere('user.lastName = :lastName')
Expand All @@ -226,6 +217,7 @@ public function postForgotUsername(string $locale, string $realName): void
->setMaxResults(1)
->getQuery()
->getSingleResult();
assert($user instanceof User);

$this->cloudManager->callRequest('cloud/forgot-username', [
'domain' => Url::get()->getNetteUrl()->getDomain(3),
Expand Down Expand Up @@ -266,8 +258,8 @@ public function postReportProblem(string $locale, string $description, string $u

public function postForgotPasswordSetNew(string $token, string $locale, string $password): void
{
/** @var UserResetPasswordRequestRepository $repository */
$repository = $this->entityManager->getRepository(UserResetPasswordRequest::class);
assert($repository instanceof UserResetPasswordRequestRepository);

try {
$request = $repository->getByToken($token);
Expand Down Expand Up @@ -299,14 +291,7 @@ public function postForgotPasswordSetNew(string $token, string $locale, string $
public function postSetUserPassword(string $locale, int $userId, string $password): void
{
try {
/** @var CmsUser $user */
$user = $this->userManager->getDefaultUserRepository()
->createQueryBuilder('user')
->where('user.id = :userId')
->setParameter('userId', $userId)
->setMaxResults(1)
->getQuery()
->getSingleResult();
$user = $this->getUser()->getUserStorage()->getUserById($userId);
} catch (NoResultException | NonUniqueResultException | \InvalidArgumentException) {
$this->sendError('User "' . $userId . '" does not exist.');
}
Expand All @@ -322,10 +307,8 @@ public function postSetUserPassword(string $locale, int $userId, string $passwor

public function postRenderEditorPreview(string $haystack): void
{
$this->sendJson(
[
'html' => $this->commonMarkRenderer->render($haystack),
],
);
$this->sendJson([
'html' => $this->commonMarkRenderer->render($haystack),
]);
}
}
Loading