Lumen Regular Expression Constraints throw NotFoundHttpException - lumen

I have a list of routes, some are using parameters and everything is working correctly.
My problem happen when I try to constrain the parameter (to check the it is valid before executing my controller).
Following the documentation I did it this way :
$router->group(['middleware' => 'auth:api'], function () use ($router) {
$router->get('/user/{userId:[a-z0-9]+}', 'UserController#userByUserIdGet');
});
But all I receive is a NotFoundHttpException meaning that it doesn't match my route.
I can't see where my mistake is. Any idea?
Thank you.

The error you recieve, if your route doensn't exists is a MethodNotAllowedHttpException - your code and the regex for your route do work correctly, so I am assuming, that your error could have an other reason.
Maybe you should check this:
NotFoundHttpException with Lumen

OK stupid error from my side.
I'm passing UUID as userID parameter... AND they have a dash in them.
So my regex should be this one
$router->group(['middleware' => 'auth:api'], function () use ($router) {
$router->get('/user/{userId:[a-z0-9\-]+}', 'UserController#userByUserIdGet');
});

Related

Redirect to a resource route with parameters Laravel

I try to redirect to a resource route with paramateres in my laravel controller
Redirect::route('users.show', array('user'=> $user->account_id));
but the parameter is never getting passed through.
What I'm doing wrong?
You can Try like this
redirect()->route('users.show', ['user'=> $user->account_id]);
It should work. May be you are passing a null value.
Check the value of $user->account_id using dd($user->account_id);
Try to use this:
Redirect::route('users.show', ["user" => $user->account_id]);
You have to add "return" keyword before "redirect". Try like this
return redirect()->route('users.show', $user->account_id);

Cannot pass idpHint option to Keycloak

I am using IDP provider for authentication and trying to bypass the standard keycloak login screen (so I need to go immediately to the IDP specific authorization screen). According to this documentation https://keycloak.gitbooks.io/server-adminstration-guide/content/topics/identity-broker/suggested.html we can simply provide idpHint for this. Though that doesn't work.
let keycloakAuth : any = new Keycloak('keycloak.json');
keycloakAuth.createLoginUrl({idpHint: 'ad-oidc'});
It failed with
Uncaught TypeError: Cannot read property 'redirectUri' of undefined
at Keycloak.kc.createLoginUrl (keycloak-core.js:212)
As far as I understand that's because adapter is not created yet. So probably we need to pass this option sometimes later (but not sure at which phase).
I was able to do this only by hardcoding the idpHint inside of the keycloak-core.js itself temporarily. Looking forward to avoid this.
Thanks in advance.
I solved the problem like this:
let kc = Keycloak('/backend/frontend.json');
let kcLogin = kc.login;
kc.login = (options) => {
options.idpHint = 'some-hint';
kcLogin(options);
};
kc.init({ onLoad: 'login-required' }).success((authenticated) => {
console.log('Logged in!');
}});
This way the very first login attempt already uses the hint. I somehow don't get, why there is no simple way to use the idpHint option, the inceptor is the only way I found to use it, without directly patching the keycloak.js file.
It would be perfect, if the Keycloak constructor just would accept an idpHint option.
You have to initialize the keycloak object first.
You don't need to call createLoginUrl(), you need to call login(options) which by its turn going to call createLoginUrl.
var keycloak = new keycloak(JSON);
keycloak.init().success(function(authenticated){
if(authenticated){
console.log("logged in");
}
else{
keycloak.login({idpHint:'ad-oidc'});
}
}).error(function(){
console.log("failed to initialize");
});
Sorry there might be syntax error but I hope it explains how to do it.

CakePHP 2.0 send eMail error

I'm using the SignMeUp Plugin for user registration in CakePHP 2.0 (whose homepage seems to be down atm).
For the most part, everything works perfectly fine, except that I'm getting the following seemingly unrelated error whenever a function uses $this->Email->send() :
Trying to get property of non-object
[CORE\Cake\View\Helper\PaginatorHelper.php, line 111]
The line is:
public function beforeRender($viewFile) {
$this->options['url'] = array_merge($this->request->params['pass'],
$this->request->params['named']);
Not sure how that is actually related to the email, so I'm at a loss as to what can possibly cause this error, as the emails are actually being sent no problem.
An example function in the plugin would be:
protected function __sendActivationEmail($userData) {
$this->__setUpEmailParams($userData);
$this->__parseEmailSubject('activation', $userData);
if ($this->__setTemplate(Configure::read('SignMeUp.activation_template'))) {
if ($this->Email->send()) {
return true;
}
}
}
I personally see nothing wrong with this either... Not sure what else could possibly be causing this error. If someone of you has any kind of idea, that would really be appreciated!
BTW: If I set debug to 0, I get a blank page after the function executes instead of a proper redirect, so that's not a solution.
I had the same problem because I included the paginator as helper:
public $helpers = array('Time','Paginator');
In CakePHP 2.0 the Paginator is always included and for some reason there seems to be a conflict with the sendMail if you include the helper in the controller. So if you delete the Paginator from the helpers list it should work without error.

Why is Play! breaking apart the {format} param in routes?

Must be a syntax issue on my part, but can't quite pin it:
In my controller I have this defined:
request.format match {
case "json" => Json(output)
case "xml" => toXml(parse(output.toString))
case _ => BadRequest
}
And in my routes I have this defined:
# Map the API to the proper domain
GET /{key}/{action}/{param}.{format} API.{action}
POST /{key}/{action}/{param}.{format} API.{action}
I posted something like: /34523452345/job/today.json
So when I go to actually run the request, it takes {param} and includes the period. So the result for {param} is today.js and the {format} becomes on
The catch if I switch the period to a forward slash / it works just fine
What is the cause of the problem?
I believe you have to escape the dot as in \., as Play uses regexp in the routes files.

PHPUnit and Zend Framework assertRedirectTo() issue

I'm having an issue with assertRedirectTo() in a test I have created, below is the code I have used:
public function testLoggedInIndexAction() {
$this->dispatch('/');
$this->assertController('index');
$this->resetResponse();
$this->request->setPost(array(
'type' => 'login',
'username' => 'root',
'password' => 'asdasd',
));
$this->request->setMethod('POST');
$this->dispatch('/');
$this->assertRedirectTo('/feed/');
}
You log in through / (index.php/) and submit post details there and the it redirects you to /feed/ (index.php/feed/). The details I have supplied are correct and should work however I am having issues whereby PHPUnit is saying they are incorrect:
There was 1 failure:
1) IndexControllerTest::testLoggedInIndexAction
Failed asserting response redirects to "/feed/"
/home/public_html/mashhr/library/Zend/Test/PHPUnit/Constraint/Redirect.php:190
/home/public_html/mashhr/library/Zend/Test/PHPUnit/ControllerTestCase.php:701
/home/public_html/mashhr/tests/application/controllers/UserControllerTest.php:36
#poelinca: No, it is simply a case of Zend_Test being unreliable in registering a redirect (even if it has been called correctly!)
In his case, the real app is no doubt redirecting the user properly, but the Zend_Test environment is having trouble registering properly called redirects. The best response I can think of is to omit any failing assertRedirect which actually works in the application.
This is not an optimal situation, but unless you're prepared to dig into the Zend code to see where the problem is, this may be your best bet for efficiency. This is an example of what causes unit testing to get a bad name: Having to alter code to pass tests which actually work already.
See http://framework.zend.com/issues/browse/ZF-7496 Which is misleadingly specific in its title: the problem relates to all redirects, especially those which must set headers and exit instead of dispatching the original controller.
For whatever reason, this behavior causes Redirects not to always fail, but to be highly unreliable instead! If anyone knows a better workaround to this problem (which is general, and probably unrelated to the OP's code) please let us know.
stumbled on this question while having the same problem. I ended up doing the following:
$this->assertRedirect();
$responseHeaders = $this->response->getHeaders();
$this->assertTrue(count($responseHeaders) != 0);
$this->assertArrayHasKey('value', $responseHeaders[0]);
// in my case I'm redirecting to another module
$this->assertEquals('/module/controller/action', $responseHeaders[0]['value']);
I've responded this answer in http://zend-framework-community.634137.n4.nabble.com/Zend-Test-failing-on-AssertRedirectTo-td3325845.html#a4451217
I'm having this same issue... A possible way to assert it could be in
PHPUnit and Zend Framework assertRedirectTo() issue
But the problem is there.. My example is (wich actually works if done manually):
// controller modules/picking/orders/product
$orderId = $this->_getParam('oId');
if (empty($orderId)) {
return $this->_redirect('picking/orders/browse/invalid/empty');
}
// test
$this->dispatch('picking/orders/product');
$this->assertRedirect(); // ok
$this->assertRedirectTo('picking/orders/browse'); // error
$this->assertRedirectTo('picking/orders/browse/invalid/empty'); // error
After I've found the error!
Actually, following the example above i've found that the string comparizon in my example has an error:
'.../public//picking/orders/browse/invalid/empty'
'.../public/picking/orders/browse/invalid/empty'
... fixing the preprended slash solve the problem! ;)
So if i understand right , you wrote a test that fails ( id say this is perfect ) .
In order to make the test pass you need to debug you're app and see where the problem is , in this case you need to have a look at the actual redirection ( or eaven the post fields sent by the form ) , maybe check the routing too . I gues nobody here will be able to answer you're question unless you post the code in you're index controller/form/view and feed controller .
For future reference, I had this issue today and it was caused by the Url class failing to build a valid url (I was passing the wrong parameters) but not reporting an error to PHPUnit (probably because PHPUnit masks the error).
Correcting the url parameters fixes the url and with it the assertion.