Files
alrahma_sunday_school_api/app/Http/Controllers/Api/RoleSwitcherController.php
T

58 lines
1.8 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Requests\Roles\RoleSwitchRequest;
use App\Services\Roles\RoleSwitchService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
class RoleSwitcherController extends BaseApiController
{
public function __construct(private RoleSwitchService $switchService)
{
parent::__construct();
}
public function index(): JsonResponse
{
$userId = (int) (auth()->id() ?? 0);
if ($userId <= 0) {
return $this->error('Please log in first.', Response::HTTP_UNAUTHORIZED);
}
$roles = $this->switchService->getUserRoleNames($userId);
if (empty($roles)) {
return $this->error('No roles assigned to this user.', Response::HTTP_NOT_FOUND);
}
return $this->success([
'roles' => $roles,
]);
}
public function switch(RoleSwitchRequest $request): JsonResponse
{
$userId = (int) (auth()->id() ?? 0);
if ($userId <= 0) {
return $this->error('Please log in first.', Response::HTTP_UNAUTHORIZED);
}
$role = (string) $request->validated()['role'];
try {
$route = $this->switchService->switchRole($userId, $role);
} catch (AccessDeniedHttpException $e) {
return $this->error($e->getMessage(), Response::HTTP_FORBIDDEN);
} catch (NotFoundHttpException $e) {
return $this->error($e->getMessage(), Response::HTTP_NOT_FOUND);
}
return $this->success([
'role' => $role,
'dashboard_route' => $route,
], 'Role switched successfully.');
}
}