validation data before insert them into the database - javascript

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.

Related

Matching Passwords with Front-End or Back-End?

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.

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.

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.

Server-side highscores for a Javascript-written game

I'm implementing a simple game in Javascript, and am interested in having an online highscores table for it, so that players can compete against one another. I've two concerns about this:
What is the simplest server-side program I need for this purpose? I don't need a full-fledged "web application", just something simple that gets POST requests with highscores, updates a database and sends back lists of scores. I'm familiar with Django. What are your suggestions?
How can I make the highscores table reasonably secure? I'm aware that making it bulletproof against competent and dedicated hackers is difficult, but I wouldn't want anyone with access to the Javascript sourcecode to be able to submit fictitious scores too simply. Any tools for this purpose?
It's going to be pretty hard to secure the high scores. I mean, it's not enough to ensure that it comes from your page, because if, say, the JavaScript function is submitHighScore(n) then they can always type javascript:submitHighScore(10000000) in the address bar on that page and have it work.
What comes to mind is perhaps some sort of hash function that generates specific codes that match certain levels in the game. When submitting the score it would also submit this hash, so users would have had to get to this level in order to get that equivalent score.
Another option would be for the game to pull in some kind of key that only works temporarily, so as you went along the key would change and then the score would be submitted to a central server intermittently.
Keep in mind that really determined individuals can always just track the data being sent to your data and decompile it.
You could go the Broderbund route and ask the player trivia questions which are validated server-side to ensure they really did pass the level they said they did...something like "What color was the monster in the previous level?"
To submit score securely, sign it (you'd also need to ensure that the score isn't faked before it's signed and sent, but that's another problem).
Hide a secret in JS code, and send highscore + hash(highscore + secret) to the server. The hash could be MD5/SHA1 — there are easy to find JS implementations.
Of course it won't stand anyone carefully analysing the JS code, but at least someone won't be able to submit fake highscore just by tampering with HTTP traffic.
On hiding stuff in JS:
You can't really hide it (it's ultimately futile like DRM), but you can try hard to obfuscate it and make debugging painful.
Don't put the secret as a literal in the source code - compute it at run time combining results of several functions, local and global-ish variables.
Minify all code, remove sourcemaps.
Add bits of code that don't do anything, but seem to be important, to make debugging more confusing.
Don't put anything in global scope, but do rely on shared mutable state by passing closures and arrays around.
Rely on Date and timers to cause race conditions to make your code produce wrong results if it's paused in the debugger (just don't make it too tight to allow it to run on slow machines).
If the game is deterministic (like a puzzle game), then users could submit highscore in form of a log of steps taken to win (user's input) that you'd replay on the server to calculate the score.
This would change attack from finding/emulating score-submitting function to witing AI or hacking the game itself to make it easier to play (but still within its basic rules).
1.) Any CGI script that can talk to a database and understand JSON, or other format of your choice, will do the work.
However, if you're familiar with Django, building your server on top of Django would be the most simple, in the sense of what you have to learn and how much application code you have to write. Seemingly simple CGI script can turn out rather complex if you write it from scratch.
I found django-piston to be a handy Django app to quickly write a REST-style API server. It supports JSON so it should be easy to interface with your JavaScript game.
2.) The most casual cracker will go for a replay attack and its variants: peek at the page source and execute a JavaScript function, intercept HTTP requests and resend it (should be easy with a Firefox add-on like Tamper Data).
To counteract the former, you can obfuscate the source code and HTTP body;
Minify the JavaScript code
Encode the message you send to the server with Base64 or other encoding algorithm
The latter can be prevented by requiring all update requests to include an one-time password ("session token" in the Wikipedia article) that was recently acquired from the server.
I am thinking about this myself. What seems to be the most reasonable solution to me is this:
1) Sessions, to disallow tampering with the scoretable outside the game.
2) Log every action in the game and send it to the score server. The server will then calculate if those actions actually give such score. If you also log the time spent playing the game, you can further minimize the chance of an attacker to bother himself enough to break your game. This will also enable you to make a replay script like Arcade servers with hi-score tables have and in case of a suspicious score, you can watch the replay and decide for yourself if the score is real. The cheater would have to use a clever bot to play your game - and unless you have a game for real prizes, noone will try that hard.
If the cheater won't even analyze your code, sessions will stop him. If he reads your code, he would quickly break anything similar to hashed scores, secrets, tokens and whatsoever. But if you make the game-logging script thorough enough, he will give up.
In answer to your question:
1.) This depends on your environment and coding preference. PHP, Python, ASP.NET are a few that come to mind. Sense you already know Python (from your profile) you can use a Python CGI script to do this or use one of the many frameworks for Python (Zope, Django, Pylons,...).
see: http://www.python.org/doc/essays/ppt/sd99east/index.htm
for info on Python CGI.
2.) A few tricks for security: (none or full-proof)
Hidden Text Box in HTML with encoded value that server checks to match a cookie to ensure high score comes from your page.
Server Script only accepts values from a specific domain
You could use a combination of one of the methods above, as well as simply requiring the user to be registered to be able to post high scores. Non registered users could view their current score compared to existing high scores, but in order to post your high score online, you must have already logged in with your registered account, or provide it when the app goes to update the score online.
A simple message along the lines of "Your high score is X, and ranks ### in the high score table. To post this score online, please register with us first".
The better I think, is to make the calculation of the score directly into the python files of your django app.
Instead of calculate it in the javascript file. You send the datas to compare with your data basis with a POST request, then you calculate the score and you store it in your data basis. Like this, you don't make circulate the score across the web to your servers. Which is completely safe because you are only doing local stuffs.

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