Skip to content

Commit

Permalink
Merge pull request #57 from MaxandreOgeret/mog-dev
Browse files Browse the repository at this point in the history
jsGrid + trans improvments
  • Loading branch information
MaxandreOgeret authored Aug 1, 2019
2 parents 5f3376a + 6dfe715 commit bfed278
Show file tree
Hide file tree
Showing 13 changed files with 133 additions and 70 deletions.
8 changes: 8 additions & 0 deletions config/routes/api.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# config/routes/api.yaml

api_validate_link:
path: /validate
controller: App\Controller\ApiController:validateLink
condition: "request.isXmlHttpRequest()"
options:
expose: true
6 changes: 6 additions & 0 deletions config/routes/routes.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# config/routes/routes.yaml
# Dont forget to update ValidUuidValidator.php !

app_main_route_changelocale:
path: /changelocale/{_locale}
Expand All @@ -21,6 +22,11 @@ app_security:
requirements:
_locale: '%app.locales%'

# User management routes
app_api:
resource: 'api.yaml'
prefix: /api/

app_handle_home_form:
path: /{_locale}/form/home
controller: App\Controller\HomeController:handleHomeForm
Expand Down
5 changes: 4 additions & 1 deletion config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,7 @@ services:
$geo2IpLogger: '@monolog.logger.geo2ip'

App\Service\Geolocalization\Geo2IpManager:
$geo2IpLogger: '@monolog.logger.geo2ip'
$geo2IpLogger: '@monolog.logger.geo2ip'

App\Validator\Constraints\ValidUuidValidator:
$locales: '%app.locales%'
1 change: 1 addition & 0 deletions public/js/fos_js_routes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"base_url":"","routes":{"api_validate_link":{"tokens":[["text","\/api\/validate"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]}},"prefix":"","host":"localhost","port":"","scheme":"http"}
2 changes: 1 addition & 1 deletion public/js/jsgrid/et.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
},

validators: {
required: { message: "Kohustuslik väli Field is required" },
required: { message: "Kohustuslik väli" },
rangeLength: { message: "Väljal olev väärtus ei vasta seatud vahemikule" },
minLength: { message: "Väljal olev väärtus on liiga pikk" },
maxLength: { message: "Väljal olev väärtus on liiga lühike" },
Expand Down
45 changes: 45 additions & 0 deletions src/Controller/ApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
/**
* Created by PhpStorm.
* User: m.ogeret
* Date: 09/04/2018
* Time: 13:07
*/

namespace App\Controller;

use App\Entity\Link;
use App\Service\UriManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ApiController extends AbstractController
{
private $uriManager;

public function __construct(UriManager $uriManager)
{
$this->uriManager = $uriManager;
}

public function validateLink(Request $request, ValidatorInterface $validator)
{
$link = new Link($request);
$link->setUuid($request->query->get('uuid'))
->setUrl($this->uriManager->format($request->query->get('url')));

$violationList = $validator->validate($link);

if (count($violationList) === 0) {
return new JsonResponse(['status' => 'ok']);
}
$messages = [];
foreach ($violationList as $violation) {
$messages[$violation->getPropertyPath()][] = $violation->getMessage();
}

return new JsonResponse(['status' => 'ko', 'messages' => $messages]);
}
}
12 changes: 9 additions & 3 deletions src/Service/LinkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class LinkManager
private $em;
private $validator;
private $linkSecLogger;
private $uriManager;

/**
* LinkManager constructor.
Expand All @@ -29,11 +30,16 @@ class LinkManager
* @param ValidatorInterface $validator
* @param Logger $linkSecLogger
*/
public function __construct(EntityManagerInterface $em, ValidatorInterface $validator, Logger $linkSecLogger)
{
public function __construct(
EntityManagerInterface $em,
ValidatorInterface $validator,
Logger $linkSecLogger,
UriManager $uriManager
) {
$this->em = $em;
$this->validator = $validator;
$this->linkSecLogger = $linkSecLogger;
$this->uriManager = $uriManager;
}

/**
Expand Down Expand Up @@ -101,7 +107,7 @@ public function createOrUpdate($linkArray, $request, $user)
$link = new Link($request);
$link
->setUuid($linkArray['uuid'])
->setUrl($linkArray['url'])
->setUrl($this->uriManager->format($linkArray['url']))
->setUser($user);
} else {
$linkSave = clone $link;
Expand Down
2 changes: 1 addition & 1 deletion src/Validator/Constraints/NoRedirectValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function validate($value, Constraint $constraint)
$redirectHost = $this->parser->parse($redirectUrl)['host'];

// Build violation if the website redirects to another website.
if ($redirectHost !== $urlHost) {
if (!in_array($redirectHost, ['www.'.$urlHost, $urlHost])) {
$this->context->buildViolation($constraint->message)->addViolation();
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Validator/Constraints/ValidUuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@
*/
class ValidUuid extends Constraint
{
public $messageChar = "UUID should contain only letters and '-', '_', '~'";
public $messageForbidden = 'This value is forbidden.';
public $messageChar = "app.validator.uuid.chars";
public $messageForbidden = 'app.validator.uuid.forbidden';
}
26 changes: 23 additions & 3 deletions src/Validator/Constraints/ValidUuidValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,27 @@

class ValidUuidValidator extends ConstraintValidator
{
const FORBIDDEN = ['app', 'security', 'link', 'form'];
const FORBIDDEN = [
'app',
'security',
'link',
'form',
'api',
'changelocale',
'register',
'js',
'_error',
'_wdt',
'_profiler'
];
const REGEX_CHAR = '/^[A-z0-9-_~]+$/';
const REGEX_FORBIDDEN = '/^(app|security|link|form)$/';

private $locales;

public function __construct($locales)
{
$this->locales = explode('|', $locales);
}

public function validate($value, Constraint $constraint)
{
Expand All @@ -24,7 +42,9 @@ public function validate($value, Constraint $constraint)
$this->context->buildViolation($constraint->messageChar)->addViolation();
}

if (preg_match(self::REGEX_FORBIDDEN, $value, $matches)) {
if (in_array($value, self::FORBIDDEN) ||
in_array($value, $this->locales)
) {
$this->context->buildViolation($constraint->messageForbidden)->addViolation();
}
}
Expand Down
2 changes: 2 additions & 0 deletions templates/base.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
<script src="{{ asset('js/jsgrid/'~app.request.getLocale()|lower~'.js') }}"></script>
<script src="{{ asset('js/bootstrap/bootbox.min.js') }}"></script>
<script src="{{ asset('js/app/base.js') }}"></script>
<script src="{{ asset('bundles/fosjsrouting/js/router.min.js') }}"></script>
<script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>
{% if app.user is not null %}<script>{{ include('manager/manager.js.twig') }}</script>{% endif %}

{% block javascripts %}{% endblock %}
Expand Down
87 changes: 31 additions & 56 deletions templates/manager/manager.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -10,59 +10,6 @@ function handleLinkJson(data) {

jsGrid.locale("{{ app.request.getLocale()|lower }}");

jsGrid.validators.url = {
message: "{{ 'app.linkmanager.error.notvalid'|trans }}",
validator: function(value, item) {
return (/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,6})?(\/.*)?$/.test(value) &&
!startsWith(value, 'lessn.io/') &&
!startsWith(value, 'http://lessn.io/') &&
!startsWith(value, 'http://www.lessn.io/') &&
!startsWith(value, 'https://lessn.io/') &&
!startsWith(value, 'https://www.lessn.io/')
);
}
}

jsGrid.validators.uuidchar = {
message: "{{ 'app.linkmanager.error.notvalid'|trans }} letters and '-', '_'",
validator: function(value, item) {
return /^[A-z0-9-_~]+$/.test(value);
}
}

jsGrid.validators.uuidforbidden = {
message: "{{ 'app.linkmanager.error.forbidden'|trans }}",
validator: function(value, item) {
return !(jQuery.inArray(value, ['app', 'security', 'link', 'form']) !== -1)
}
}

{# todo : Add len validator #}
{#jsGrid.validators.uuidmaxlen = {
message: "This value ",
validator: function(value, item) {
return !(jQuery.inArray(value, ['app', 'security', 'link', 'form']) !== -1)
}
}#}

jsGrid.validators.uuidUnique = {
message: "{{ 'app.linkmanager.error.taken'|trans }}",
validator: function(value, item) {
var valid = false;

$.ajax({
type: 'GET',
url: '{{ path('app_link_manager_check_uuid') }}',
data: {uuid: value},
dataType: 'json',
async: false
}).done(function (data) {
valid = data;
});
return valid;
}
}

var customFinishInsert = function(grid) {
jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid);
};
Expand Down Expand Up @@ -148,23 +95,51 @@ function handleLinkJson(data) {
}
},

onItemInserting: function (args) {
$.ajax({
type: 'GET',
url: Routing.generate('api_validate_link', {uuid: args.item.uuid, url: args.item.url}),
dataType: 'json',
async: false
}).done(function (data) {
if (data.status === 'ko') {
args.cancel = true;

var msgList = '';
Object.keys(data.messages).forEach(key => {
msgList = msgList + '<b>' + key.toUpperCase() + '</b> : ' + data.messages[key] + '<br>';
});

$('#main_modal').modal('show');
// language=HTML
$('.modal-content').html(
`
<div class="modal-body">
<p class="text-center">` +
msgList
+ `</p>
</div>
<a class="link btn" data-dismiss="modal">OK</a>
`);
}
});
},

fields: [
{
title: "{{ 'app.linkmanager.table.uuid'|trans }}",
name: "uuid",
type: "text",
width: 40,
css: "jsgrid-inverted",
validate: ["uuidchar", 'uuidforbidden', 'uuidUnique'],
editing: false,
inserting: true
},
{
title: "{{ 'app.linkmanager.table.uuid'|trans }}",
title: "{{ 'app.linkmanager.table.url'|trans }}",
name: "url",
type: "text",
css: "jsgrid-inverted",
validate: ["required", "url"]
},
{
title: "{{ 'app.linkmanager.createdon'|trans }}",
Expand Down
3 changes: 0 additions & 3 deletions templates/security/login.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ form = $('#loginform');

form.submit(function (event) {
event.preventDefault();
console.log(form.serializeArray());

$.ajax({
url: form.attr('action'), // url where to submit the request
Expand All @@ -13,8 +12,6 @@ form.submit(function (event) {
success: function (data) {
// you can see the result from the console
// tab of the developer tools
console.log(data[0] === false);
console.log(data[1]);

if (data[0] === false) {
$('.loginerror').html(data[1])
Expand Down

0 comments on commit bfed278

Please sign in to comment.