How to prevent user to change javascript button disable() function? - javascript

Creating a forum on localhost. When user clicks on the button to post the question, my javascript function disables it(when the question was asked) to prevent question spamming. Everything okay with that, but:
Here is the code which is in /scripts/scriptname.js
function disable() {
document.getElementById("submit-img").disabled = true;
}
disable();
If the user changes this code above to false, the user can post various questions, because he can change it to: .disabled = false

Unfortunately, you cannot. Any form of front-end validation will not protect your server or database from spammers hence a back-end validation is required. Depending on what back-end language and framework you're using, you'll need to keep track of the user's IP address (assuming there is no form of authentication) and set a timestamp in your database that will prevent that specific IP address from sending requests to the endpoint you're trying to protect.

The way you are going about with it is wrong. You should allow only registered and verified user to access and post content to your forum. Your implementation is javascript base so it can be hacked.
It should be done server side. At least, you should create a database where you should track all users activities via something like their login session data, ip address, emails etc. You can set a counter to count number of content to be posted by users on a particular time and then banned or stop any offending user.
While double registration by users are not easily avoided but you can limit it by asking each registered user to verify their email via a link sent to them upon registration.
You can also set up a captcha eg Google recaptcha to limit bots access
Infact, what you are trying to implement is too broad from security point of view.
If security is not much of your interest you can try this little sample code below. The tracking is based on session. just remember that if users clears session cookies, he can still bypass
Based on your request. You can use session to track users submission count. This is not security proof as I stated earlier but it will give you an insight into building your own app. However its far better that doing it in a javascript which your users/clients can easily abused....
The code below will hide submit button if user submit more than 2 times
<form action="" method="post">
Enter name<input type="text" name="uname">
<?php
error_reporting(0);
session_start();
if($_SESSION['att'] >=2){
// hide submit button
}else{
echo '<input type="submit" value="submit">';
}
?>
</form>
<?php
//session_start();
// set up session counter
echo $_SESSION['att'] = $_SESSION['attempts']++; //increment
$name='';
$uname='';
$name = $_POST["uname"];
echo $_SESSION['uname'] = $name;
?>

Related

Prevent a user to complete two times a form in javascript

I created a form with Html, CSS and JavaScript and an API with ASP.NET for the HTTP request. Users will have a link to fill in the form. Is there any browser id or IP which I can get so prevent the user to submit multiple times the form?
Disable the submit button is not an option
The form has to be anonymous so a unique id for the users is also not an option
you could make like a cookie in java script that doesn't expire. after that you could make a if else state and check for the cookie if it exists in the browser
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
// Put your cookie name in in place of MyCookie.
if (value_or_null = 1)
{
//redirect to other page
}
else
{
// let him do the form
}
There is no 100% safe way, as returning users could have cleared they cache or something. Also, tracking the IP could potentially work, but you ask for full anonymity...
If you want your server to have authority on this decision, the only information you will have or can use is the IP address. Even that would not be accurate if your users hop on different VPNs and stuff.
What I think could work is if the link for the users to access the form is unique for each user. You'd generate a UUID, that way it cannot be guessed if users want to answer more than one. That UUID would have no link to any user, it would just be stored in a list of VALID UUID and get removed when the user uses it to answer.
The link would provide the UUID through query param, the javascript would then add its value to the form when being sent.
If you do not link that UUID to a userId or if the email sent (or its content) is not stored, this would provide anonymity.

Prevent multiple form submission using a counter?

P.S - Although there are many other such questions in Stackoverflow, I could NOT find the method that I was trying to implement.
Now, what I tried doing is as follows :-
Profile Page
Email : example#example.com [Edit Details Button]
Edit Details Page //user is sent here if s/he clicks on Edit Details Button
<form id='inputform'>
<input type="text" name="email" id='email'>
<button type="submit" id='submitform'>Submit</button>
</form>
<script>
//Script part below
</script>
Script
//validation part here
var noofsubmits = 0;
$('#submitform').on('click',function(e){
e.preventDefault();
if($('#inputform').valid()){
noofsubmits++;
if(noofsubmits == 1){
$('#inputform').submit();
//redirect users to a different page on successful form submission
}
}
});
On every form submit, the user is redirected to the profile page (which shows updated info). Now, everytime the user tries to edit details , the varialbe noofsubmits is set to 0.
I am not having any problem with this method, but is there any practical problem with this method? Like what if the user disables Javascript in the browser, so would this method not work?
Yes for sure if javascript is disabled on the client side, the script part will not be executed. (and you have to do validation and redirection on the server side)
However, there are very very few people who disable javascript in their browser.
The drawback of doing validation and redirection on the server side is that the user will need to wait for a slightly longer time because there will be time lag before the server respondes to the client request. But if your validation is done on the client side (javascript), then the user will experience immediate response on data validation.
On the other hand, using javascript will also be good if you want some visual effect like animation to be rendered on the client side.
Since very very few people will disable javascript in their browser, you can continue to use your javascript approach to do the job

End Session in all browser after logout.php

I currenly have this on my logout.php
<?php
//LOGOUT.PHP
session_start();
//// unset all $_SESSION variables
session_regenerate_id();
session_unset();
session_destroy();
$_SESSION['logoutsuccess'] = 'You have successfully logged out.';
header("Location: index.php");
exit;
But after changing password using changepassword.php that has logout.php in the end. It just destroy the session on current tab. But it doesn't destroy the session on the other browser/tab. TIA!
Do this:
$_SESSION = array();
session_destroy();
setcookie (session_name(), '', time()-3600);
You can try this
//LOGOUT.PHP
session_start();
//// destroy all $_SESSION variables
session_destroy();
echo "<script>alert('You have successfully logged out.')</script>";
echo "<script>window.open('index.php','_self')</script>";
What you are attempting to do isn't easy when it comes to pure PHP. Javascript will be your friend in a situation like this.
If I were to implement this I would create something in JS that checks every x amount of seconds/minutes with the backend to see if the password has changed. This will require a separate endpoint that is specifically for this check.
Here would be a rough outline of what I would consider doing:
When the user logs in take the username and hashed password to create a hash of that data using something like $userAuthHash = sha1("{$username}${password_hash}) and save that in the user session.
In your page (in the header more than likely) display the created hash. This is generally best to do in a meta tag in the header (ex: <meta name="user_auth_hash" content="<?php echo $userAuthHash; ?>">). You can obviously set this up however you want as long as you can look it up using JS.
Have the JS script get the value of the hash from the meta tag and every x interval send this to the validation endpoint. The endpoint should in some way indicate if the users token is still valid.
If the users token is no longer valid you can have the JS script redirect the user to the logout script as needed.
There are a lot more complex ways of doing this but this is one of the easiest ways of going about this that I know of.
Also remember not to over think these things when building software. Security is important but imagine the case where an account gets hacked and the hacking party changes the password. Your now legitimate user has been logged out and thats never any good. This would be a case where you would need to evaluate your initial strategy and possibly implement an email that forces the user to validate a password change before it is persisted to the database. Just some food for thought.

How do password managers know when I've logged in successfully?

So you know how you are presented with a login screen and then, you fill it out, and then the browser loads the next page? At this point, somehow the password manager bar pops up for LastPass, 1Password, or some other extension, asking if you want to save the password. How do they know you've just logged in successfully??
Forms are sometimes submitted and other times the js intercepts the form submit and sends AJAX.
The response comes back and may set a new cookie, but sometimes the existing session cookie continues to be used (allows session fixation attacks but some implementations do that).
A new location is loaded or reloaded but sometimes the javascript reloads a portion of the document instead
But somehow these password managers DETECT that I've logged into a site successfully! How? Is it because I entered something in a password field, and then some form was submitted or some network request was sent? But how do they know it was successful?
Anyone familiar with these password managers able to give some useful info?
The reason I ask is that I want to develop an extension that detects when you've logged in and somehow tries to extract your user id from the service. It is for the purposes of sharing your user id with friends automatically, and letting them know (with your permission) what sites you are using a lot.
Any hints on techniques to extract the logged-in user's id on the service would also be helpful.
They aren't actually aware of a successful login in most cases. They are aware that a form with a password field was submitted, and the response was a 200OK. This may still be a page displaying an error message.
As for extracting user IDs, I'm pretty sure you mean profile pages or something similar. That will have to be done on a site by site basis as sites will have their own APIs and route structures.
As someone already answered this question, I will agree with him.
They aren't actually aware of a successful login in most cases. They are
aware that a form with a password field was submitted, and the response
was a 200OK. This may still be a page displaying an error message.
Since browsers watch for the request having a password field in it and the response status, But still you can fool the browsers easily. To get to know about the logged in userid you definitely need backend support / api. It depends on the authentication frameworks used in the back-end. But you can get the form fields easily, but extracting / finding userid from the form fields is a quiet difficult task, In most cases, form will be having only two fields there you can manage to get the userid. But in some cases like banking sites they will send few dummy fields fool such tools, Also many fields will be encrypted in the client itself to protect man in the middle attacks. In some cases userid is different from email, So its difficult task.
They only detect if the form was submitted, and it a code 200 (OK) was returned. They don't necessarily know if you were logged in, but this method works on most websites. They might also detect if a new page was loaded afterwards, since a failed login doesn't usually redirect the user. I have, however, had a prompt to save an incorrect password before.
They can detect your current tab. and each HTML element of that page.
May we they have list of login page case to detect keywords like
login,username,forgot password. and check all keyword to identify this is login page.
They just ready page and even they can read your password (yes) .
If you made request from that page & response will be 200ok it means your password is correct.
Whenever to request to server with username and password the server checks these two entry into their database and the server will found your data it will return response code 200 and using AJAX success call back script will catch the response code and will show successful message.
and also return some sort of information you can store into localStorage of browser or into cookie for further use.
I have created a couple of pages static HTML and form: So when form is submitted it goes to second page.
Let's test
<form action="test1.html">
<input type="text" />
<input type="password" />
<input type="submit" />
</form>
</body>
Chrome don't bothered anything happened. While firefox has given a popup to save password even when form is submitted to an error page.
So firefox only looks for a form submitted with a password field and asks for save password popup box.
If want to create an extension which can check wheather user is successfully logged-in and then you want to ask for password remember popup. For that you have to check for server response. I couldn't create a dynamic page to to proof read it with browser example.

Redirect using post and get the succes of the redirect

Say, I have a simple form on my website having three fields : name, password and email.
I have to get these information from the users, and keep in my database.
Then redirect to another website and send all these information using post.
I also have to know whether the user was successfully redirected to that site(HTTP STATUS 200).
Here's how I'm doing it:
For Point 1, I'm simply submitting the form.
After the data has been successfully saved in my database, I'm rendering the following form with hidden fields. This gets submitted and user gets redirected to anotherwebsite.com
<form id="form_id" action="https://www.anotherwebsite.com/form" method="POST">
<input type ="hidden" name ="name" value ="$name">
<input type ="hidden" name ="password" value ="$password">
<input type ="hidden" name ="email" value ="$email">
</form>
<script> document.getElementById('form_id').submit(); </script>
Problems:
I don't think my strategy to achieve point 1 and 2 is correct. I need a better solution. Submitting the form, then rendering a page with hidden fields and submitting it again to redirect to another site just doesn't feel right.
I have no clue to achieve the 3rd point.
Based on your question you might try this approach:
create a form with name, password, email fields in a file ( HTML ).
Submit the form to server.
On the server side get the data (including the form attribute in a variable) and save it to database.
then redirect to the given website ( using the variable you've stored in step 3 ).
You can easily know the status ( 202 or any error) using any of server side scripting language.
If you are sending the user to another website, the only way to know that the user was successfully redirected is for that website to notify you in some manner. Once the user leaves your page (and that's what a redirect is - it tells the browser "leave this URI and go to this URI instead"), the scripts on that page stop running, so they can't collect any further information.
If you just need to know that the information was submitted successfully, your script could POST the data in the background, wait for a 200 response, then redirect after the information has been submitted. But that may not meet your requirements, since you still won't know if the redirect succeeded.
Another possibility which does allow you to know whether the page on the other site loaded correctly would be to open it in a new browser window/tab instead of redirecting. This is the only way to keep your page active (and, thus, your scripts able to run) while loading another page. However, it introduces other issues, like what to do with the original page. (Leave it open in the background (likely to confuse the user) or close itself after seeing that the new URI has loaded (could cause undesirable visual artifacts as one window/tab opens and then the original one closes; destroys browser history)?)
If at all possible, having the final destination site notify you when the transaction completes is almost certainly the best way to go.
To achieve point 3 you need to use cookies if you are actually trying to implement a login-cum-membersarea system. Othewise, you simple need a redirect inside a condition statement.
my $cgi = CGI->new;
if (condition) { print $cgi->redirect('https://www.examplesite.com/file.html') }
for a general way of doing point 1-2, you can look at the tutorial here:
http://practicalperl5.blogspot.com/

Categories