CakePHP - How to make routes with custom parameters? - cakephp

My Cake URL is like this:
$token = '9KJHF8k104ZX43';
$url = array(
'controller' => 'users',
'action' => 'password_reset',
'prefix' => 'admin',
'admin' => true,
$token
)
I would like this to route to a prettier URL like:
/admin/password-reset/9KJHF8k104ZX43
However, I would like the token at the end to be optional, so that in the event that someone doesn't provide a token it is still routed to:
/admin/password-reset
So that I can catch this case and redirect to another page or display a message.
I've read the book on routing a lot and I still don't feel like it explains the complex cases properly in a way that I fully understand, so I don't really know where to go with this. Something like:
Router::connect('/admin/password-reset/:token', array('controller' => 'users', 'action' => 'password_reset', 'prefix' => 'admin', 'admin' => true));
I don't really know how to optionally catch the token and pass it to the URL.

You'll want to use named parameters. For an example from one of my projects
Router::connect('/:type/:slug',
array('controller' => 'catalogs', 'action' => 'view'),
array(
'type' => '(type|compare)', // regex to match correct tokens
'slug' => '[a-z0-9-]+', // regex again to ensure a valid slug or 404
'pass' => array(
'slug', // I just want to pass through slug to my controller
)
));
Then, in my view I can make a link which will pass the slug through.
echo $this->Html->link('My Link', array('controller' => 'catalogs', 'action' => 'view', 'type' => $catalog['CatalogType']['slug'], 'slug' => $catalog['Catalog']['slug']));
My controller action looks like this,
public function view($slug) {
// etc
}

Related

CakePHP 3 use default routing in some cases

I have a CakePHP 3.5 website. It was necessary to set slugs without any url prefixes like /pages/slug, so I wrote the following rule:
$routes->connect(
'/:slug',
['controller' => 'Pages', 'action' => 'redirectPage']
)
->setMethods(['GET', 'POST'])
->setPass(['slug'])
->setPatterns([
'slug' => '[a-z0-9\-_]+'
]);
It works nice, but in some cases I want cakePHP to route as default (Controller/Action/Params). For example, I want /admin/login to call 'login' action in 'AdminController'.
I have two ideas that doesn't need exact routings, but I can't make any of them to work:
Filtering some strings by pattern: It would be nice if I could filter some strings, that if slug doesn't match pattern, it will simply skip the routing rule.
Create a '/admin/:action' routing rule, but then I cant use :action as an action variable. It causes errors.
$routes->connect(
'/admin/:action',
['controller' => 'Admin', 'action' => ':action']
)
Any ideas?
Thanks
You can use prefix for admin restricted area.
Example:
Router::prefix('admin', function ($routes) {
$routes->connect('/', ['controller' => 'Users', 'action' => 'login']);
$routes->fallbacks(DashedRoute::class);
});
$routes->connect('/:slug' , [
'controller' => 'Pages',
'action' => 'display',
'plugin' => NULL
], [
'slug' => '[A-Za-z0-9/-]+',
'pass' => ['slug']
]);
Now, for example, path /admin/dashboard/index will execute method in Admin "subnamespace" \App\Controller\Admin\DashboardController::index()
Its nicely described in docs: https://book.cakephp.org/3.0/en/development/routing.html#prefix-routing
Try this:
$routes->connect(
'/admin/:action',
['controller' => 'Admin'],
['action' => '(login|otherAllowedAction|someOtherAllowedAction)']
);
Also, your slug routes seems to not catch /admin/:action routes, b/c dash is not allowed there: [a-z0-9\-_]+

CakePHP: storing origin URL when redirecting to login page using Permit class

In Config/Permit.php we define rules, which actions are permitted without login. It looks like that:
Permit::access(
array(
'controller' => array('incentives'), 'action' => array('downloadvoucher')
),
array(),
array()
);
(...)
Permit::access(
array('controller' => $controllers),
array('auth' => true),
array('redirect' => array('controller' => 'users', 'action' => 'login'), 'message' => __('Your session has ended. Please log in again.'))
);
The redirect is defined at the bottom. What would be the right approach to achieve the following: if the user calls an URL (note: by default in the following format: base/controller/action/?q=1&q=2#hash or with routing) he will be redirected to the users/login page, but we would like to store somewhere from where he is coming (for example appended to the URL).
I tried this:
array('redirect' => array('controller' => 'users', 'action' => 'login', '?' => $this->here()), 'message' => __('Your session has ended. Please log in again.'))
but of course it doesn't work - the here()method is not defined in the Permit class.
Any better ideas?

Routing all but certain parameters in CakePHP

I'm trying to set up a routing definition in my project which will allow users to have profiles accessible by simply using their username as the only parameter in the url, like www.example.com/username as opposed to www.example.com/user/view/username
I've set up a catch all route to go to an action which checks if the user exists, as the last route in the config file, and it works, but it over rides all of the basic routing that cake does. Meaning that I would have to define a route for every controller I want to provide access to just to make sure I never make it to the catchall. My routes:
Router::connect('/events/edit/*', array('controller' => 'events', 'action' => 'edit'));
Router::connect('/events/view/*', array('controller' => 'events', 'action' => 'view'));
Router::connect('/events/add', array('controller' => 'events', 'action' => 'add'));
Router::connect('/events/*', array('controller' => 'events', 'action' => 'index'));
Router::connect('/*', array('controller' => 'users', 'action' => 'view'));
So, this will allow me to access my events page, but any other pages get sent to the second router, expectedly.
What I'd like is to have is a route that does the basic cake function of /controller/action/param if the controller exists, but have it fall through to the last route which goes to the user/view page otherwise.
My question is, for what I'm trying to accomplish, am I doing this the right way? If I need to define a route for every controller I want access to, I will, but I have to think there's a better way to accomplish this.
Thanks
According to the my understanding of your question, I think You can proceed like this.
App::uses('UserRoute','Lib');
Router::connect('/:user_name', array('controller' => 'users', 'action' => 'view'),
array('routeClass'=>'UserRoute', 'pass' => array('user_name')));
and in your app/lib create a file UserRoute.php like this
<?php
App::uses('Lib', 'CakeRoute');
class UserRoute extends CakeRoute {
function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
App::import('Model', 'User');
$User = new User();
$user_count = $User->find('count',array(
'conditions' => array('User.username' => $params['user_name']),
'recursive' => -1
));
if ($user_count) {
return $params;
}
return false;
}
}
Hope this will help you..

Weird redirect issue when using Auth and admin prefix in CakePHP

I'm using the admin prefix in my Cakephp app, for some admin views. I'm also using Auth to restrict access to those views, based on a role field in the User table. Pretty standard.
The problem is, that when an unauthorized user tries to go to, say, admin/users, (in this case the index action is prohibited), they are redirected to /admin/users/login which of course, doesn't exist.
This doesn't happen with actions that do not have the admin prefix. Those behave just fine.
Why are users being sent to to a login that is prepended by the admin prefix and the prohibited action?
Anyone who is still having trouble with this, according to the documentation you can use an array or a string in loginAction (Documentation).
Using an array and setting 'admin' => false was still giving me trouble, so I tried using a string instead:
public $components = array(
'Auth' => array(
'loginRedirect' => array('controller' => 'dashboards', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'loginAction' => '/users/login',
'authorize' => array('Actions')
),
);
This ended up solving my problem. Hopefully it works for you as well.
You need to override the specific prefix in the routing array.
$this->Auth->loginAction = array(
'controller' => 'users',
'action' => 'login',
'admin' => false
);
or, if you're using multiple prefixes, you can dynamically remove the prefix name like this:
$this->Auth->loginAction = array(
'controller' => 'users',
'action' => 'login',
$this->request->prefix => false
);

cakephp named parameters break REST based web service

I have a json REST based in the form of:
Router::mapResources('Test');
Which is equivalent to for the index method to:
Router::connect( '/Test',
array(
'controller' => 'ChannelSources',
'action' => 'index',
'[method]' => 'GET' ),
array();
I am trying to add support for named parameters this method.
but apparently its breaks the Router method as an index action is not part of the URL
i have tried using
Router::connectNamed(array('somenameparam'));
But it failed.
I would create a specific route so that you can pass in the right parameters, then you can pass your params into the route.
Have a look at, http://book.cakephp.org/2.0/en/development/routing.html#passing-parameters-to-action
Router::connect(
'/blog/:id-:slug', // E.g. /blog/3-CakePHP_Rocks
array('controller' => 'blog', 'action' => 'view'),
array(
// order matters since this will simply map ":id" to $articleId in your action
'pass' => array('id', 'slug'),
'id' => '[0-9]+'
)
);

Resources