Add id to the User entity in the API bundle. Add support for list and add API user to the site. #194
This commit is contained in:
parent
b8ab5bb3c0
commit
d42e1b1ed5
6 changed files with 558 additions and 19 deletions
|
|
@ -16,9 +16,15 @@ use DateTime;
|
|||
*/
|
||||
class User extends BaseUser implements UserInterface
|
||||
{
|
||||
// api key
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\Column(type="integer")
|
||||
* @ORM\GeneratedValue(strategy="AUTO")
|
||||
*/
|
||||
protected $id;
|
||||
|
||||
// api key
|
||||
/**
|
||||
* @ORM\Column(type="string", length=32)
|
||||
*/
|
||||
protected $api_key;
|
||||
|
|
@ -43,9 +49,7 @@ class User extends BaseUser implements UserInterface
|
|||
// roles
|
||||
/**
|
||||
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
|
||||
* @ORM\JoinTable(name="api_user_role",
|
||||
* joinColumns={@JoinColumn(name="user_api_key", referencedColumnName="api_key")},
|
||||
* inverseJoinColumns={@JoinColumn(name="role_id", referencedColumnName="id")})
|
||||
* @ORM\JoinTable(name="api_user_role")
|
||||
*/
|
||||
protected $roles;
|
||||
|
||||
|
|
|
|||
|
|
@ -47,10 +47,6 @@ access_keys:
|
|||
label: Update
|
||||
- id: apiuser.delete
|
||||
label: Delete
|
||||
- id: apiuser.role.sadmin
|
||||
label: Super Admin Role
|
||||
- id: apiuser.profile
|
||||
label: User Profile
|
||||
- id: apirole
|
||||
label: API Role Access
|
||||
acls:
|
||||
|
|
|
|||
|
|
@ -31,14 +31,3 @@ api_user_delete:
|
|||
path: /apiusers/{id}
|
||||
controller: App\Controller\APIUserController::destroy
|
||||
methods: [DELETE]
|
||||
|
||||
api_user_profile:
|
||||
path: /apiprofile
|
||||
controller: App\Controller\APIUserController::profileForm
|
||||
methods: [GET]
|
||||
|
||||
api_user_profile_submit:
|
||||
path: /apiprofile
|
||||
controller: App\Controller\APIUserController::profileSubmit
|
||||
methods: [POST]
|
||||
|
||||
|
|
|
|||
209
src/Controller/APIUserController.php
Normal file
209
src/Controller/APIUserController.php
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
<?php
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Ramcar\BaseController;
|
||||
|
||||
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;
|
||||
|
||||
class APIUserController extends BaseController
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->denyAccessUnlessGranted('apiuser.list', null, 'No access.');
|
||||
|
||||
$params = $this->initParameters('api_user_list');
|
||||
|
||||
return $this->render('api-user/list.html.twig', $params);
|
||||
}
|
||||
|
||||
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
|
||||
]);
|
||||
}
|
||||
|
||||
public function addForm()
|
||||
{
|
||||
$this->denyAccessUnlessGranted('apiuser.add', null, 'No access.');
|
||||
|
||||
$params = $this->initParameters('api_user_list');
|
||||
$params['obj'] = new APIUser();
|
||||
$params['mode'] = 'create';
|
||||
|
||||
// get roles
|
||||
$em = $this->getDoctrine()->getManager();
|
||||
$params['roles'] = $em->getRepository(APIRole::class)->findAll();
|
||||
|
||||
// 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();
|
||||
|
||||
// set and save values
|
||||
$obj->setName($req->request->get('name'))
|
||||
->setEnabled($req->request->get('enabled') ? true : false)
|
||||
->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!'
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 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'] . '%');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
177
templates/api-user/form.html.twig
Normal file
177
templates/api-user/form.html.twig
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
{% extends 'base.html.twig' %}
|
||||
|
||||
{% block body %}
|
||||
<!-- BEGIN: Subheader -->
|
||||
<div class="m-subheader">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="mr-auto">
|
||||
<h3 class="m-subheader__title">
|
||||
API Users
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- END: Subheader -->
|
||||
<div class="m-content">
|
||||
<!--Begin::Section-->
|
||||
<div class="row">
|
||||
<div class="col-xl-8">
|
||||
<div class="m-portlet m-portlet--mobile">
|
||||
<div class="m-portlet__head">
|
||||
<div class="m-portlet__head-caption">
|
||||
<div class="m-portlet__head-title">
|
||||
<span class="m-portlet__head-icon">
|
||||
<i class="la la-user"></i>
|
||||
</span>
|
||||
<h3 class="m-portlet__head-text">
|
||||
{% if mode == 'update' %}
|
||||
Edit API User
|
||||
<small>{{ obj.getId() }}</small>
|
||||
{% else %}
|
||||
New API User
|
||||
{% endif %}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<form id="row-form" class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('api_user_update_submit', {'id': obj.getId()}) : url('api_user_create_submit') }}">
|
||||
<div class="m-portlet__body">
|
||||
<div class="form-group m-form__group row no-border">
|
||||
<div class="col-lg-6">
|
||||
<label for="name" data-field="name">Name</label>
|
||||
<input type="text" name="name" class="form-control m-input" value="{{ obj.getName() }}">
|
||||
<div class="form-control-feedback hide" data-field="name"></div>
|
||||
<span class="m-form__help">Name for this user</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group m-form__group row no-border">
|
||||
<div class="col-lg-12">
|
||||
<span class="m-switch m-switch--icon block-switch">
|
||||
<label>
|
||||
<input type="checkbox" name="enabled" id="enabled" value="1"{{ obj.isEnabled() ? ' checked' }}>
|
||||
<label class="switch-label">Enabled</label>
|
||||
<span></span>
|
||||
</label>
|
||||
</span>
|
||||
<div class="form-control-feedback hide" data-field="enabled"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="m-form__seperator m-form__seperator--dashed"></div>
|
||||
<div class="m-form__section">
|
||||
<div class="m-form__heading">
|
||||
<h3 class="m-form__heading-title">
|
||||
API Roles
|
||||
</h3>
|
||||
</div>
|
||||
<div class="form-group m-form__group row">
|
||||
<div class="col-lg-12">
|
||||
<div class="m-checkbox-list">
|
||||
{% for role in roles %}
|
||||
{% if role.isSuperAdmin and not is_granted('user.role.sadmin') %}
|
||||
{% else %}
|
||||
<label class="m-checkbox">
|
||||
<input type="checkbox" name="roles[]" value="{{ role.getID() }}"{{ role.getID() in obj.getRoles() ? ' checked' : '' }}>
|
||||
{{ role.getName() }}
|
||||
<span></span>
|
||||
</label>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="form-control-feedback hide" data-field="roles"></div>
|
||||
<span class="m-form__help">Check all roles that apply</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="m-portlet__foot m-portlet__foot--fit">
|
||||
<div class="m-form__actions m-form__actions--solid m-form__actions--right">
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<button type="submit" class="btn btn-success">Submit</button>
|
||||
<a href="{{ url('api_user_list') }}" class="btn btn-secondary">Back</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
$(function() {
|
||||
$("#row-form").submit(function(e) {
|
||||
var form = $(this);
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: form.prop('action'),
|
||||
data: form.serialize()
|
||||
}).done(function(response) {
|
||||
// remove all error classes
|
||||
removeErrors();
|
||||
swal({
|
||||
title: 'Done!',
|
||||
text: 'Your changes have been saved!',
|
||||
type: 'success',
|
||||
onClose: function() {
|
||||
window.location.href = "{{ url('api_user_list') }}";
|
||||
}
|
||||
});
|
||||
}).fail(function(response) {
|
||||
if (response.status == 422) {
|
||||
var errors = response.responseJSON.errors;
|
||||
var firstfield = false;
|
||||
|
||||
// remove all error classes first
|
||||
removeErrors();
|
||||
|
||||
// display errors contextually
|
||||
$.each(errors, function(field, msg) {
|
||||
var formfield = $("[name='" + field + "']");
|
||||
var label = $("label[data-field='" + field + "']");
|
||||
var msgbox = $(".form-control-feedback[data-field='" + field + "']");
|
||||
|
||||
// add error classes to bad fields
|
||||
formfield.addClass('form-control-danger');
|
||||
label.addClass('has-danger');
|
||||
msgbox.html(msg).addClass('has-danger').removeClass('hide');
|
||||
|
||||
// check if this field comes first in DOM
|
||||
var domfield = formfield.get(0);
|
||||
|
||||
if (!firstfield || (firstfield && firstfield.compareDocumentPosition(domfield) === 2)) {
|
||||
firstfield = domfield;
|
||||
}
|
||||
});
|
||||
|
||||
// focus on first bad field
|
||||
firstfield.focus();
|
||||
|
||||
// scroll to above that field to make it visible
|
||||
$('html, body').animate({
|
||||
scrollTop: $(firstfield).offset().top - 200
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// remove all error classes
|
||||
function removeErrors() {
|
||||
$(".form-control-danger").removeClass('form-control-danger');
|
||||
$("[data-field]").removeClass('has-danger');
|
||||
$(".form-control-feedback[data-field]").addClass('hide');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
164
templates/api-user/list.html.twig
Normal file
164
templates/api-user/list.html.twig
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
{% extends 'base.html.twig' %}
|
||||
|
||||
{% block body %}
|
||||
<!-- BEGIN: Subheader -->
|
||||
<div class="m-subheader">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="mr-auto">
|
||||
<h3 class="m-subheader__title">
|
||||
API Users
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- END: Subheader -->
|
||||
<div class="m-content">
|
||||
<!--Begin::Section-->
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="m-portlet m-portlet--mobile">
|
||||
<div class="m-portlet__body">
|
||||
<div class="m-form m-form--label-align-right m--margin-top-20 m--margin-bottom-30">
|
||||
<div class="row align-items-center">
|
||||
<div class="col-xl-8 order-2 order-xl-1">
|
||||
<div class="form-group m-form__group row align-items-center">
|
||||
<div class="col-md-4">
|
||||
<div class="m-input-icon m-input-icon--left">
|
||||
<input type="text" class="form-control m-input m-input--solid" placeholder="Search..." id="data-rows-search">
|
||||
<span class="m-input-icon__icon m-input-icon__icon--left">
|
||||
<span><i class="la la-search"></i></span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl-4 order-1 order-xl-2 m--align-right">
|
||||
<a href="{{ url('api_user_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
|
||||
<span>
|
||||
<i class="la la-user"></i>
|
||||
<span>New API User</span>
|
||||
</span>
|
||||
</a>
|
||||
<div class="m-separator m-separator--dashed d-xl-none"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!--begin: Datatable -->
|
||||
<div id="data-rows"></div>
|
||||
<!--end: Datatable -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
$(function() {
|
||||
var options = {
|
||||
data: {
|
||||
type: 'remote',
|
||||
source: {
|
||||
read: {
|
||||
url: '{{ url("api_user_rows") }}',
|
||||
method: 'POST',
|
||||
}
|
||||
},
|
||||
saveState: {
|
||||
cookie: false,
|
||||
webstorage: false
|
||||
},
|
||||
pageSize: 10,
|
||||
serverPaging: true,
|
||||
serverFiltering: true,
|
||||
serverSorting: true
|
||||
},
|
||||
columns: [
|
||||
{
|
||||
field: 'id',
|
||||
title: 'ID',
|
||||
width: 30
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
title: 'Name'
|
||||
},
|
||||
{
|
||||
field: 'api_key',
|
||||
title: 'API Key'
|
||||
},
|
||||
{
|
||||
field: 'enabled',
|
||||
title: 'Status',
|
||||
template: function (row, index, datatable) {
|
||||
var tag = '';
|
||||
|
||||
if (row.enabled === true) {
|
||||
tag = '<span class="m-badge m-badge--success m-badge--wide">Enabled</span>';
|
||||
} else {
|
||||
tag = '<span class="m-badge m-badge--danger m-badge--wide">Disabled</span>';
|
||||
}
|
||||
|
||||
return tag;
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'Actions',
|
||||
width: 110,
|
||||
title: 'Actions',
|
||||
sortable: false,
|
||||
overflow: 'visible',
|
||||
template: function (row, index, datatable) {
|
||||
var actions = '';
|
||||
|
||||
if (row.meta.update_url != '') {
|
||||
actions += '<a href="' + row.meta.update_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill btn-edit" data-id="' + row.id + '" title="Edit"><i class="la la-edit"></i></a>';
|
||||
}
|
||||
|
||||
if (row.meta.delete_url != '') {
|
||||
actions += '<a href="' + row.meta.delete_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill btn-delete" data-id="' + row.id + '" title="Delete"><i class="la la-trash"></i></a>';
|
||||
}
|
||||
|
||||
return actions;
|
||||
},
|
||||
}
|
||||
],
|
||||
search: {
|
||||
onEnter: false,
|
||||
input: $('#data-rows-search'),
|
||||
delay: 400
|
||||
}
|
||||
};
|
||||
|
||||
var table = $("#data-rows").mDatatable(options);
|
||||
|
||||
$(document).on('click', '.btn-delete', function(e) {
|
||||
var url = $(this).prop('href');
|
||||
var id = $(this).data('id');
|
||||
var btn = $(this);
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
swal({
|
||||
title: 'Confirmation',
|
||||
html: 'Are you sure you want to delete <strong>' + id + '</strong>?',
|
||||
type: 'warning',
|
||||
showCancelButton: true
|
||||
}).then((result) => {
|
||||
if (result.value) {
|
||||
$.ajax({
|
||||
method: "DELETE",
|
||||
url: url
|
||||
}).done(function(response) {
|
||||
table.row(btn.parents('tr')).remove();
|
||||
table.reload();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
Loading…
Reference in a new issue