javascript form checking and encrypted passwords - javascript

I have a simple form where users can change their passwords, and I am using an onsubmit event to check the form which generally works fine, except when I try to stop them using a password already in use.
The passwords are stored in a database and are encrypted. What I need to do is compare the encrypted password with the new password, which is not yet encrypted. The encryption I am using is:
<%
Function encrypt(x1, x2)
s = ""
t = 0
For i = 1 to len(x1)
t = t + asc(mid(x1,i,1))
Next
For i = 1 to len(x2)
y = (t + asc(mid(x2,i,1)) * asc(mid(x2,((i+1) mod len(x2)+1),1))) mod 255
s = s & chr(y)
Next
For i = (len(x2) + 1) to 10
If t>598.8 Then t = 598.8
y = t^3*i mod 255
s = s & chr(y)
Next
encrypt = s
End Function
%>
and I run encrypt(Username,Password) which gives me a output like ¬{±ÝÆÝl
The onsubmit code I am using is
function checkData (){
if (document.signup.password1.value != document.signup.password2.value) {
alert("Your passwords do not match.")
document.signup.password1.focus()
return false
}
if (document.signup.password1.value == "") {
alert("Please enter a password.")
document.signup.password1.focus()
return false
}
}
This all works fine and I am just stuck on the last bit which is the old password check.
I have tried various things like
if (encrypt(document.signup.password1.value,emailaddress) == "value from database"){
alert("The password chosen is already in use.")
document.signup.password1.focus()
return false
}
My main question is: can I call the ASP function encrypt into my javascript checkData? As I am beginning to think this is where the problem is, I am wondering if I am wasting my time and feel that there is no way of doing this. I know I can submit the form to the next page and do the check there but I really wanted to do it this way if I can.

You can not directly invoke ASP (or any other server side language's) functions from JavaScript. That being said, there is a widely used technology called AJAX, which allows you to execute asynchronous JavaScript requests to your server side application. They're called asynchronous, because you do not submit/reload the entire page, but you execute a piece of JavaScript which invokes a server side functionality and returns the result, thus letting you update your page without having to reload it.
In your case, you'd want to implement an AJAX request which asks your if a certain password entered by a user is already in use, and the server will simply return a boolean, which you'd evaluate on the JavaScript side and update your page accordingly.
I'm very certain that there are tons of tutorials and explanations on how to use AJAX requests with ASP (which I am unfamiliar with), and providing such an explanation would certainly be out of what can be provided here. Please consult Google :)

Related

Bots are bypasing my script for blocking emails

I currently have a script for blocking non-business email addresses on my website form (Marketo) yet bots are still finding a way to bypass it. Today I got another "gmail" and "hotmail.fr" submission. Whenever I test my form it works but the bots are finding a way to bypass the script. I have also tried the honeypot method but it has not worked. They are also submitting with two-letter names, the past month has been really bad and I am desperate for help, I am not very good in JS so any help would be very much appreciated.
This is my script:
(function (){
// Please include the email domains you would like to block in this list
var invalidDomains = ["#gmail.","#yahoo.","#hotmail.","#live.","#aol.","#outlook.","#icloud.","#zoho.","#hubspot.","#gmx.","#yandex.","#mail.","#email.","#tutanota.","#trashmail.","#lycos.","#tutanota.","#protonmail."];
MktoForms2.whenReady(function (form){
form.onValidate(function(){
var email = form.vals().Email;
if(email){
if(!isEmailGood(email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage("Must be Business email.", emailElem);
}else{
form.submitable(true);
}
}
});
});
function isEmailGood(email) {
for(var i=0; i < invalidDomains.length; i++) {
var domain = invalidDomains[i];
if (email.indexOf(domain) != -1) {
return false;
}
}
return true;
}
})();
</script>```
Some bots when they run, they don't even execute the JavaScript on the page. They just take the fields, find the post request the form is submitting, and submit the fields to them with pre-defined values. Thus, ignoring your validation completely.
So now the solution would be checking the post request values on the backend. Some people use the fact that some bots are dumb, and they include a honeypot field in their fields. They mark it hidden with CSS on the frontend, but again, some bots are dumb, and they will fill it out regardless and send it in the post request. Now you can have your sever throw that out right away.

Custom validation script on submit for PDF - Can't get it working

I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}

Email Validation in Javascript based upon domain look up

I know this question has been posted many times. But still i would like to inquire a little more. I have used a function
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(elementValue);
}
It works fine. But my problem is that it allows 123#123.com as a valid email. So i want to check the domain also like checkdnsrr() does in php. Can i do it in javascript? I want to check for valid domain also.
It looks like there is no other solution than using AJAX to do this.
You do a request on your server with JS, the server checks the DNS using checkdnsrr(), and it responds with whatever you want, it will allow your JS to handle the validation depending on this.
Why don't you do it in php? That will be much easier than making an ajax call.
On the same code that you have Provided
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(elementValue);
}
Change it in this manner and it will validate 123#123.com Checking that the Domain can not be #123.com
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(elementValue);
}

Javascript code not being called in asp.net code behind

I have a block of code (posted below) where if the first IF clause is satisfied, the app does not call the javascript('MyPortfolioItemExists()') function. Instead, it exits the function and goes on to process other code lines.
If drPortfolio.HasRows Then
Dim p As Page = CType(System.Web.HttpContext.Current.Handler, Page)
p.ClientScript.RegisterStartupScript(Me.GetType(), "Script", "javascript:'MyPortfolioItemExists()';", True)
Return ""
Exit Function
ElseIf drFav.HasRows = False And drPortfolio.HasRows = False Then
Utils.ExecNonQuery("insert into UserPortfolio values ('" & PortfoName & "','" & PortfoPage & "','" & Username & "')")
Return GeneratePortfolioContent()
End If
How can I force the javascript function to be executed?
p.ClientScript.RegisterStartupScript just registers the script to be executed on the client. See the documentation for more information on this function.
You can't execute Javascript on the server (unless, of course, you are writing the server-side in Javascript which you are not). Figuring out the difference between server side code and client side code is something many beginners have gotten hung up on and WebForms blurs the line even more.

How to validate username using Javascript?

I want to know how can I validate using Javascript that if user has entered any username at the time of creating an account is already present in database and ask user to type any other username?
Attach listener for blur event for <input /> element.
Using AJAX send request to the server (with field value as parameter)
On the server side check whether given username is already in use or not
Based on server's response display (or not) This username is already in use message
jQuery (I'm too lazy for pure JS) + PHP sample code:
<form ...>
...
<input type="text" name="username" id="input-username" />
<p class="error"></p>
...
$("#input-username").blur(function() {
$.post("/check-username.php", { username: $(this).val() }, function(data) {
if ("0" == data) { /* username in use */
$(this).next("p").text("This username is already in use.</p>");
} else { /* username is fine */
$(this).next("p").empty();
}
});
});
<?php
$username = $_POST['username'];
// check whether given username exists in database
$usernameExists = ...;
echo $usernameExists ? '0' : '1'; // 0 if exists, 1 if not.
The answer is AJAX. If you must validate against a database, you need to make a call to the server. The only way to do that (EDIT: properly) without reloading the page is AJAX. How you implement it will depend upon what javascript libraries you are using, if any, and what your server is like. I suggest you do a little searching and reading on it - this is a pretty common use case.
Personally, I would use a JQuery validation plugin just to make things simple.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
But in general it would consist of a small AJAX request to a server (ie. JSON object) with the username and do a 'search' in your database and return either true/false after the user hits enter or tab in the textfield (attach an event listener). Then within your callback response alter the DOM elements of your choice to indicate to your users whether the account name is already present in the database or not.
Ajax might not be the only solution, since usernames are generally public. A simple way is to just have an RDF/XML document at some point (which just updates with every new user added) which has a list of all the users on your site that you can easily just traverse with Javascript DOM to see if that user is already in use. You also make them pay computational power, not you, depending on how nice you are it's an advantage or a dis-advantage.

Categories