resq/src/Controller/APIUserController.php

348 lines
10 KiB
PHP

<?php
namespace App\Controller;
use Catalyst\APIBundle\Entity\User as APIUser;
use Catalyst\APIBundle\Entity\Role as APIRole;
use Doctrine\ORM\Query;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\Rider;
class APIUserController extends Controller
{
/**
* @Menu(selected="api_user_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('apiuser.list', null, 'No access.');
return $this->render('api-user/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('apiuser.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(APIUser::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
// add filters to count query
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
// add filters to query
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// Query::HYDRATE_ARRAY);
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
$row['api_key'] = $orow->getAPIKey();
$row['enabled'] = $orow->isEnabled();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// check if they have access to super admin users
if (!$this->isGranted('user.role.sadmin') && $orow->isSuperAdmin())
{
$rows[] = $row;
continue;
}
// add crud urls
if ($this->isGranted('apiuser.update'))
$row['meta']['update_url'] = $this->generateUrl('api_user_update', ['id' => $row['id']]);
if ($this->isGranted('user.delete'))
$row['meta']['delete_url'] = $this->generateUrl('api_user_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="api_user_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('apiuser.add', null, 'No access.');
$params['obj'] = new APIUser();
$params['mode'] = 'create';
// get roles
$em = $this->getDoctrine()->getManager();
$params['roles'] = $em->getRepository(APIRole::class)->findAll();
$params['riders'] = $em->getRepository(Rider::class)->findBy([], ['first_name' => 'asc']);
// response
return $this->render('api-user/form.html.twig', $params);
}
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('apiuser.add', null, 'No access.');
// create new row
// API and secret keys are generated with the call to new APIUser()
$em = $this->getDoctrine()->getManager();
$obj = new APIUser();
// metadata
$rider_id = $req->request->get('rider_id');
$rider = $em->getRepository(Rider::class)->find($rider_id);
// TODO: check for null rider
$meta = ['rider_id' => $rider_id];
// set api user in rider
$rider->setAPIUser($obj);
// set and save values
$obj->setName($req->request->get('name'))
->setEnabled($req->request->get('enabled') ? true : false)
->setMetadata($meta)
->setRider($rider)
->clearRoles();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(APIRole::class)->find($role_id);
if (!empty($role))
{
// check access to super user roles
if ($role->isSuperAdmin() && !$this->isGranted('user.role.sadmin'))
continue;
$obj->addRole($role);
}
}
}
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
} else {
// validated! save the entity
$em->persist($obj);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
}
/**
* @Menu(selected="api_user_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('apiuser.update', null, 'No access.');
$params['mode'] = 'update';
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(APIUser::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// get roles
$params['roles'] = $em->getRepository(APIRole::class)->findAll();
$params['riders'] = $em->getRepository(Rider::class)->findBy([], ['first_name' => 'asc']);
$params['obj'] = $obj;
// response
return $this->render('api-user/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('apiuser.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(APIUser::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// set and save values
// metadata
$rider_id = $req->request->get('rider_id');
$rider = $em->getRepository(Rider::class)->find($rider_id);
// TODO: check for null rider
$meta = $obj->getMetadata();
$meta['rider_id'] = $rider_id;
// set api user in rider
$rider->setAPIUser($obj);
$obj->setName($req->request->get('name'))
->setEnabled($req->request->get('enabled') ? true : false)
->setMetadata($meta)
->setRider($rider)
->clearRoles();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(APIRole::class)->find($role_id);
if (!empty($role))
$obj->addRole($role);
}
}
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
} else {
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
}
public function destroy($id)
{
$this->denyAccessUnlessGranted('apiuser.delete', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(APIUser::class)->find($id);
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// delete this row
$em->remove($obj);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
// check if datatable filter is present and append to query
protected function setQueryFilters($datatable, &$query) {
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}