Laravel Echo / Pusher authentication fails (403) - laravel-5.4

Learning Laravel event broadcasting / Echo / Vue and playing around with this tutorial.
I keep getting 403 responses to authentication, and I suspect my lack of understanding on the channels.php routes is the issue. I am using Player model instead of User for Auth which works ok.
Event ChatMessageSend
class ChatMessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $channel;
public $player;
public $chatMessage;
/**
* Create a new event instance.
* GameChat constructor.
* #param $chatMessage
* #param $player
*/
public function __construct(ChatMessage $chatMessage, Player $player)
{
$this->channel = session()->get('chat.channel');
$this->chatMessage = $chatMessage;
$this->player = $player;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel($this->channel);
}
}
Listener ChatMessageNotification (default / empty)
class ChatMessageNotification
{
/**
* ChatMessageNotification constructor.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param ChatMessageSent $event
* #return void
*/
public function handle(ChatMessageSent $event)
{
//
}
}
Controller ChatController
class ChatController extends Controller
{
/**
* Send chat message
*
* #param Request $request
* #return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function getMessages(Request $request)
{
return ChatMessage::with('player')
->where('progress_id', '=', session('game.progress.id'))
->orderBy('created_at', 'DESC')
->get();
}
/**
* Send chat message
*
* #param Request $request
* #return array|string
*/
public function sendMessage(Request $request)
{
$player = Auth::user();
$message = $request->input('message');
if ($message) {
$message = ChatMessage::create([
'player_id' => $player->id,
'progress_id' => session()->get('game.progress.id'),
'message' => $request->input('message')
]);
}
broadcast(new ChatMessageSent($player, $message))->toOthers();
return ['type' => 'success'];
}
}
Routes channels.php
Broadcast::channel(session()->get('chat.channel'), function ($player, $message) {
return $player->inRoom();
});
And in my Player class
/**
* A user can be in one chat channel
*/
public function inRoom()
{
if ((Auth::check()) and ($this->games()->where('progress_id', '=', session('game.progress.id'))->get())) {
return true;
}
return false;
}
When a player logs in, I store in session a chat room id which I would like to use as channel.
My vue chat instance is
Vue.component('chat-messages', require('./../generic/chat-messages.vue'));
Vue.component('chat-form', require('./../generic/chat-form.vue'));
const app = new Vue({
el: '#toolbar-chat',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private(chat_channel)
.listen('chatmessagesent', (e) => {
this.messages.unshift({
message: e.data.message,
player: e.data.player.nickname
});
});
},
methods: {
fetchMessages() {
axios.get(chat_get_route)
.then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.unshift(message);
this.$nextTick(() => {
this.$refs.toolbarChat.scrollTop = 0;
});
axios.post(chat_send_route, message)
.then(response => {
console.log(response.data);
});
}
}
});
But I keep getting
POST http://my-games.app/broadcasting/auth 403 (Forbidden)
Pusher : Couldn't get auth info from your webapp : 403

Error 403 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your key',
cluster: 'your cluster',
encrypted: true,
auth: {
headers: {
Authorization: 'Bearer ' + YourTokenLogin
},
},
});
And in app/Providers/BroadcastServiceProvider.php change by
Broadcast::routes()
with
Broadcast::routes(['middleware' => ['auth:api']]);
or
Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT
it worked for me, and hope it help you.

It may be an idea to figure out whether your routes/channels.php file is doing as you expect. Maybe add some logging to see if that route gets called at all, and that your inRoom function is returning what you expect.

In case anyone still needs an answer, this worked for me.
Add to your broadcastServiceProvider.php
Broadcast::routes([
'middleware' => 'auth:api']);
add to your channels.php
Broadcast::channel('chat', function () {
return Auth::check();
});

Related

how to add AngularJS DHTML directive?

dhtml syntax help
this is the syntax used
I do not exhaust the complete dhtmlXGrid API here...
however configure and dataLoaded callbacks let user
add any additional configuration they desire
"use strict";
angular.module('dhxDirectives')
.directive('dhxGrid', function factory(DhxUtils) {
return {
restrict: 'E',
require: 'dhxGrid',
controller: function () {
},
scope: {
/**
* Grid will be accessible in controller via this scope entry
* after it's initialized.
* NOTE: For better design and testability you should use instead the
* configure and dataLoaded callbacks.
*/
dhxObj: '=',
/** Mandatory in current implementation! */
dhxMaxHeight: '=',
/** Optional. Default is 100%. */
dhxMaxWidth: '=',
/**
* Data is given here as an object. Not a filename! Must conform to the
* specified or default dataFormat
*/
dhxData: '=',
/**
* View possible formats here: http://docs.dhtmlx.com/grid__data_formats.html
* Currently supported:
* ['Basic JSON', 'Native JSON'] // 'Basic JSON' is default value
*/
dhxDataFormat: '=',
/** Optional! Recommended! http://docs.dhtmlx.com/api__dhtmlxgrid_setheader.html */
dhxHeader: '=',
/** Optional! http://docs.dhtmlx.com/api__dhtmlxgrid_setcoltypes.html */
dhxColTypes: '=',
/** Optional! http://docs.dhtmlx.com/api__dhtmlxgrid_setcolsorting.html */
dhxColSorting: '=',
/** Optional! http://docs.dhtmlx.com/api__dhtmlxgrid_setcolalign.html */
dhxColAlign: '=',
/** Optional! http://docs.dhtmlx.com/api__dhtmlxgrid_setinitwidthsp.html */
dhxInitWidths: '=',
/** Optional! http://docs.dhtmlx.com/api__dhtmlxgrid_setinitwidths.html */
dhxInitWidthsP: '=',
/**
* preLoad and postLoad callbacks to controller for additional
* customization power.
*/
dhxConfigureFunc: '=',
dhxOnDataLoaded: '=',
/**
* [{type: <handlerType>, handler: <handlerFunc>}]
* where type is 'onSomeEvent'
* Events can be seen at: http://docs.dhtmlx.com/api__refs__dhtmlxgrid_events.html
* Optional
*/
dhxHandlers: '=',
dhxVersionId: '=',
dhxContextMenu: '='
},
compile: function compile(/*tElement, tAttrs, transclude*/) {
return function (scope, element/*, attrs*/) {
var loadStructure = function () {
$(element).empty();
$('<div></div>').appendTo(element[0]);
var rootElem = element.children().first();
var width = scope.dhxMaxWidth ? (scope.dhxMaxWidth + 'px') : '100%';
var height = scope.dhxMaxHeight ? (scope.dhxMaxHeight + 'px') : '100%';
rootElem.css('width', width);
rootElem.css('height', height);
//noinspection JSPotentiallyInvalidConstructorUsage
if (scope.dhxObj) {
DhxUtils.dhxDestroy(scope.dhxObj);
}
scope.dhxObj = new dhtmlXGridObject(rootElem[0]);
var grid = scope.dhxObj;
grid.setImagePath(DhxUtils.getImagePath());
grid.enableAutoHeight(!!scope.dhxMaxHeight, scope.dhxMaxHeight, true);
grid.enableAutoWidth(!!scope.dhxMaxWidth, scope.dhxMaxWidth, true);
scope.dhxContextMenu ? grid.enableContextMenu(scope.dhxContextMenu) : '';
scope.$watch(
"dhxContextMenu",
function handle( newValue, oldValue ) {
grid.enableContextMenu(newValue);
}
);
scope.dhxHeader ? grid.setHeader(scope.dhxHeader): '';
scope.dhxColTypes ? grid.setColTypes(scope.dhxColTypes): '';
scope.dhxColSorting ? grid.setColSorting(scope.dhxColSorting): '';
scope.dhxColAlign ? grid.setColAlign(scope.dhxColAlign): '';
scope.dhxInitWidths ? grid.setInitWidths(scope.dhxInitWidths): '';
scope.dhxInitWidthsP ? grid.setInitWidthsP(scope.dhxInitWidthsP): '';
// Letting controller add configurations before data is parsed
if (scope.dhxConfigureFunc) {
scope.dhxConfigureFunc(grid);
}
grid.init();
// Finally parsing data
var dhxDataFormat = scope.dhxDataFormat || 'Basic JSON';
switch (dhxDataFormat) {
case 'Basic JSON':
grid.parse(scope.dhxData, 'json');
break;
case 'Native JSON':
grid.load(scope.dhxData, 'js');
break;
}
// Letting controller do data manipulation after data has been loaded
if (scope.dhxOnDataLoaded) {
scope.dhxOnDataLoaded(grid);
}
DhxUtils.attachDhxHandlers(grid, scope.dhxHandlers);
DhxUtils.dhxUnloadOnScopeDestroy(scope, grid);
};
scope.$watch('dhxVersionId', function (/*newVal, oldVal*/) {
console.log('rebuilding...');
loadStructure();
});
}
}
};
});
© 2020 GitHub, Inc.
I do not exhaust the complete dhtmlXGrid API here...
however configure and dataLoaded callbacks let user
add any additional configuration they desire
<dhx-grid
dhx-obj="grid.obj"
style="height: 100%"
dhx-data="gridData"
dhx-col-sorting="'str,str,int'"
dhx-header="'Title,Author,Copies sold'"
dhx-context-menu="contextMenu"
dhx-handlers="grid.handlers"></dhx-grid>
angular.module('myApp')
.controller('GridController', ['$scope' ,function ($scope) {
$scope.grid = {
obj: {},
handlers: [
{type: "onRowSelect", handler: function (id) {
$scope.grid.obj.deleteRow(id);
}}
]
};
$scope.alert = function alert(event_name) {
switch (event_name) {
case "refreshsize":
$scope.grid.obj.setSizes();
}
};
$scope.contextMenu = {};
$scope.gridData = {
rows:[
{ id:1, data: ["Click a row", "John Grasham", "100"]},
{ id:2, data: ["to have it", "Stephen Pink", "2000"]},
{ id:3, data: ["deleted", "Terry Brattchet", "3000"]},
{ id:4, data: ["La la la", "Isaac Zimov", "4000"]},
{ id:5, data: ["La la la", "Sax Pear", "5000"]}
]
};
}]);
"use strict";
/**
* Created by Emanuil on 01/02/2016.
*/
angular.module('dhxDirectives')
.factory('DhxUtils', [function () {
var _imgPath = "bower_components/dhtmlx/imgs/";
/**
* #param dhxObject
* #param dhxHandlers
*/
var attachDhxHandlers = function (dhxObject, dhxHandlers) {
(dhxHandlers || [])
.forEach(function (info) {
dhxObject.attachEvent(info.type, info.handler);
});
};
var getImagePath = function () {
return _imgPath;
};
var setImagePath = function (imgPath) {
_imgPath = imgPath;
};
/**
* I hope to never resort to using that
*/
var createCounter = function () {
var current = -1;
return function () {
current++;
return current;
};
};
var removeUndefinedProps = function(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
delete obj[prop];
}
}
};
var dhxDestroy = function (dhxObj) {
var destructorName =
'destructor' in dhxObj
? 'destructor'
:
('unload' in dhxObj
? 'unload'
: null);
if (destructorName === null) {
console.error('Dhtmlx object does not have a destructor or unload method! Failed to register with scope destructor!');
return;
}
dhxObj[destructorName]();
};
var dhxUnloadOnScopeDestroy = function (scope, dhxObj) {
var destructorName =
'destructor' in dhxObj
? 'destructor'
:
('unload' in dhxObj
? 'unload'
: null);
if (destructorName === null) {
console.error('Dhtmlx object does not have a destructor or unload method! Failed to register with scope destructor!');
return;
}
scope.$on(
"$destroy",
function (/*event*/) {
dhxObj[destructorName]();
}
);
};
return {
attachDhxHandlers: attachDhxHandlers,
getImagePath: getImagePath,
setImagePath: setImagePath,
createCounter: createCounter,
removeUndefinedProps: removeUndefinedProps,
dhxUnloadOnScopeDestroy: dhxUnloadOnScopeDestroy,
dhxDestroy: dhxDestroy
};
}]);

Return JsonResponse when i use an AuthTokenAuthenticator (symfony 3)

I specify that I start with Symfony. I want to create an API (without FOSRestBundle) with a token as a means of authentication.
I followed different tutorials for this set up. What I would like is when there is an error that is picked up by the class "AuthTokenAuthenticator", it is returned a json and not a html view.
Here are my script:
AuthTokenAuthenticator
namespace AppBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
class AuthTokenAuthenticator implements
SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
{
const TOKEN_VALIDITY_DURATION = 12 * 3600;
protected $httpUtils;
public function __construct(HttpUtils $httpUtils)
{
$this->httpUtils = $httpUtils;
}
public function createToken(Request $request, $providerKey)
{
//$targetUrlToken = '/auth-tokens'; // login
//$targetUrlUser = '/users/create'; // create account
/*if ($request->getMethod() === "POST" && $this->httpUtils->checkRequestPath($request, $targetUrlUser) || $request->getMethod() === "POST" && $this->httpUtils->checkRequestPath($request, $targetUrlToken) ) {
return;
}*/
$authTokenHeader = $request->headers->get('X-Auth-Token');
if (!$authTokenHeader) {
//return new JsonResponse(array("error" => 1, "desc" => "INVALID_TOKEN", "message" => "X-Auth-Token header is required"));
throw new BadCredentialsException('X-Auth-Token header is required');
}
return new PreAuthenticatedToken(
'anon.',
$authTokenHeader,
$providerKey
);
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
if (!$userProvider instanceof AuthTokenUserProvider) {
throw new \InvalidArgumentException(
sprintf(
'The user provider must be an instance of AuthTokenUserProvider (%s was given).',
get_class($userProvider)
)
);
}
$authTokenHeader = $token->getCredentials();
$authToken = $userProvider->getAuthToken($authTokenHeader);
if (!$authToken || !$this->isTokenValid($authToken)) {
throw new BadCredentialsException('Invalid authentication token');
}
$user = $authToken->getUser();
$pre = new PreAuthenticatedToken(
$user,
$authTokenHeader,
$providerKey,
$user->getRoles()
);
$pre->setAuthenticated(true);
return $pre;
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}
/**
* Vérifie la validité du token
*/
private function isTokenValid($authToken)
{
return (time() - $authToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
throw $exception;
}
}
Here is the error return that I have when I do not inform the token:
<!DOCTYPE html>
<html>
<head>
<title> X-Auth-Token header is required (500 Internal Server Error)
How can i do to get a return json response ?
If i try to do a return new JsonResponse(array("test" => "KO")) (simple example), i get this error:
<title> Type error: Argument 1 passed to Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager::authenticate() must be an instance of Symfony\Component\Security\Core\Authentication\Token\TokenInterface, instance of Symfony\Component\HttpFoundation\JsonResponse given, called in /Users/mickaelmercier/Desktop/workspace/api_monblocrecettes/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/SimplePreAuthenticationListener.php on line 101 (500 Internal Server Error)
You can create your own Error Handler. It's a event listener or subscriber that listens to kernel.exception, when it adds a response to the event, the event propagation is stopped, so the default error handler will not be triggered.
It could look something like this:
<?php declare(strict_types = 1);
namespace App\EventSubsbscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
final class ExceptionToJsonResponseSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(GetResponseForExceptionEvent $event): void
{
// Skip if request is not an API-request
$request = $event->getRequest();
if (strpos($request->getPathInfo(), '/api/') !== 0) {
return;
}
$exception = $event->getException();
$error = [
'type' => $this->getErrorTypeFromException($exception),
// Warning! Passing the exception message without checks is insecure.
// This will potentially leak sensitive information.
// Do not use this in production!
'message' => $exception->getMessage(),
];
$response = new JsonResponse($error, $this->getStatusCodeFromException($exception));
$event->setResponse($response);
}
private function getStatusCodeFromException(\Throwable $exception): int
{
if ($exception instanceof HttpException) {
return $exception->getStatusCode();
}
return 500;
}
private function getErrorTypeFromException(\Throwable $exception): string
{
$parts = explode('\\', get_class($exception));
return end($parts);
}
}
ApiPlatform provides its own exception listener like this, that is more advanced, that you could look into if you need "better" exception responses.

ZF2AuthAcl Module doesnt work out of the box

I picked up this ZF2AuthAcl module to make my life easier. For some reason it does not work out of the box. As soon as i activate it in Zend2 Application.config it takes over the whole site. Meaning it goes straight to login on any page i have. There is a "white list" and i tried to add pages to this in an array and it does not seem to work. I will show the Acl page that it has with the "white list" maybe i did not add them correctly or there is a better way. It is data driven also. Has anyone used this with success or know about it?
The author is the one who told me it probably has to do with the white list.
The area that i added to looked like this:
public function initAcl()
{
$this->roles = $this->_getAllRoles();
$this->resources = $this->_getAllResources();
$this->rolePermission = $this->_getRolePermissions();
// we are not putting these resource & permission in table bcz it is
// common to all user
$this->commonPermission = array(
'ZF2AuthAcl\Controller\Index' => array(
'logout',
'index'
),
);
$this->_addRoles()
->_addResources()
->_addRoleResources();
}
This is the whole thing with parts i added.
namespace ZF2AuthAcl\Utility;
use Zend\Permissions\Acl\Acl as ZendAcl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Acl extends ZendAcl implements ServiceLocatorAwareInterface
{
const DEFAULT_ROLE = 'guest';
protected $_roleTableObject;
protected $serviceLocator;
protected $roles;
protected $permissions;
protected $resources;
protected $rolePermission;
protected $commonPermission;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function initAcl()
{
$this->roles = $this->_getAllRoles();
$this->resources = $this->_getAllResources();
$this->rolePermission = $this->_getRolePermissions();
// we are not putting these resource & permission in table bcz it is
// common to all user
$this->commonPermission = array(
'ZF2AuthAcl\Controller\Index' => array(
'logout',
'index'
),
'Frontend\Controller\Index' => array(
'index'
),
'Blog\Controller\Blog' => array(
'blog',
'list',
'view',
'UsMap',
'maps'
)
);
$this->_addRoles()
->_addResources()
->_addRoleResources();
}
public function isAccessAllowed($role, $resource, $permission)
{
if (! $this->hasResource($resource)) {
return false;
}
if ($this->isAllowed($role, $resource, $permission)) {
return true;
}
return false;
}
protected function _addRoles()
{
$this->addRole(new Role(self::DEFAULT_ROLE));
if (! empty($this->roles)) {
foreach ($this->roles as $role) {
$roleName = $role['role_name'];
if (! $this->hasRole($roleName)) {
$this->addRole(new Role($roleName), self::DEFAULT_ROLE);
}
}
}
return $this;
}
protected function _addResources()
{
if (! empty($this->resources)) {
foreach ($this->resources as $resource) {
if (! $this->hasResource($resource['resource_name'])) {
$this->addResource(new Resource($resource['resource_name']));
}
}
}
// add common resources
if (! empty($this->commonPermission)) {
foreach ($this->commonPermission as $resource => $permissions) {
if (! $this->hasResource($resource)) {
$this->addResource(new Resource($resource));
}
}
}
return $this;
}
protected function _addRoleResources()
{
// allow common resource/permission to guest user
if (! empty($this->commonPermission)) {
foreach ($this->commonPermission as $resource => $permissions) {
foreach ($permissions as $permission) {
$this->allow(self::DEFAULT_ROLE, $resource, $permission);
}
}
}
if (! empty($this->rolePermission)) {
foreach ($this->rolePermission as $rolePermissions) {
$this->allow($rolePermissions['role_name'], $rolePermissions['resource_name'], $rolePermissions['permission_name']);
}
}
return $this;
}
protected function _getAllRoles()
{
$roleTable = $this->getServiceLocator()->get("RoleTable");
return $roleTable->getUserRoles();
}
protected function _getAllResources()
{
$resourceTable = $this->getServiceLocator()->get("ResourceTable");
return $resourceTable->getAllResources();
}
protected function _getRolePermissions()
{
$rolePermissionTable = $this->getServiceLocator()->get("RolePermissionTable");
return $rolePermissionTable->getRolePermissions();
}
private function debugAcl($role, $resource, $permission)
{
echo 'Role:-' . $role . '==>' . $resource . '\\' . $permission . '<br/>';
}
}
06/10/2016 Additional information
I have also found that this ACL page is not in any of the pages in the module. The functions are not called out anywhere in any page nor is it "use" on any page. So how is it supposed to work?
Update 06/10/2017 - Area that has been fixed.
I have found where this is used in the module.php there is a whitelist that the pages have to be added too. Below is where you add them.
$whiteList = array(
'Frontend\Controller\Index-index',
*Add whatever modules/controller/action you do not want included*
'ZF2AuthAcl\Controller\Index-index',
'ZF2AuthAcl\Controller\Index-logout'
);
Above is the conclusion of my issue. I stumbled upon it. I did not look in the module.php file. That is where the answer was.
Here is a general implementation of Zend ACL. I followed this one. If you wish you can follow this one too.
Create a file named module.acl.php in the config/ folder of your module. This file contains configuration for roles and permissions. Modify this script as you need.
ModuleName/config/module.acl.php
return array(
'roles' => array(
'guest',
'member'
),
'permissions' => array(
'guest' => array(
// Names of routes for guest role
'users-signup',
'users-login'
),
'member' => array(
// Names of routes for member role
// Add more here if you need
'users-logout'
)
)
);
You need to import the following three classes and define and initialize some methods in the Module.php.
ModuleName/Module.php
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole;
use Zend\Permissions\Acl\Resource\GenericResource;
// Optional; use this for authentication
use Zend\Authentication\AuthenticationService;
Now lets create methods that will deploy ACL and check roles and permissions.
Module::initAcl()
public function initAcl(MvcEvent $e)
{
// Set the ACL
if ($e->getViewModel()->acl == null) {
$acl = new Acl();
} else {
$acl = $e->getViewModel()->acl;
}
// Get the roles and permissions configuration
// You may fetch configuration from database instead.
$aclConfig = include __DIR__ . '/config/module.acl.php';
// Set roles
foreach ($aclConfig['roles'] as $role) {
if (!$acl->hasRole($role)) {
$role = new GenericRole($role);
$acl->addRole($role);
} else {
$role = $acl->getRole($role);
}
// Set resources
if (array_key_exists($role->getRoleId(), $aclConfig['permissions'])) {
foreach ($aclConfig['permissions'][$role->getRoleId()] as $resource) {
if (!$acl->hasResource($resource)) {
$acl->addResource(new GenericResource($resource));
}
// Add role to a specific resource
$acl->allow($role, $resource);
}
}
}
// Assign the fully prepared ACL object
$e->getViewModel()->acl = $acl;
}
Module::checkAcl()
public function checkAcl(MvcEvent $e) {
// Get the route
$route = $e->getRouteMatch()->getMatchedRouteName();
// Use this if you have authentication set
// Otherwise, take this off
$auth = new AuthenticationService();
// Set role as you need
$userRole = 'guest';
// Use this if you have authentication set
// Otherwise, take this off
if ($auth->hasIdentity()) {
$userRole = 'member';
$loggedInUser = $auth->getIdentity();
$e->getViewModel()->loggedInUser = $loggedInUser;
}
// Check if the resource has right permission
if (!$e->getViewModel()->acl->isAllowed($userRole, $route)) {
$response = $e->getResponse();
// Redirect to specific route
$response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/404');
$response->setStatusCode(404);
return;
}
}
Now call those above methods on the onBootstrap() method in your Module.php. Initialize Module::initAcl() and check resource permission by adding Module::checkAcl() to the route event.
Module::onBootstrap()
public function onBootstrap(MvcEvent $e)
{
$this->initAcl($e);
$e->getApplication()->getEventManager()->attach('route', array($this, 'checkAcl'));
}
Let us know it helps you or not!

laravel validate Content-Type: application/json request

in laravel 5 i made a new request named ApiRequest.
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function rules()
{
return [
//
];
}
}
As you can see i am accepting only json data. And i am receiving the json in controller like this
public function postDoitApi(ApiRequest $payload) {
$inputJson = json_decode($payload->getContent());
$name = $inputJson->name;
}
Which is working fine. I am getting data in $name. But now i need to validate the input json.
I need to set validation rule in ApiRequest for the name key like this
public function rules()
{
return [
'name' => 'required|min:6'
];
}
Help me to do this. Thanks.
Laravel validates AJAX requests the same way. Just make sure you're setting one of these request headers on your request:
'Accept': 'application/json'
'X-Requested-With': 'XMLHttpRequest'
Validating any headers can be done in clean way two steps:
Step 1: Prepare header data to request data in prepareForValidation method.
public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
Step 2: Apply any validation rules that you want, (Here, you want your data exact to be application/json. so
public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
Complete Example looks like:
/**
* Class LoginRequest
*
* #package App\Requests
*/
class LoginRequest extends FormRequest
{
public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
}
You could use a validator method instead of rules method:
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function validator(){
//$data = \Request::instance()->getContent();
$data = json_decode($this->instance()->getContent());
return \Validator::make($data, [
'name' => 'required|min:6'
], $this->messages(), $this->attributes());
}
//what happens if validation fails
public function validate(){
$instance = $this->getValidatorInstance();
if($this->passesAuthorization()){
$this->failedAuthorization();
}elseif(!$instance->passes()){
$this->failedValidation($instance);
}elseif( $instance->passes()){
if($this->ajax())
throw new HttpResponseException(response()->json(['success' => true]));
}
}
}
return $inputJson->toArray();
and then pass to validator
$name = ['name'=>'er'];
$rules = array('name' => 'required|min:4');
$validation = Validator::make($name,$rules);
you can put following function in your ApiRequest form request.
public function validator(){
return \Validator::make(json_decode($this->getContent(),true), $this->rules(), $this->messages(), $this->attributes());
}

How to access configs from autoloaded config files in a layout / view script in Zend Framework 2?

I would like / have to manage some settings in ZF1 style and provide the view with the infomation about the current environment.
/config/application.config.php
return array(
...
'module_listener_options' => array(
...
'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php')
)
);
/config/autoload/env.local.php
return array(
// allowed values: development, staging, live
'environment' => 'development'
);
In a common view script I can do it over the controller, since the controllers have access to the Service Manager and so to all configs I need:
class MyController extends AbstractActionController {
public function myAction() {
return new ViewModel(array(
'currentEnvironment' => $this->getServiceLocator()->get('Config')['environment'],
));
}
}
Is it also possible to get the configs in a common view directly?
How can I access the configs in a layout view script (/module/Application/view/layout/layout.phtml)?
(My implementation/interpretation of) Crisp's suggestion:
Config view helper
<?php
namespace MyNamespace\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;
class Config extends AbstractHelper {
protected $serviceManager;
public function __construct(ServiceManager $serviceManager) {
$this->serviceManager = $serviceManager;
}
public function __invoke() {
$config = $this->serviceManager->getServiceLocator()->get('Config');
return $config;
}
}
Application Module class
public function getViewHelperConfig() {
return array(
'factories' => array(
'config' => function($serviceManager) {
$helper = new \MyNamespace\View\Helper\Config($serviceManager);
return $helper;
},
)
);
}
Layout view script
// do whatever you want with $this->config()['environment'], e.g.
<?php
if ($this->config()['environment'] == 'live') {
echo $this->partial('partials/partial-foo.phtml');;
}
?>
My implementation/interpretation of Sam's solution hint for the concret goal (to permit displaying the web analytics JS within the dev/staging environment):
DisplayAnalytics view helper
<?php
namespace MyNamespace\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;
class DisplayAnalytics extends AbstractHelper {
protected $serviceManager;
public function __construct(ServiceManager $serviceManager) {
$this->serviceManager = $serviceManager;
}
public function __invoke() {
if ($this->serviceManager->getServiceLocator()->get('Config')['environment'] == 'development') {
$return = $this->view->render('partials/partial-bar.phtml');
}
return $return;
}
}
Application Module class
public function getViewHelperConfig() {
return array(
'factories' => array(
'displayAnalytics' => function($serviceManager) {
$helper = new \MyNamespace\View\Helper\DisplayAnalytics($serviceManager);
return $helper;
}
)
);
}
Layout view script
<?php echo $this->displayAnalytics(); ?>
So this solution becomes more flexible:
/config/application.config.php
return array(
...
'module_listener_options' => array(
...
'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php')
)
);
/config/autoload/whatever.local.php and /config/autoload/whatever.global.php
return array(
// allowed values: development, staging, live
'environment' => 'development'
);
ContentForEnvironment view helper
<?php
namespace MyNamespace\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\View\HelperPluginManager as ServiceManager;
class ContentForEnvironment extends AbstractHelper {
protected $serviceManager;
public function __construct(ServiceManager $serviceManager) {
$this->serviceManager = $serviceManager;
}
/**
* Returns rendered partial $partial,
* IF the current environment IS IN $whiteList AND NOT IN $blackList,
* ELSE NULL.
* Usage examples:
* Partial for every environment (equivalent to echo $this->view->render($partial)):
* echo $this->contentForEnvironment('path/to/partial.phtml');
* Partial for 'live' environment only:
* echo $this->contentForEnvironment('path/to/partial.phtml', ['live']);
* Partial for every environment except 'development':
* echo $this->contentForEnvironment('path/to/partial.phtml', [], ['development', 'staging']);
* #param string $partial
* #param array $whiteList
* #param array $blackList optional
* #return string rendered partial $partial or NULL.
*/
public function __invoke($partial, array $whiteList, array $blackList = []) {
$currentEnvironment = $this->serviceManager->getServiceLocator()->get('Config')['environment'];
$content = null;
if (!empty($whiteList)) {
$content = in_array($currentEnvironment, $whiteList) && !in_array($currentEnvironment, $blackList)
? $this->view->render($partial)
: null
;
} else {
$content = !in_array($currentEnvironment, $blackList)
? $this->view->render($partial)
: null
;
}
return $content;
}
}
Application Module class
public function getViewHelperConfig() {
return array(
'factories' => array(
'contentForEnvironment' => function($serviceManager) {
$helper = new \MyNamespace\View\Helper\ContentForEnvironment($serviceManager);
return $helper;
}
)
);
}
Layout view script
<?php echo $this->contentForEnvironment('path/to/partial.phtml', [], ['development', 'staging']); ?>