resq/src/Controller/UserController.php

487 lines
15 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\Role;
use App\Entity\Hub;
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;
class UserController extends Controller
{
/**
* @Menu(selected="user_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('user.list', null, 'No access.');
return $this->render('user/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('user.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(User::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['username'] = $orow->getUsername();
$row['first_name'] = $orow->getFirstName();
$row['last_name'] = $orow->getLastName();
$row['email'] = $orow->getEmail();
$row['contact_num'] = $orow->getContactNumber();
$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('user.update'))
$row['meta']['update_url'] = $this->generateUrl('user_update', ['id' => $row['id']]);
if ($this->isGranted('user.delete'))
$row['meta']['delete_url'] = $this->generateUrl('user_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="user_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('user.add', null, 'No access.');
$params['obj'] = new User();
$params['mode'] = 'create';
// get roles
$em = $this->getDoctrine()->getManager();
$params['roles'] = $em->getRepository(Role::class)->findAll();
$params['hubs'] = $em->getRepository(Hub::class)->findAll();
// response
return $this->render('user/form.html.twig', $params);
}
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('user.add', null, 'No access.');
// create new row
$em = $this->getDoctrine()->getManager();
$obj = new User();
// set and save values
$obj->setUsername($req->request->get('username'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'))
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles()
->clearHubs();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(Role::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);
}
}
}
// set hubs
$hubs = $req->request->get('hubs');
if (!empty($hubs)) {
foreach ($hubs as $hub_id) {
// check if hub exists
$hub = $em->getRepository(Hub::class)->find($hub_id);
if (!empty($hub))
$obj->addHub($hub);
}
}
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if (!$password) {
$error_array['password'] = 'This value should not be blank.';
} else if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder($obj);
$encoded_password = $enc->encodePassword($req->request->get('password'), $obj->getSalt());
// set password
$obj->setPassword($encoded_password);
}
// 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="user_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('user.update', null, 'No access.');
$params['mode'] = 'update';
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(User::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(Role::class)->findAll();
$params['hubs'] = $em->getRepository(Hub::class)->findAll();
$params['obj'] = $obj;
// response
return $this->render('user/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('user.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(User::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$obj->setUsername($req->request->get('username'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'))
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles()
->clearHubs();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(Role::class)->find($role_id);
if (!empty($role))
$obj->addRole($role);
}
}
// set hubs
$hubs = $req->request->get('hubs');
if (!empty($hubs)) {
foreach ($hubs as $hub_id) {
// check if hub exists
$hub = $em->getRepository(Hub::class)->find($hub_id);
if (!empty($hub))
$obj->addHub($hub);
}
}
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if ($password || $confirm_password) {
if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder($obj);
$encoded_password = $enc->encodePassword($req->request->get('password'), $obj->getSalt());
// set password
$obj->setPassword($encoded_password);
}
}
// 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('user.delete', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(User::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.username LIKE :filter')
->orWhere('q.first_name LIKE :filter')
->orWhere('q.last_name LIKE :filter')
->orWhere('q.email LIKE :filter')
->orWhere('q.contact_num LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
/**
* @Menu(selected="user_profile")
*/
public function profileForm()
{
$this->denyAccessUnlessGranted('user.profile', null, 'No access.');
$params['mode'] = 'profile';
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $this->getUser();
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$params['obj'] = $obj;
// response
return $this->render('user/form.html.twig', $params);
}
public function profileSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('user.profile', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $this->getUser();
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$obj->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'));
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if ($password || $confirm_password) {
if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder($obj);
$encoded_password = $enc->encodePassword($req->request->get('password'), $obj->getSalt());
// set password
$obj->setPassword($encoded_password);
}
}
// 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!'
]);
}
}
}