Specific issue with a fetch request on input - input

I have an input field and when on input a function is called. It stops the timeout if there is one, if not then we know the user stopped typing. If the timeout finishes it makes a fetch request to determine if the user's input is valid. Lastly, if the fetch request returns valid, the user's input goes into a list. It will never be valid if a special character exists.
My problem is that when a user enters a valid input, after the 1-second timeout finishes, if the user just happens to within that microsecond window between the fetch and the sending to the list a user enters a special character... the user's valid input plus the special character will go into the list.
My solution is to disable the input field while awaiting the pending promise to resolve (which takes maybe a quarter of a second).
My boss however wants me to see if there is a better solution out there. Since my situation feels rather unique I thought I'd just ask other developers if they perhaps did have a better solution.
Thank you for your help everyone.
The code is something like:
function (){
if (timeoutexists){
clearTimeout
}
timeout = setTimeout ({
submitting = true
fetch user input
submitting = false
if fetch resolve input is valid and put users input in list else it's invalid and do not put user input in list.
})
}

Related

Change of Security Stamp

When a user's password is updated I want the Security stamp value to be updated every time that happens. I believe that is how Security stamp works from my research.
I place this code in the ApplicationUserManager.cs but this isn't working:
private static string NewSecurityStamp()
{
return Guid.NewGuid().ToString();
}
What and where do I need to get the security stamp value to change each time an update is made to the user's account?
That is what happens. However, the security stamp is only re-validated on an interval (every 30 minutes, by default), to reduce the number of database queries being made. You can lower this interval, even to zero, which effectively makes the stamp be re-validated with each request. However, that will increase the chatter back and forth to the database.
services.Configure<SecurityStampValidatorOptions>(o =>
{
// WARNING: this will issue a query for every request
// You might want to rather just compromise with an interval
// less than 30 minutes (5 minutes, 10 minutes, etc.)
o.ValidationInterval = TimeSpan.Zero;
});
An alternative option is to simply log the user out after such a change. If the goal is to simply make them re-login, that should do the trick much better. Just inject SignInManager<TUser>, and then call SignOutAsync on that instance. You'll need to redirect the user afterwards. That could be directly to the sign in page or to some area of the site that is protected, which will then cause them to be taken to the sign in page to authenticate. In either case, a redirect is necessary to have the auth cookie actually be deleted.

Idiomatic authentication in Elm

I'm trying to wrap my head around Elm. I have experience in Haskell, and a bit of Erlang.
I want to complete the following exercise:
User is shown a login form
On submit, the frontend makes a request to localhost/auth to try and receive an auth token.
On success, the homepage is shown, which fetches some data.
On failure, the login screen displays an error.
This is quite basic, but hopefully complex enough to model the behaviour of a real webapp.
My first problem is with the Model. I only need the data if the client is authenticated. Should I wrap this in something similar to a Maybe monad?
type Model
= NoAuth String String
| AuthFetching
| AuthFailed err
| AuthSuccess String
And then the login screen can display a spinner, and error, or redirect to a new page.
This feels like it ties the rest of the applications state to the authentication state. Although is is "correct", it feels wrong to have the whole model be a (variant type?) with only one record.
It "feels" more correct to have the model like so:
type FetchStatus
= Loading
| Success val
| Err err
type Model =
{ token : RequestStatus String
, data : List number
}
But whenever you update the model, you now need to check if token is still present - i.e. pattern match within the record. In the first example, you only needed to pattern match on the whole model, which is a bit simpler.
And to hold the login form state, I'd need to add extra fields:
type Model =
{ token : RequestStatus String
, data : List number
, username : String
, password : String
}
Which feels incorrect because the password should not be held in memory after login. I'd hold these in records, but I cannot use records in custom type declarations.
All in all, I'm a bit confused. Can someone please shed some light on the most "correct", idiomatic way to do this?
All authorization related stuff should be handled on the backend side. Elm's job is only to display what server has sent to it. In my opinion the first option you proposed is the best for such a little example, but in more real-life application the typesystem would be more complex:
type LoginForm =
{ username : String
, password : String
}
type Activity
= Login LoginForm
| LoginSuccess
| LoginFailure String
type Model =
{ loggedUser : Maybe String
, activity : Activity
, ...
}
You don't need (and shouldn't) keep password on frontend. You also shouldn't perform any authorizations on the client side, as the client may easily replace any script in his browser. The backend will track whether the user is logged in by eg. session cookies. In this scenario even if the loggedUser value is set to Just "someguy" and "someguy" is not marked as logged in the server database, any action that requires authorization shall fail.
Summarizing, handling login and giving permissions to access any content is a job for backend. Elm is frontend language, so it's only purpose here is to display things.

Wit.ai seems to be jumping randomly between stories

I have two separate simple stories on my Wit.ai bot,
the first one takes in the word "Debug", sends "test" then runs a function that outputs context stuff to the console called test_context()
the second one takes in an address, runs a function that changes the context called new_session(), then sends a confirmation of the change to the user structured like "your location has been changed to {address}"
when I type directly into the wit.ai test console it seems to correctly detect the stories and run the corresponding functions, but when I try to use it through the Node.js API it seems to act completely randomly.
Sometimes when typing in an address it will run test_context() followed by new_session(), then output no text, sometimes it will just output the test text followed by the address text and run no functions, sometimes it will act correctly.
The same behavior happens when inputting "Debug" as well.
The back end is set up correctly, as 2 other stories seem to be working perfectly fine.
Both of these stories were working fine earlier today, I have made no changes to the wit stories themselves and no change to the back-end has even touched the debug function.
Is this a known issue?
I encountered this problem as well.
It appears to me as when you do not handle setting context variables in the story from wit.ai correctly (by setting them to null for example), it messes up the story. As a developer it is your own responsability to handle the story correctly "client side", so I can understand wit.ai lets weird stuff happen when you do not do this. Maybe wit.ai decided to jump stories to keep their bot from crashing, still remains a bit mysterious to me. Maybe your problem is of a different kind, just sharing a similair observation and my solution.
Exactly for reasons of testing I created three stories;
handle greetings
tell what the weather in city x is
identify when you want to plan a meeting
The bot is connected to facebook and I handle actions (like planning a meeting) on my nodejs express server.
I said to the bot "I want to plan a meeting tomorrow", resulting in a wit date/time. One timeslot by the way. This is going ok. Then I sent the message "I want to plan a meeting this morning". This resulted in TWO date/time variables in the wit.ai context. In turn, my code could not handle this; two timestamps resulted in null (probably json message getting more complicated and I try to get the wrong field). This in turn resulted in null for the context variable that had to be returned.
So what I did is to catch the error for when the context variable is not filled and just fill in [wit.js could not find date]. This fixed the problem, even though I now of course need to handle this error better.
Old code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
},}
New, working code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
if(myDateTime){
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
} else {
context.appointmentText = '[wit.js could not find date]'
return resolve(context);
}
});
},
Hope this helps

Getting a HTTP Status code 404 on web_custom_request in Loadrunner

I have a web_custom_request method that needs to handle dynamic item data
web_custom_request("create",
"URL=someurl\create",
"Method=POST",
"Resource=0",
"RecContentType=application/json",
"Referer=someurl",
"Snapshot=t6.inf",
"Mode=HTML",
"EncType=application/json",
"Body={\"actions\":{\"name\":\"value\"}}"
LAST);
To address the dynamic name-value pair parameters that come into play, I had built a bufferthat would hold the Body string. I have used correlation and looping to achieve that. Code towards the end of building this buffer looks like this
lr_param_sprintf("s_buffer", "\\\"actions\\\":{%s}",paramStr);
lr_output_message("Final Actions string is %s", lr_eval_string("{s_buffer}"));
Output for above lr_output_message is
Final Actions string is \"actions\":{\"name\":\"value\"}
I replaced Body parameter in web_custom_request with the buffer I had built
web_custom_request("create",
"URL=someurl\create",
"Method=POST",
"Resource=0",
"RecContentType=application/json",
"Referer=someurl",
"Snapshot=t6.inf",
"Mode=HTML",
"EncType=application/json",
"Body={s_buffer}"
LAST);
I receive a HTTP Status-Code=400 (Bad Request) indicating the format of web_custom_request is wrong. I would highly appreciate if someone could help me with the Body parameter so that the web_custom_request embraces it like the way it should.
Record it three times. First two with the same login session. The third with another one. You likely have something that is going to change based upon data which is not being handled in the body appropriately.

Docpad : show error/success message on contact form

I added a route in my docpad.coffee file to handle form submissions, that I validate using the express-validator middleware. Now depending on the validation, I want to redirect the users to the same contact page but displaying either a success message when validation is successful (here I'll send an email), or display the error messages.
I didn't manage to pass the validation message to the template to display it. I tried almost all combinations of dynamic: true/false, res.locals = validationMessages, res.sessions = validationMessages, res.templateData = validationMessages with no success.
Furthermore, adding dynamic: true made the changes to the content not appear at all, whatever refresh strategy I use (private mode, cleaning cache, relaunching Docpad, refreshing without cache, etc.). I should probable file a bug about it.
How to ?
I'm using Docpad 6.53.0 (latest to date), node 0.10.15, on OS X 10.8.4
I cheated on this one a bit by appending a hash to the redirect url (eg: "www.mywebsite.com/#messagesent"). I then use client side javascript to read the hash and then show the appropriate message. Something like this:
if (location.hash == "#messagesent") {
$('#message-sent').show();
setTimeout(function () {
$('#message-sent').fadeOut(1000);
}, 1000);
}
Not quite what you were asking though :)