Zend Application - a 404 error instead of Zend_Acl_Exception - how? - zend-framework

At the present, when I type a wrong address I get the following:
exception 'Zend_Acl_Exception' with message 'Resource 'default_asda' not found' in /home/alkimi/www/ ...
I would like to, instead of this, display a costumized 404.
How can we configure the framework for doing so?
Thanks a lot,
MEM

You get that exception when you attempt to query your ACL for a non-existant resource. You should check your ACL for the resource before calling isAllowed, eg
if (!$acl->has($resource)) {
// do something that triggers or leads to a 404
}

You can check if action and controller exists (is dispatchable) before checking permissions:
$front = Zend_Controller_Front::getInstance();
if (!$front->getDispatcher()->isDispatchable($request)) {
throw new Zend_Exception('Page not found', 404);
return false;
}

Related

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

PHPBrowser Hidden API method "_loadPage" is not following 301 Redirects

I am writing a test with PHPBowser, in Codeception v2.2.11 that uses the hidden API method of _loadpage.
I have added this into my \Helper\Api as follows:
public function loadpage($link)
{
$this->getModule('PhpBrowser')->_loadPage('POST', $link);
}
And call it in an Api Codeception test, as follows:
$link = 'http://www.fiercebiotech.com/contact';
$I->loadpage($link);
The issue I am facing is that when using _loadpage, it does not follow redirects. This exampled link when finally resolved is 301 redirected to:
http://www.fiercebiotech.com/contact-us.
Here is the header response console output when _loadpage opens $link.
I loadpage "http://www.fiercebiotech.com/contact"
[Request Headers] []
[Page] http://www.fiercebiotech.com/contact
[Response] 404
I need help getting _loadpage to not stop at ~/contact but follow the 301 redirect to ~/contact-us, so I can get the output header response to be
[page] http://www.fiercebiotech.com/contact-us
[response] 200
Currently I cant get _loadpage to follow 301 redirects. Anyone out there have success doing so?
Ive attempted to use Codeception REST function startFollowingRedirects and adding allow_redirects: true as follows, but neither technique seems to work (as the redirect is not followed).
class_name: ApiTester
modules:
enabled:
- WebDriver:
url: ''
browser: 'chrome'
window_size: 1200x993
clear_cookies: true
allow_redirects: true
- \Helper\Acceptance
- REST:
url: 'host'
depends: PhpBrowser
allow_redirects: true
- \Helper\Api
I found the solution to my issue:
The issue began with, as I suspected is that _loadpage does not follow redirects, it only loads the page requested and stops. In this case '~/contact-us', ignoring the fact that the page gets redirected to (with a 301) to '~/contact-us'.
I cant simply load the page (via _loadpage)
Get the header response
and assume that I will be getting the header response of the redirected URL
I will only get the header response of the original URL.
The Solution:
I have to in my foreach loop:
Go to the URL
send a GET
Grab the HTTP Header
Assert that the HTTP header has a 200OK response
Solution - As it is in Codeception code:
public function Validate_httpStatus_mainNav($mainNavLocator)
{
//Used to test main navigation -- 404 tests
$I = $this;
$mainNavLinks = $I->grabMultiple($mainNavLocator, 'href');
codecept_debug($mainNavLinks);
foreach ($mainNavLinks as $link) {
$I->amOnUrl($link);
$I->sendGET($link);
$I->grabHttpHeader($link);
$I->canSeeResponseCodeIs(HttpCode::OK);
}
}

Getting HTTP response from balanced

If I am using PHP code such as
$card = Balanced\Card::get("/v1/marketplaces/TEST-MP4K6K0PWGyPtXL4LZ42sQSb/cards/CC5N3HHUDrAyvhNwQOoUd3UX");
$card->unstore();
or
$customer->addCard($card)
how do I read the HTTP response from balanced to know if it has worked or what the error is?
The Balanced client libraries are written so that they will throw exceptions if there is a non 2xx HTTP response from the API.
The correct way to tell if the addCard operation failed for example would be to write some code that looks like
try {
$customer->addCard($card)
} catch (Balanced\Error $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

fulljid is empty after connection to BOSH service with XMPHP

I am trying to pre-bind an XMPP session via XMPHP and pass the rid/sid/jid to a strophe client to attach to the session.
connection code here:
$conn = new CIRCUIT_BOSH('server.com', 7070, $username, $pass, $resource, 'server.com', $printlog=true, $loglevel=XMPPHP_Log::LEVEL_VERBOSE);
$conn->autoSubscribe();
try{
$conn->connect('http://xmpp.server.com/http-bind', 1, true);
$log->lwrite('Connected!');
}catch(XMPPHP_Exception $e){
die($e->getMessage());
}
I am getting the rid and sid but the fulljid in the $conn object stays empty and I cant see a session started on my openfire admin console.
If I create the jid manually by using the given resource and passing jid/rid/sid to strophe to use in attach, I get the ATTACHED status and I see calls from the client to the BOSH ip but I still dont see a session and I cant use the connection.
Strophe Client Code:
Called on document ready:
var sid = $.cookie('sid');
var rid = $.cookie('rid');
var jid = $.cookie('jid');
$(document).trigger('attach', {
sid: sid,
rid: rid,
jid: jid,
});
$(document).bind('attach', function (ev, data) {
var conn = new Strophe.Connection(
"http://xmpp.server.com/http-bind");
conn.attach(data.jid, data.sid, data.rid, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
} else if (status === Strophe.Status.ATTACHED){
$(document).trigger('attached');
}
});
Object.connection = conn;
});
I think the problem starts on the XMPPHP side which is not creating the session properly.
'attached' is triggered but never 'connected', is status 'connected' supposed to be sent?
What am I missing?
Ok, solved, I saw that XMPPHP lib didn't create a session at all on the openfire server, so I wrote a simple test for the XMPP class which was good and created the session, and for the XMPP_BOSH class that didn't manage create one. Then I saw the issue report here: http://code.google.com/p/xmpphp/issues/detail?id=47 comment no.9 worked, it fixed the issue by copying the processUntil() function from the XMLStream.php to BOSH.php, still can't figure out why this is working. Then I found I had an overlapping bug also with some of the passwords set for users on the openfire server. These passwords contained these ! # % ^ characters, for some reason the XMPP_BOSH is sending the password corrupted or changed so I got Auth Failed exception. Changing the password fixed the issue and I can now attach to the session XMPPHP created with the Strophe.js library.

displaying page not found error with zend acl

whenever a controller is called if it is not registered in zend acl then we ususally get erro r like this
Fatal error: Uncaught exception 'Zend_Acl_Exception' with message
'Resource 'hsfasfdadsf' not found' in /usr/share/php/libzend-framework-php/Zend/Acl.php:365
Stack trace:
#0 /var/www/update/library/Management/Access.php(55): Zend_Acl->get('hsfasfdadsf')
#1 /usr/share/php/libzend-framework-php/Zend/Controller/Plugin/Broker.php(309): Management_Access->preDispatch(Object(Zend_Controller_Request_Http))
#2 /usr/share/php/libzend-framework-php/Zend/Controller/Front.php(941):
isn't there a way to check if the controller and action is registered in zend acl, i tried
if(!$acl->get($controller))
{
$request->setControllerName('error');
$request->setActionName('notfound');
}
but did not work
First solution:
Avoid those exceptions, e.g.
if (!$acl->has($your_resource)) {
// .. handle it the way you need
}
Second one
Handle those exceptions in ErrorController, i.e.:
if ($errors->exception instanceof Zend_Acl_Exception) {
// send needed headers...
// prepare log message...
// render info: resource_not_found.phtml
$this->_helper->viewRenderer('resource_not_found');
}