Rack Warden: how can I access the message passed to the fail! method? - rack

When failing an authentication strategy in Warden, a message can be passed to the fail! method. How can I access this message in my default failure application action such that I can display it in a flash message? I tried request.env['warden'].message, but after looking at the code for Warden::Proxy this variable is only set for winning strategies. Thoughts?

When using the fail or fail! methods, you can obtain the failure message from the environment warden object.
Example:
def unauthenticated
flash[:alert] = env["warden"].message unless env["warden"].message.blank?
end
http://www.rubydoc.info/github/hassox/warden/Warden/Proxy#message-instance_method

Perhaps a different way of failing strategies (from recent documentation), is to use throw(:warden, :foo => 'bar'). Anything you throw with will be available in your failure application through request.env['warden.options'], including a string of the desired url as well. HTH

Related

How to set Cadence test workflow id?

I'm following https://cadenceworkflow.io/docs/go-client/workflow-testing/#setup and seeing errors with Activity error. {"WorkflowID": "default-test-workflow-id".
How do I go about setting the WorkflowID (eg so that it contains the test name)? I'm using Go.
It's not supported directly to set a workflowID. we recently realized it and are actively working on this.
At the mean time, if you have to test with workflowID, a workaround is to use
ReplayWorkflowExecution(ctx context.Context, service workflowserviceclient.Interface, logger *zap.Logger, domain string, execution workflow.Execution) error
But you have to mock the service interface for fetching history.
See https://github.com/uber-go/cadence-client/blob/b31c3bbfb06a1f96c6ad911a48237cfbc4f9a565/worker/worker.go#L166
I will update this thread when this feature is implemented.

How to fail a Gatling test from within "exec"?

A Gatling scenario with an exec chain. After a request, returned data is saved. Later it's processed and depending on the processing result, it should either fail or pass the test.
This seems like the simplest possible scenario, yet I can't find any reliable info how to fail a test from within an exec block. assert breaks the scenario and seemingly Gatling (as in: the exception throw doesn't just fail the test).
Example:
// The scenario consists of a single test with two exec creating the execChain
val scn = scenario("MyAwesomeScenario").exec(reportableTest(
// Send the request
exec(http("127.0.0.1/Request").get(requestUrl).check(status.is(200)).check(bodyString.saveAs("MyData")
// Process the data
.exec(session => {
assert(processData(session.attributes("MyData")) == true, "Invalid data");
})
))
Above the scenario somewhere along the line "guardian failed, shutting down system".
Now this seems a useful, often-used thing to do - I'm possibly missing something simple. How to do it?
You have to abide by Gatling APIs.
With checks, you don't "fail" the test, but the request. If you're looking for failing the whole test, you should have a look at the Assertions API and the Jenkins plugin.
You can only perform a Check at the request site, not later. One of the very good reasons is that if you store the bodyString in the Sessions like you're doing, you'll end using a lot of memory and maybe crashing (still referenced, so not garbage collectable). You have to perform your processData in the check, typically in the transform optional step.
were you looking for something like
.exec(http("getRequest")
.get("/request/123")
.headers(headers)
.check(status.is(200))
.check(jsonPath("$.request_id").is("123")))
Since the edit queue is already full.
This is already resolved in the new version of Gatling. Release 3.4.0
They added
exitHereIf
exitHereIf("${myBoolean}")
exitHereIf(session => true)
Make the user exit the scenario from this point if the condition holds. Condition parameter is an Expression[Boolean].
I implemented something using exitHereIfFailed that sounds like exactly what you were trying to accomplish. I normally use this after a virtual user attempts to sign in.
exitHereIfFailed is used this way
val scn = scenario("MyAwesomeScenario")
.exec(http("Get data from endpoint 1")
.get(request1Url)
.check(status.is(200))
.check(bodyString.saveAs("MyData"))
.check(processData(session.attributes("MyData")).is(true)))
.exitHereIfFailed // If we weren't able to get the data, don't continue
.exec(http("Send the data to endpoint 2")
.post(request2Url)
.body(StringBody("${MyData}"))
This scenario will abort gracefully at exitHereIfFailed if any of the checks prior to exitHereIfFailed have failed.

asp.net mvc azure "Error accessing the data store!"

I've started using the AspProviders code to store my session data in my table storage.
I'm sporadically getting the following error:
Description: Exception of type 'System.Web.HttpException' was thrown. INNER_EXCEPTION:Error accessing the data store! INNER_EXCEPTION:An error occurred while processing this request. INNER_EXCEPTION: ConditionNotMet The condition specified using HTTP conditional header(s) is not met. RequestId:0c4239cc-41fb-42c5-98c5-7e9cc22096af Time:2010-10-15T04:28:07.0726801Z
StackTrace:
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar)
System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) INNER_EXCEPTION:
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 484
System.Web.SessionState.SessionStateModule.GetSessionStateItem()
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) INNER_EXCEPTION:
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.get_Result()
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.ExecuteAndWait()
Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func`2 impl, RetryPolicy policy)
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(TableServiceContext svc, SessionRow session, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 603
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 480 INNER_EXCEPTION:
System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext()
Anyone run into this? The only useful information I've found is this, which I'm hesitant to do:
If you want to bypass the validation, you can open TableStorageSessionStateProvider.cs, find ReleaseItemExclusive, and modify the code from:
svc.UpdateObject(session);
to:
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
from here
Thanks!
So I decided to change this:
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
to this:
try
{
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
catch
{
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
So, I'll see how that works...
I've encountered this problem as well and after some investigation it seems to happen more often when you have more than one instance and you try to make calls in rapid succession in the same session. (e.g. if you had an auto complete box and making ajax calls on each key press)
This occurs because when you try to access the session data, first of all the web server takes out a lock on that session. When the request is complete, it releases the lock. With the table service provider, it updates this lock status by updating a field in the table. What I think is happening is that Instance1 loads the session row, then Instance2 loads the session row, Instance1 saves down the updated lock status and when Instance2 attempts to save the lock status it gets an error because the object isn't in the same state as when it loaded it (the ETag doesn't match any more).
This is why the fix that you found will stop the error from occurring, because by specifying the "*" in the AttachTo, when Instance2 attempts to save the lock it will turn off ETag checking (and over write the changes made by Instance1).
In our situation we have altered the provider so that we can turn off session for certain paths (the ajax call that was giving us our problems didn't need access to session data, neither did the loading of images) which may be an option for you depending on what is causing your problem.
Unfortunately the TableStorageSessionStateProvider is part of the sample projects and so isn't (as far as I'm aware, but I'll happily be told otherwise) officially supported by Microsoft. It does have other issues, like the fact that it doesn't clean up it's session data once a session expires, so you will end up with lots of junk in the session table and blob container that you'll have to clean up some other way.

What is the best way to log errors in Zend Framework 1?

We built an app in Zend Framework (v1) and have not worked a lot in setting up error reporting and logging. Is there any way we could get some level or error reporting without too much change in the code? Is there a ErrorHandler plugin available?
The basic requirement is to log errors that happens within the controller, missing controllers, malformed URLs, etc.
I also want to be able to log errors within my controllers. Will using error controller here, help me identify and log errors within my controllers? How best to do this with minimal changes?
I would use Zend_Log and use the following strategy.
If you are using Zend_Application in your app, there is a resource for logging. You can read more about the resource here
My advice would be to choose between writing to a db or log file stream. Write your log to a db if you plan on having some sort of web interface to it, if not a flat file will do just fine.
You can setup the logging to a file with this simple example
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../data/logs/application.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = 4
Also, I would suggest sending Critical errors to an email account that is checked regularly by your development team. The company I work for sends them to errors#companyname.com and that forwards to all of the developers from production sites.
From what I understand, you can't setup a Mail writer via a factory, so the resource won't do you any good, but you can probably set it up in your ErrorController or Bootstrap.
$mail = new Zend_Mail();
$mail->setFrom('errors#example.org')
->addTo('project_developers#example.org');
$writer = new Zend_Log_Writer_Mail($mail);
// Set subject text for use; summary of number of errors is appended to the
// subject line before sending the message.
$writer->setSubjectPrependText('Errors with script foo.php');
// Only email warning level entries and higher.
$writer->addFilter(Zend_Log::WARN);
$log = new Zend_Log();
$log->addWriter($writer);
// Something bad happened!
$log->error('unable to connect to database');
// On writer shutdown, Zend_Mail::send() is triggered to send an email with
// all log entries at or above the Zend_Log filter level.
You will need to do a little work to the above example but the optimal solution would be to grab the log resource in your bootstrap file, and add the email writer to it, instead of creating a second log instance.
You can use Zend_Controller_Plugin_ErrorHandler . As you can see on the documentation page there is an example that checks for missing controller/action and shows you how to set the appropriate headers.
You can then use Zend_Log to log your error messages to disk/db/mail.

facebook connect api "Cannot use string offset as an array in" error

Please help! I have been grappling with this error for days and I cannot for the life of me figure it out. I am using facebook connect and fetching a "contact_email" attribute using their api method users_getInfo.
The issue is that when I execute this PHP file, i get this error: "Cannot use string offset as an array in...". This error specifically refers to this line of code: $firstName=$user_details[0]['contact_email'];
I'm thinking this is because the user_getInfo method is not returning any results... However, the most ridiculous part about all this is that, I can execute the code below several dozens of times in a row SUCCESSFULLY without the above error, BUT THEN randomly without changing ANY code at all, I will suddenly encounter this error, in which case it will begin to give me an error several dozens of times, and then AGAIN without any code change, start executing successfully again.
This odd behavior occurs regardless of the attribute i am fetching.. (contact_email, first_name, last_name, etc.). I am running php 5.2.11. Is there something I'm missing??
Please Help!
include_once 'site/fbconnect/config.php'; //has $api_key and $secret defined.
include_once 'site/facebook-platform/client/facebook.php';
global $api_key,$secret;
$fb=new Facebook($api_key,$secret);
$fb->require_login();
$fb_user=$fb->get_loggedin_user();
$user_details=$fb->api_client->users_getInfo($fb_user,array('last_name','first_name','contact_email'));
$email=$user_details[0]['contact_email'];
$firstName=$user_details[0]['first_name'];
$lastName=$user_details[0]['last_name'];
Using the facebook php client API I was also receiving that error but my error was related to checking if the users are friends using the friends_areFriends php method.
//$results_array = $facebook->api_client->friends_areFriends($fb_user, $selected_friend_uid);
//$answer = $results_array[0]['are_friends'];
I would get this error when I assigned the $result, "Cannot use string offset as an array" and aparently the friends_areFriends method above was failing alot. My solution was to create a for loop that ran that code and then check $answer to see if it was an array using php method is_array() and executing the method call again if it wasn't. My loop was for 10 tries before just letting it fail. In the end, this check was severely degrating the performance of my facebook application. Instead, I removed the friends_areFriends api call alltogather and my facebook app performance was nice and fast again.
You could probably implement a similar feature allowing the method to retry itself if the result is not an array. The problem I think is on facebook's side, sometimes they are flooded and the requests do not complete successfully. I caution you not to retry more than 5 tries though because if you do a forever loop, rest assured they will ban you from the using the Facebook API for flooding it, so be careful.