Matching Passwords with Front-End or Back-End? - javascript

Does anyone have any information on the industry-standard or best practice for checking matching passwords (e.g. Gmail's "passwords do not match" feedback")? Is it a back-end, front-end or client-side process? Or is it completely based on other factors?
Here is an example of the code that I am using (Python with Bottle) to sign up a user. The code works, but I am unsure whether I should provide a flash message from the back-end (where it returns "Passwords do not match") or would it be better to use something like JS? I know that there are scripts out there to validate this, but they are all JS. My question is not how to do it with JS, but which is the preferred method.
#route('/suser', method='POST')
def sign_suser():
cemail = request.forms.get('semail')
cpassword1 = request.forms.get('spass1')
cpassword2 = request.forms.get('spass2')
ctype = request.forms.get('stype')
if cpassword1 != cpassword2:
return "<p>Passwords do not match</p>"
else:
pwhash = crypt(cpassword1)
connection = sqlite3.connect("whatever.db")
cursor_v = connection.cursor()
cursor_v.execute("insert into users (cemail, cpassword, atype) values (?,?,?)", (cemail,pwhash,ctype))
connection.commit()
cursor_v.close()
info = {'status': 'User Added',
'type': 'success'}
return template('whatever',info)

Checking if two password fields match during a sign up should be purely done with client-side logic. It is provided as a safety against a user mistakenly inserting a typo into their password. A server-side check is pointless, as your client will have prevented it and if your user is a tech savvy individual that does everything with curl then it's on them if they mess up.
Also I will expand on your question about best practices. You should not immediately save the user in your database without them first verifying via a link, usually sent to their email, that it is valid. Remember: never trust anything provided by the user.

You need to distinguish between two cases:
You are not able to validate the value without using a database or any non-sharable technique in the back-end. In this case, you're only possibility is to check it in the back-end (with e.g. an Ajax call or a communication over WebSockets). Examples for this kind of validation are: username/password validation or anything which needs a connection to a database, a proprietary algorithm to check a value with a logic which cannot be published
You can validate the value without checking it first in the back-end (database). In this case, you can move the check for performance reasons to the front-end/client side. You still have to protect the back-end against incorrect values (in case of an attack, corrupt JavaScript etc.) Examples for this kind of check are e.g. email address validation, phone number validation etc.
For 1, I would just use a regular connection to the back-end either when submitting the value or while typing (if the response from the back-end is fast enough).
For 2, you have several options:
Do it like in 1. Make a back-end check either while submitting or during the input. This may have some performance issues though (mainly if you are checking it on key down). If you are checking it after submitting, the validation is not real time.
Do it with separate validations on the front-end side and the back-end side. If you are doing. This is not recommended. You are duplicating code between the front-end and the back-end. Avoid it as often as possible.
Do it with shared validation patterns in the front-end and the back-end. This is my recommended way of validating values. This validation works best, if the checks are done with regular expressions (regex). The back-end has a Map() of patterns which are provided over an interface to the front-end. The patterns are loaded initially, when the web applications is loaded and are then present during the runtime of the application. This makes sure, that the validations are always the same on the back-end and front-end side.
Your example however comprises of the matching of two passwords (equality check). This is a special case, because you cannot use a regular expression to check the validity of the value. This precludes the recommended case from above and leaves the two other mentioned solutions.
If your sole purpose is to compare the two values, I would recommend to duplicate the logic. Duplicating is in this case (imho) somewhat justified because the check is very simple and not likely to be changed over time. Making a check to the back-end to soley check for equality is (imho) overstated.

Related

Client side validation for PHP project good or bad? And how to improve the PHP project?

new to PHP. After around hours of learning&practising I have created a small PHP project with MySQL database for check/create/edit/delete employee's information.
So here are my questions to improve it(as a good and smart php project standard, doesn't have to be a enterprise levelled one):
Should I use more Javascript to do the client side validation , or use PHP functions to do the job mostly? (e.g. check if form data was entered with the correct format )
To modify the employee's information , what should I do to make sure the data was created/edited with the same standard inside database(e.g. first & second name should always starting with the one(and the only) upper case letter no matter what did user entered into the forms), javascript, php function or the sql queries? I think they could all make it working but which one is the best way and why?
This kind of code is driving me crazy
<input type="text" name="inputFname" class="field-divided" placeholder="First"value="<?php echo $emp['f_name'] ?>"/>
Any better way to make the php code separated with the html code?
Any and all data coming from an untrustworthy source (the client, which can be manipulated by a hostile user) needs to be validated and sanitized within a controlled, secure environment (the server, which is locked away where end-users can't get at it) before being allowed contact with the database.
You can (and should) also perform "bozo-test" validation at the client to ensure completeness, correct formatting &c.; client-side validation allows you to inform the user of an error immediately without the overhead of a round-trip to the server. Keep in mind, though, that client-side validation can not protect you from an actively hostile user.
Hope that helps.

Isn't input sanitisation with JavaScript pointless?

Background:
I've been searching for a way to sanitise some form inputs with JavaScript to prevent the form being submitted if it contains characters that aren't whitelisted.
I've come up with this based off a brilliant Stack Overflow answer
function allowSubmission(string) {
return string == string.replace(/[^\w\s]/gi, 'X');
}
var s1 = 'simple string';
var s2 = 'alert(0);';
var s3 = '<nasty>string';
console.log(allowSubmission(s1)); //true
console.log(allowSubmission(s2)); //false
console.log(allowSubmission(s3)); //false
Problem
But doesn't this just mean a potential attacker can turn off JavaScript and submit whatever the hell they like? Or simply edit the JavaScript on the fly and overwrite the validation method to just return true.
Question
SO... Isn't input sanitisation with JavaScript pointless?
This only means you should always validate and sanitize your input server-side. Regardless of whether it's checked in front-end as well.
Doing this in JavaScript can help you avoid unnecessary requests hitting your backend and increasing the load as well as improve the user experience but they should not be treated as a means of security.
It's pointless, when treated like a line of defence. In general, its use serves many purposes.
But doesn't this just mean a potential attacker can turn off javascript and submit whatever the hell they like? Or simply edit the javascript on the fly and overwrite the validation method to just return true.
Yep, but that doesn't make javascript validation pointless.
The purpose of javascript validation is not to sanitize input for the server. That job must be handled by the server.
The purpose of javascript validation is to make the user interface more responsive for the user. JavaScript validation allows the user to know when they made a mistake without having to wait for a potentially slow server response. It can also reduce the overall load on the server.
Client-side JavaScript should never be used as the only means of sanitizing input, it can be used to assist the server, but in the end the server must be able to correctly handle invalid input.
Input sanitization is not done for security, but for usability. You should give feedback to the user that he inputs bad characters as soon as possible (on each keystroke), not after he submits the form and the response comes back from the server.
For security you MUST validate anything coming from the client on the server. There is no way around it.

validation data before insert them into the database

I know how to validate data using Client Side (JAVASCRIPT) , Server Side (PHP) and Database(Triggers in mysql).Do i want to validate data in all these methods when working with a large application process ? if i used those methods to validate does it slow ? if it's what is the fasted way to do it ?
JAVASCIPT
var data $("#input").val();
if(is_nan(data)){
}
PHP
if(empty($_POST['input'])){
}
MYSQL
DELIMITER $$
CREATE TRIGGER example_before_insert
BEFORE INSERT ON registrations FOR EACH ROW
BEGIN
IF NEW.RG_Reg_NO NOT REGEXP '^[A-Z]{3}\/[A-Z]-\d{6}$' THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'The registration number you have entered is wrong';
END IF;
END;
$$
That's my approach & opinions:
Client side validation is always needed for two reasons:
better user exprience
avoid round trips to the server and reduce payload (That is the main reason why Netscape came up with javascript in the first place).
Server side validation is always needed for two reasons:
security! as someone can always post requests(curl) and bypass your client side validation.
provide fallback to js disabled clients (very rare nowadays).
Database validation:
If you have to avoid mistakes by the team that writes the server side code use those.
If your team is small and the one who writes the server side code is able to implement all the business logic without double checking it at another level than don't use those.
If you prefer productivity and flexibility over data integrity don't use those.
If you don't have someone at your team that really knows how to deal with sql spaghetti then don't use those!!
If your application is so large that performance starts to be an issue then you must first check out NOSQL solutions if they feet your requirements before entering the SQL spaghetti maze. Also employ an experienced dba.
Feel free to add more reasons or to correct my mistakes.
This is subjective - how secure do you need to be and how confident are you in writing secure code?
I would personally use client side first (to save on over-head on server more than anything) then php check (for site safety) before doing prepared INSERTS, UPDATES or DELETES etc.
However if you think there is scope for someone to run queries on your database then the MySQL check could be used
Overheads are quite small for all so it depends on acceptable script times, number of users etc.
Like I said subjective - I would go javascript php and make sure my code is secure but thats just me.
NEVER just javascript checks - way to easy for me to start calling functions and ruining your database.
Usually validation on client side (javascript) and serverside (php) would be sufficient .
Because if someone has js disabled, then your js validation will not take place. Therefore you would rely on php for validation.

Best practice for handling errors in forms submitted via ajax?

I'm wondering what is considered best practice for dealing with forms submitted via ajax. Specifically, I'm wondering what is the best way to handle a form which contains errors.
I see two possible options upon submitting a form with errors:
A. The server returns a JSON document of name value pairs of fields names / error messages. This would then need to be processed client-side and the form would need to be altered by prefixing each field with it's error message and changing the form's styling (adding an error class to the fields for example).
OR
B. The server simply returns a new HTML fragment containing the form with error messages and styles pre-applied. No need to process anything client-side except swap-out the form.
To me option B seems like the easier/quicker option but I can't help but feel that it isn't 'best practice'. Is there pros/cons for either method?
Separation of logic is a huge one here I reckon.
As a project grows, you generally have a front-end team and a back-end team. Imagine the website gets a huge makeover but the logic stays the same. Option B is harder to change the style when the layout is enforced server side.
The application logic (which is this case is server side validation) should be separate from the presentation layer (which is this case is the html/css rendered by the browser).
But at the end of the day, we get paid to produce results so if your not trying to win an academy award for best quality code, and you got bills to pay, just get it done the quickest way.
I'd go with the first option.
The second option just increases the load on the server ... which you always want to avoid. Plus, I feel that if the styling was done on the server-end, the your website isn't exactly modular ... all styling should be done on the front end only.
This is sort of an opinion question but there are a few objective things to say about the topic. Your first option, the pure JSON choice is best used for apps that focus on speed an keeping HTTP requests as small as possible.
The other option, to process your form server-side then return the new form through AJAX doesn't seem to have too many advantages to me. If you're going that route then why bother with AJAX at all? Why not just do a regular form post to the server?
I usually prefer a front end validation and server-side verification. This way you can avoid a JSON call at all if things aren't valid but just in case someone sneaks something in there the server-side code will verify.
I would establish a JSON scheme for validation on the front end. Just basic stuff like what you're checking for on each field, which fields are optional, etc... That gets baked into every page with a form on it. Then let your front end devs pre-validate to avoid unnecessary calls in whatever way makes the most sense to them.
Pre-built errors isn't against any best practice I'm aware of and it's not a terrible way to go (people tend to throw the UI manual of style out the window when it comes to forms anyway), but sometimes you'll want to give more specifics or different errors for different problems.
Always aim for having your cake and eating it too, IMO.

Favorite Web Form Validation Technique

What is everyone's favorite way to sanitize user data?
I've been using Javascript, but have recently required something more secure (people can turn it off, after all), so I was looking at Flex, but thought I'd ask the community what they thought.
NEVER NEVER NEVER use javascript or any other client-side technology for the only validation. You can use client-side validation to save some load on your server or make your app seem more responsive by showing the error sooner when validation fails, but you should always validate using server-side code.
Personally, I like the ASP.Net validation controls because it gives you the benefit of client-side validation with security of server-side, without having to write your logic twice. Of course, the stock controls are pretty bare, but you can extend them.
Validation should ALWAYS be done server-side. Doing it client-side, in addition, is fine.
How you do it depends on what your app is written in. Any language should be able to handle validation; the logic used is what matters, not the language.
It also depends on what you're doing with the data you're given. Putting it in a URL or storing it in a SQL database requires two very different kinds of sanitization. If at all possible, white-list valid values--don't black-list invalid values. Someone will always be able to come up with a new mal-input you hadn't considered.
Depending on the requirements of your project you may or may not want to implement client-side validation. However, server-side validation should ALWAYS be implemented. I prefer to white-list appropriate inputs and values as opposed to black-listing invalid data because this ensures that no one will ever slip something by that I failed to consider.
always use server side validation at the very least
use regular expressions
PHP Example:
preg_match('/^[\w][\w\,\-\.]*\#[\w]+[\w\-\.]*$/', $_GET['email'], $matches);
if (count($matches) > 0) {
$_GET['email'] = $matches[0];
} else {
die('invalid email address');
}
It's recommended to use both server- and client-side validation.
I use JQuery for client side validation.

Categories