MVC asp.net server side timer to prevent user from editing timer - javascript

I have a MVC asp.net quiz application. You have a variable amount of time to take the quiz, and if time runs out, then the answers are automatically submitted.
Currently, I have the timer setup in Javascript, with the amount of time being held in the Controller - Session["EndTime"]. But, my understanding is that a user can edit the Javascript and change the timer when it is implemented in Javascript. If true, how do I run the timer in the Controller and send an Action once the timer runs out?

The server can't force the browser to submit anything, that's what the JavaScript code would do. And, yes, the user can choose to modify that if he or she wants.
What the server would do is keep track of two things:
A unique identifier for that instance of the "test"
A date/time stamp of when the "test" began (or, conversely, when it expires, as either value carries the same amount of information)
The first value is included in the form sent to the browser, basically just a hidden form field. When a test result is posted to the server, the server-side code uses the identifier to look up the persisted date/time stamp to compare it with the current date/time. If more time than expected has elapsed, reject the test results with an error.
Basically, the server-side code can't force the user to submit the results. But it can reject results which aren't submitted in time.

Related

Start a timer on initial page load. Must keep counting from first load if they leave and return

I want to have a time limited offer displayed on stage 1 of a checkout process. The timer will be set at, for example, 5 minutes and should start when the page is first loaded.
If they leave the page and then return to it, the timer needs to continue counting down from the initial activation, not start again.
Is anyone aware of a script for this function using php and javascript?
If not, some advice on how to achieve this would be great. I can create a timer without too much problem, but no idea how to get it to trigger only on first page load and then maintain the count.
I have already implemented this type of functionality. In my scenario, student has to pass some specified time before go to next chapter. For that we are showing timer to student and at the back-end we are saving elapsed time every five second to database using ajax. So if student has pass the time 17 seconds and then leave the page. So next time when he will come to that chapter timer will start from 15 second, which was saved to database then again start to record the elapsed time to database every 5 second.
You want more details. Please tell me.
Thanks,
Amit Prajapati
You can resolve this storing the datetime of the first visit on server or client side.
On the client side, you can use the localStorage to save the datetime the first time the page is loaded. The next time the page is visited, you check in the localStorage if the datetime variable is set, and compare this value with the current time to show the timer.
If you are not worried about a change on this value (there is not side effects if the client modifies or delete this value on the localStorage) I'll take this approach.
But if this timer is a Domain concern (you want to track the datetime), you have to store this value on the server side.

Passing a JS variable to PHP Safely

I making a javascript game where the player builds up a score against a count down timer. When the timer runs out I display a form that show the score and lets the user enter they username (arcade style). I'm going to use the POST method send the user score to a php file that will store it somehow (database,textfile. or something). How do I prevent people from fiddling with the JS code and passing some new value thru that isn't the correct score (or something that isn't malicious).
At the very least, what are the safest methods on the PHP/reviving end to at least only accept and integer value?
That's a well known and difficult problem. I'm not sure it ever has a good solution. The user is the client is JS, so they have 100% control over what's sent to the server.
The only thing you can do and force, is server side validation. Don't just send the score. Send the path, the method, the steps, etc. Starting a session/game/level should also happen on the server, because the timestamp could be faked from the client.
You can make the whole game in JS, but start and end it on the server and remember all the steps. This might mean double step/path validation: JS (instantly) and server.
(I had the same problem with http://games.webblocks.nl/110 which stores steps (clicks) in g_stack.)

set and show a countdown timer for a form using js and php

I have an exam form. i want to set and show a countdown timer (for example 60 minutes) as the student open the page. if they post the form after that specific time it wont be acceptable and they lose the exam.
how can i do that? only using js or need using php as well?
i'm a new so need some clear codes!
Thanks
Consider using a database for this or some kind of server-side check. When the student opens the test for the first time, the time should be stored in a database and the shown time should be calculated. Otherwise refreshing the page would reset the timer. At the end if the time of submitTime-startTime < 60 seconds then he/she made it in time.
This means that you need PHP for example. It should call a method which stores the current time if a field in database if it isn't allready stored and then do the same after submit. If the time of submit is present in the database, you shouldn't allow him/her to do the test again.
JavaScript should only be used for the display of time, not for validity checking alone without any server-side checking.

Trigger client side event when session in lost

As some of you probably know, Facebook is using this kind of "system" where a popup is displayed when a user session is lost due to inactivity or distant session close. I already saw and read this Node.js question but didn't find anything.
I am working for a Canadian computer business our main product is a CRM and everything is coded using Classic ASP.
I know.
The whole web-based application is working great and since we host the site on our servers, it is possible if necessary to open ports and use sockets.
Here goes the main question: is there a way (using a javascript library or a jQuery plug-in maybe?) to trigger a client-side event when the session expires or is simply lost due to a server reset for example?
Of course, the best would be to use another solution than sending an AJAX request every second to validate if the user session still exists. If it can help, there is a maximum of about 3'500 users connected at the same time and our servers can easily handle more traffic. The servers are working on Windows Server 2008 along with IIS 7.
Unfortunately, I cannot provide any code blocks or screenshots for this question since there is nothing to debug.
One idea would be to use an AJAX request to a file that does not return anything and hangs there. If session is lost (inactivity or server reset), the AJAX request will trigger an error and the "error" function will be triggered. Would that be something to consider?
Or else, any other suggestions?
One way to do it is to set client-side timer set to the same time as session expiration time.
Let's say your session is set to expire after 20 minutes. When page loads - client-side timer set to 20 minutes kicks in. If user does any server interaction (submits form etc.) - timer is reset. But if nothing happens during this 20 minutes - timer counts down and you get your event.
You could do the following to achieve this, assuming you have a default session timeout of 20:00 minutes:
Ensure, that each user has a "session cookie" issued by you, NOT the default ASP Session Cookie.
dim live_session_id
live_session_id = Request.Cookies("livesession")
if live_session_id = "" then
live_session_id = create_unique_session_id()
Response.Cookies("livesession") = live_session_id
end if
Save this live_session_id in a database along with the expected session expire date
call updateSession(live_session_id, dateadd("n", 20, now())) ' = now()+20min
Output the live_session_id somewhere on your page, so you can access it via JS.
Implement a serverside ASP script that checks the current session state for a given live_session_id and make it accessible in IIS in a DIFFERENT subdomain, so calls to this check will NOT refresh the ASP session. The script could return the time difference between now and session end, so you could output the duration the session will remain valid.
Add some AJAX code to call the check script every other second, so you could issue a warning if the session time draws to an end.
To make it detect IIS reset, you could clear the saved sessions in the database by implementing Application_OnStart in global.asa. This way, your clients would detect a session loss by IIS reset.
another quick and dirty method
On every page load, you could let a javascript count down from 20:00 minutes and display a session lost warning after this time. This is what my online banking system uses... :)
as far as i understand you the main Problem is that the user has to fill out enormous forms. that could take some time and during that time the session could expire.
furthermore the session could be ended by anything else (iisreset or so) during the time the user fills out the form.
in my understanding you do not have to notify the Client that the session is lost/expired/ended/abandoned. it would be enough to just show a Login form (Ajax or something) when the user submits the form OR the next request (by Ajax as you mentioned) is made by the Client.
the called asp script checks if the session is valid and if not a popup or overlay is shown to Login the user by Ajax first and the form is submitted afterwards.
you could think of a http Status code 401 or something to send back to the Client and the Client then Shows the mentioned Ajax Login form...
What makes a session expire in your CRM? Expiring after X time passes since last [user] action is pretty conventional and will allow you to use ajax to keep the session alive. Let's say a session is good for 5 minutes as part of security requirements for super-secret NSA banking CRM with kittens and youtube videos. A good scenario of how a session can be extended would be this:
a page is opened, validating the session for another 5 minutes
a timeout is set with JS to make an ajax request every 4 minutes
[4 minutes later] the request is made, returning a very light-weight response.
if the response says everything is ok and the session is still valid, schedule another "ping" and carry on as usual. If the response comes back with an error (session invalidated on the server because of logging in from a different PC etc.), gracefully handle it. Allow the users to retain what they were working, don't just kick them out to a log in screen with an error
User navigates away from the page (clicks a link, submits a form), repeat from the beginning. If the user navigates to an external site or closes the browser, his session will self-destruct in no more than 5 minutes :)
Obviously you can piggy-back any additional information onto the ajax call in step 3 - e.g. notifying the user of new items assigned to them in CRM?
Google is your friend, one of the first results gives a not bad overview of the approach basics.

Countdown Timer to activate a controller method

I am building a survey page where users have a limited time to answer all their questions. The time given is stored in the model as #test.time_allowed, which is an integer representing seconds.
I need to have a simple and non-user-tamperable way to get a timer to display on the view and execute a controller action when it winds down to 0. How can I accomplish this?
I'm a relative beginner so any specific answers would be really helpful. Thank you.
---UPDATE---
#Bryan:
I assume there is a tamper proof way if the timing is done server side? For example, there might be a javascript timer on the client side as you suggested, but upon submission can't the submission time be checked against the time of the window's initial load?
Since data coming back from the client can never be fully trusted, the server must somehow know what the timestamp of the originally generated form was. This could be done by saving variables in the session or database, but this is problematic. Instead, the server can place a timestamp in the form, either encrypted, or signed, to ensure the client has not altered it. The server can then reject the submission as necessary. On the client, separate logic can handle the UI portion, giving the user feedback on the time limit, but ultimately this only loosely coupled to the server handling.
Details:
The server should generate two form fields: one with the system timestamp time = Time.now.to_i to track when the form was generated, and another with a signature Digest::MD5.hexdigest(time.to_s.concat('Some-secret-string-1234')) (note using the same time value here for the timestamp form field and signature form field). This validates that the form is submitted with a server-generated timestamp that has not been altered by the client.
You might also send another form field with the time limit.
On the client, read the timestamp, use setTimeout and the time limit to generate a countdown or whatever you want to do on the front end.
When the form is submitted, authenticate the timestamp submitted with the form by regenerating the MD5 signature using the same method as before. Make sure it matches the signature submitted by the form. Then, add the timestamp to the timeout, and make sure it's later than the current server time. If so, you have a valid submission, within your time constraint.
You probably will need to give a little more leeway on the timeout at the server than on the client, maybe a few seconds, to account for network delays, otherwise the user might see one second remaining, click submit, and then by the time the server request is received, it will seem like the timer has expired.
Be sure to add require 'digest/md5' to get access to MD5.
Using MD5 signatures like this is a great way to verify that a client has not altered key parameters in a form in a stateless manner, whatever you would like them to be. A good addition to your bag of tricks.
Good luck!
There's no 100% tamper proof way of implementing this since you would need to do this using JavaScript which can be turned off or manipulated by a sufficiently malicious user.
However if you aren't concerned about these issues you could simply set a timeout on the page to submit the form after the number of seconds have elapsed. To do this you would need something similar to the follow. Obviously timeInMilliseconds would need to be generated into the page from the template on the server side.
window.setTimeout(function() {
document.forms['survey_form'].submit();
},
timeInMilliseconds);
Create model for ongoing surveys, and add after_create filter that will set deadline to Time.now + survey_duration. Keep logic that will deny late sending of answers in model.

Categories

Resources