3 Commits

8 changed files with 303 additions and 7 deletions

View File

@@ -3,17 +3,72 @@ declare(strict_types=1);
namespace App\Game\Controller;
use App\Game\Entity\Session;
use App\Game\Repository\GameRepository;
use App\Game\Repository\SessionRepository;
use App\Game\Service\GameDashboardService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\ExpressionLanguage\Expression;
final class GameController extends AbstractController
{
#[Route(path: '', name: 'game')]
public function index(): Response
{
return $this->render('game/index.html.twig', [
'user_id' => $this->getUser()?->getId(),
#[Route(path: '', name: 'game_dashboard', methods: ['GET', 'POST'])]
#[IsGranted(new Expression("is_granted('ROLE_PLAYER') or is_granted('ROLE_ADMIN')"))]
public function dashboard(
Request $request,
GameRepository $gameRepository,
SessionRepository $sessionRepository,
GameDashboardService $dashboardService,
Security $security
): Response {
$user = $security->getUser();
$isAdmin = $this->isGranted('ROLE_ADMIN');
if ($request->isMethod('POST')) {
if ($request->request->has('create_session')) {
$gameId = $request->request->get('game_id');
$game = $gameRepository->find($gameId);
if ($game) {
if ($dashboardService->createSession($game, $user, $isAdmin)) {
$this->addFlash('success', 'New session created!');
}
}
} elseif ($request->request->has('create_invite')) {
$sessionId = $request->request->get('session_id');
$session = $sessionRepository->find($sessionId);
if (!$session) {
$this->addFlash('error', 'Session not found.');
return $this->redirectToRoute('game_dashboard');
}
$inviteCode = $dashboardService->generateInviteCode($session, $user, $isAdmin);
if ($inviteCode) {
$this->addFlash('success', 'Invite link created: ' . $inviteCode);
}
}
return $this->redirectToRoute('game_dashboard');
}
return $this->render('game/dashboard.html.twig', [
'sessions' => $dashboardService->getSessionsForUser($user),
'availableGames' => $dashboardService->getAvailableGames($isAdmin),
]);
}
#[Route(path: '/{session}', name: 'game')]
#[IsGranted(new Expression("is_granted('ROLE_PLAYER') or is_granted('ROLE_ADMIN')"))]
#[IsGranted('SESSION_VIEW', subject: 'session')]
public function index(
Session $session): Response
{
return $this->render('game/index.html.twig', ['session' => $session]);
}
}

View File

@@ -10,4 +10,5 @@ enum SessionSettingType: string
case RIGHTS_FOR_PLAYER1 = 'RightsForPlayer1';
case RIGHTS_FOR_PLAYER2 = 'RightsForPlayer2';
case RIGHTS_FOR_PLAYER3 = 'RightsForPlayer3';
case INVITE_CODE = 'InviteCode';
}

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Game\Security\Voter;
use App\Game\Entity\Session;
use App\Tech\Entity\User;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class SessionVoter extends Voter
{
public const VIEW = 'SESSION_VIEW';
public function __construct(
private readonly Security $security,
) {
}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute === self::VIEW && $subject instanceof Session;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
/** @var Session $session */
$session = $subject;
foreach ($session->getPlayers() as $player) {
if ($player->getUser() === $user) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Game\Service;
use App\Game\Entity\Game;
use App\Game\Entity\Player;
use App\Game\Entity\Session;
use App\Game\Entity\SessionSetting;
use App\Game\Enum\GameStatus;
use App\Game\Enum\SessionSettingType;
use App\Game\Enum\SessionStatus;
use App\Game\Repository\GameRepository;
use App\Game\Repository\SessionRepository;
use App\Tech\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
final class GameDashboardService
{
public function __construct(
private readonly GameRepository $gameRepository,
private readonly SessionRepository $sessionRepository,
private readonly EntityManagerInterface $entityManager,
) {
}
/**
* @return Session[]
*/
public function getSessionsForUser(UserInterface $user): array
{
return $this->sessionRepository->createQueryBuilder('s')
->innerJoin('s.players', 'p')
->where('p.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
}
/**
* @return Game[]
*/
public function getAvailableGames(bool $isAdmin): array
{
if ($isAdmin) {
return $this->gameRepository->findAll();
}
return $this->gameRepository->findBy(['status' => GameStatus::OPEN]);
}
public function createSession(Game $game, UserInterface $user, bool $isAdmin): ?Session
{
if ($game->getStatus() !== GameStatus::OPEN && !$isAdmin) {
return null;
}
if(!$user instanceof User)
return null;
$session = new Session();
$session->setGame($game);
$session->setStatus(SessionStatus::CREATED);
$session->setTimer(0);
$player = new Player();
$player->setUser($user);
$player->setSession($session);
$player->setScreen(1);
$this->entityManager->persist($session);
$this->entityManager->persist($player);
$this->entityManager->flush();
return $session;
}
public function generateInviteCode(Session $session, UserInterface $user, bool $isAdmin): ?string
{
// Security check: is user part of this session?
$isPlayer = false;
foreach ($session->getPlayers() as $player) {
if ($player->getUser() === $user) {
$isPlayer = true;
break;
}
}
if (!$isPlayer && !$isAdmin) {
return null;
}
$inviteCode = bin2hex(random_bytes(4));
$setting = null;
foreach ($session->getSettings() as $s) {
if ($s->getName() === SessionSettingType::INVITE_CODE) {
$setting = $s;
break;
}
}
if (!$setting) {
$setting = new SessionSetting();
$setting->setSession($session);
$setting->setName(SessionSettingType::INVITE_CODE);
}
$setting->setValue($inviteCode);
$this->entityManager->persist($setting);
$this->entityManager->flush();
return $inviteCode;
}
}

View File

@@ -31,6 +31,8 @@ class RegistrationController extends AbstractController
)
);
$user->setRoles(['ROLE_USER', 'ROLE_PLAYER']);
$entityManager->persist($user);
$entityManager->flush();

View File

@@ -14,7 +14,7 @@
<nav>
{% set pathinfo = app.request.pathinfo %}
<a href="/">{{ 'nav.home'|trans }}</a> |
<a href="/game">{{ 'nav.game'|trans }}</a> |
<a href="{{ path('game_dashboard') }}">{{ 'nav.game'|trans }}</a> |
{% if app.user %}
<a href="{{ path('app_logout') }}">Logout</a>
{% else %}

View File

@@ -0,0 +1,74 @@
{% extends 'base.html.twig' %}
{% block title %}Game Dashboard{% endblock %}
{% block body %}
<h1>Game Dashboard</h1>
<h2>Create New Session</h2>
{% if availableGames is not empty %}
<form method="post">
<select name="game_id">
{% for game in availableGames %}
<option value="{{ game.id }}">
{{ game.name }} ({{ game.numberOfPlayers }} players)
{% if is_granted('ROLE_ADMIN') %}
[{{ game.status.value }}]
{% endif %}
</option>
{% endfor %}
</select>
<button type="submit" name="create_session">Create Session</button>
</form>
{% else %}
<p>No games available to start.</p>
{% endif %}
<h2>Your Sessions</h2>
{% if sessions is not empty %}
<table>
<thead>
<tr>
<th>ID</th>
<th>Game</th>
<th>Status</th>
<th>Created At</th>
<th>Invite Code</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for session in sessions %}
<tr>
<td>{{ session.id }}</td>
<td>{{ session.game.name }}</td>
<td>{{ session.status.value }}</td>
<td>{{ session.created|date('Y-m-d H:i') }}</td>
<td>
{% set inviteCode = '' %}
{% for setting in session.settings %}
{% if setting.name.value == 'InviteCode' %}
{% set inviteCode = setting.value %}
{% endif %}
{% endfor %}
{% if inviteCode %}
<code>{{ inviteCode }}</code>
{% else %}
<form method="post" style="display:inline;">
<input type="hidden" name="session_id" value="{{ session.id }}">
<button type="submit" name="create_invite">Generate Invite</button>
</form>
{% endif %}
</td>
<td>
<a href="{{ path('game', {session: session.id}) }}">Enter Game</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>You are not part of any sessions.</p>
{% endif %}
{% endblock %}

View File

@@ -5,5 +5,5 @@
{% block body %}
<h1>{{ 'home.h1'|trans({'%site%': ('site.name'|trans)}) }}</h1>
<p>{{ 'home.description'|trans }}</p>
<p><a href="{{ path('game') }}">{{ 'link.enter_game'|trans }}</a></p>
<p><a href="{{ path('game_dashboard') }}">{{ 'link.enter_game'|trans }}</a></p>
{% endblock %}