Age verification with just javascript and no cookies: how? - javascript

I'm building a website for a EU company that sells beer, and need an age verification splash screen. That's quite easy, and I have one in place already. I use a lightweight cookie plugin (cookie.js found on the excellent http://microjs.com) in the page header. This is more or less my set up:
JS (in <head> element)
if (cookie.get("agechecked")) {
document.documentElement.className += " agechecked";
}
CSS
.agechecker { display: block; width: 100%; height: 100%; ... }
.agechecked .agechecker { display: none };
Sadly, for few visitors the agecheck doesn't work properly. Some can't get past it, for others it pops up after every page load, and for some, cookies just don't work which means the checkbox 'remember me' is broken to them. I want to use an alternative route to at least make sure the agecheck doesn't prevent anyone from viewing the site completely.
I only have javascript to my disposal and don't want to use cookies. Since I'm quite sure the equivalent to a session is a cookie that expires after the browser closes - so that kind of limits my options to... yeah, what?
Alternatives I'm considering:
jStorage - but that relies on a framework such as jQuery or Prototype, meaning I'd have to load jQuery in the page header. That won't do;
The window.name method, combined with JSON to store data in the window name property, which is a bit too hacky for my taste, and also doesn't carry over to other tabs
I could check the referer (was the visitor already on another page on this domain?) which is a 90% guarantee he/she got through the agecheck
I couldn't find any real useful information here on stackoverflow, but I'm sure some of you have built age verifications. How did you solve these issues?
(edit: I know, I should build a form that actually posts to the server where I can store and retrieve information in a gazillion different manners, but just take it from me I have to rely on javascript. Can't help it)

HTML5 webstorage (localStorage) is a client-side persistency mechanism. For browser compatibility, see http://caniuse.com/#feat=namevalue-storage.

I read your question as you need a way to persist state across webpages without using cookies.
Here are a few choices:
Html5 local storage http://diveintohtml5.info/storage.html
data in the URL (http://example.com/app/agechecked/main)
data as a GET variable ( ?agechecked=1 )

Related

Hiding my admin login information HTML

I'm pretty new to HTML, like 1 week new. I am making a web store and I want to be able to login into an "admin panel" to make it easier for me to manage my products. Add new, remove, rename etc. My problem is, I have my login information stored in the html code and I use if-statements to check the validity.
When I was testing the code, I was curious and wanted to inspect element. Unsurprisingly, there was my entire login information and anybody can have access to it.
I need to somehow hide it, or hide the login fields from users except me. But I do not know how to approach that. I thought of a few solutions like have a hidden part on the store page and if I click it a certain amount of times then it will show the fields. But I think I'm complicating it.
Any ideas are greatly appreciated. Thanks. Below is my function for logging in.
function login()
{
var username = "test username";
var password = "testpassword";
if(document.getElementById("username field").value == username && document.getElementById("password field").value == password)
{
var btn = document.createElement("BUTTON");
document.body.appendChild(btn);
<!-- hide the user name field after login -->
document.getElementById("username field").hidden = true;
<!-- hide the password field after login -->
document.getElementById("password field").hidden = true;
<!-- hide the login button after login -->
document.getElementById("login btn").hidden = true;
<!-- show a message indicating login was successfull -->
window.alert("Login successfull! Welcome back admin!")
}
else
{
window.alert("Sorry, you are not authorized to view this page.");
}
}
And this is a screenshot of the inspect element. I don't want anything too crazy like a database because I'm the only user, just a way to be able to access the admin panel without exposing myself. Thanks again.
Inspect Element Screenshot
EDIT:
I am not using my own server, I am using Wix.com to make the initial website and then using the HTML widget to create a webstore. I don't think they allow people to have any communication with their servers whatsoever.
Username and password validation should never be done on the client side. It should always be done on the server. Do not use javascript for this task. Allow your user to enter their username and password in a form, and then submit the form to a server side script to validate their credentials. Doing it on the client side will never be secure.
There's no easy solution to your particular request, but before I oblige you with the details I'd like to stress three very important points.
1: Javascript is not Safe
Javascript is a client side language, which means every piece of data you'll ever be dealing with that comes from your user can be directly modified. These include, but are not limited too, any values or attributes of HTML tags, inline Javascript, loaded image files, etc. Essentially, anything that is cached on the user's computer can be modified and might not be what you're expecting to receive.
As such, a Javascript authentication system is absolutely not safe by any definition of the word. For a local page that only you can access, it would do the job, but that begs the question of why you need authentication in the first place. Even then, as a new developer you'd be widely encouraged to never try do it anyway. There's no point practising and learning how to do something in a completely insecure way and nobody is likely to suggest it.
2: Authentication is a tricky topic
Authenticating logins is not an easy thing to do. Yes, it's easy to make a login script but it's not easy to do it properly. I would never try to discourage anyone from making something themselves nor discourage a new developer from pursuing any goal, but authentication is not something you should be learning only a week into HTML. I'm sorry if that comes across as harsh, but there are people who have been masterminding applications for years who still don't do it securely.
3: Third Party are Best
It's possible to make your own authentication system that likely only the most determined of attackers could access, but it wouldn't involve Javascript authentication. Consider Javascript to be more of a convenience to the user than a solution for the developer. Javascript can do some remarkable things, but being a trusted source of data is something it will never do. Please understand this important point, because the source code you have provided is riddled with security flaws.
--
Now, on to what you want to do. Identifying that you're the "admin" user is something you're putting a password in to do. If you could figure out you're the owner of this site before putting in your password, you wouldn't need the password, right? In short, you can't do what you want to do; not reliably, anyway. It's possible to only show those forms if you're using a particular IP, but IPs can be masked, imitated and changed, which makes it insecure.
There are several third party authentication methods that you can use to do all the heavy lifting for you. All you do is put the fields on your page and they'll handle the rest. You can use any Social Media login (Facebook, Twitter, Google Plus, etc) or you can use O Auth, which deals with all the heavy lifting of authentication for you.
I don't mean to discourage you, nor anyone else, from pursuing their own authentication methods but if I'm honest with you I think this is something way beyond your skill level that you shouldn't be considering right now.
If you serve the pages via a server, you can enforce basic HTTP auth. Should be really simple to set up and you would have the benefit of a standard of security.
Here are the Apache docs for this, for example.

Jquery to pull the URL of a webpage

I am looking for a way to use Jquery (or any other open source script) to pull the URL of a particular webpage. I am working on a service that will pull the original URL of any webpage - consider a scenario where I load google.com but have entered yahoo.com in the address bar (without pressing enter key) - the script should be able to validate if the the URL on the address bar is the same as the actual URL or if it is different.
There is no way to do this. And there better not be any in the making. There is no reason to need such information, and it's a violation of user privacy.
No dear, Absolutely no way to do this.
and i agree with #bjb568 , its definitely violation of user privacy.
you can get the current page URL in your script.
But why you need this kind of functionality.?
i will advise you to find any alternative of your requirement,
You can get the current location of the page using regular Javascript, but I do not think you can get the currently typed address bar, although I do not see where you should ever need to.
In response to everyone on here saying it is a breach of user privacy: I don't think grabbing the URL or the typed address bar on the current page is a breach of privacy or security unless you are somehow able to change the address bar to make it seem like you are on a different site - like being on Google.com and it saying you are on Yahoo.com. But, from the OP's original question, it just seems like he wants to get the information; not change it.
Using Javascript, you can use var location = document.location.href
The closest you can get to change the addressbar is window.history.pushState(), but browsers have a security settings that do not allow domains outside of the current domain to be used.
My first question that comes to mind: "Why on earth does he want to do that???" If it was possible you would have to interact with each browser directly which is not possible.
jQuery is just a client-language that interprets with each browsers "engine" (that handles rendering of html, javascript etc) and not the browser itself (menus, settings etc). Secondly, if it would work: How often would you check? Each keypress? Every 10 seconds? It would not be doable in a proper way - even if it was possible.
I think you should rethink your issue and try to explain why you want to do this. It might be other (better) solutions that would handle your issue in a better way.

how to use cookies in JQuery

It is easy to use cookies in serverside like PHP,.NET...etc
I would like to use cookies for static website which is just HTML, CSS & JQuery .
Anybody know how to implement cookies in JQuery ?
the jQuery Cookie plugin is one way to go:
https://github.com/carhartl/jquery-cookie
You use it like so:
$.cookie('cookie_name', 'value'); // to set
$.cookie('cookie_name'); // to get
You can use this plugin
example: to set a cookie
$.cookie("example", "foo");
You don't need a jQuery plugin, you can easily access cookies in JavaScript. Here's how: https://developer.mozilla.org/en/DOM/document.cookie
But maybe the plugins linked in the other answers will give you easier access.
Are you sure that cookie is exactly what you need? There are localStorage which is much better in many scenarios.
You wrote that you want use cookies with static website, but cookies will be sent to the server and returned back. Is it really needed that you sent the information to the server on leading the static website? It increases the size of HTTP header and decreases the performance of the web site (see here for example).
Cookies have very hard restrictions. Corresponds to the section 6.3 of rfc2109 or 6.1 of rfc6265: At least 4096 bytes per cookie, at least 50 cookies per domain (20 in rfc2109), at least 3000 cookies total (300 in rfc2109). So the cookies one can't use to save too many information. For example if you would save state of every grid of every your web page you can quickly achieve the limits.
If you just want to save some users preferences for the page you can use localStorage and the usage is really easy.
If you prefer to use some jQuery plugin instead of direct usage of localStorage and if you need support old web browsers (like IE6/IE7) then you can use jStorage for example. In the case you has only less size of storage: 128 KB instead of 5 MB (see here and IE userData Behavior), but it's better as 4K which one has for cookies (see here).
I want that you just think a little about alternatives to cookies.
Read Cookie:
var cookieValue = $.cookie("cookieName");
Write Cookie:
$.cookie("cookieName", "CookieValue");
You can use plain JS by accessing document.cookie.
See: http://jsfiddle.net/ShsYp/
Also: https://developer.mozilla.org/en/DOM/document.cookie
A simple, lightweight jQuery plugin for reading, writing and deleting cookies.For details demo and example see a link.https://github.com/carhartl/jquery-cookie

Facebook makes their AJAX calls through iframe?

I want to implement AJAX like facebook, so my sites can be really fast too. After weeks of research and also knowing about bigPipe (which is not ajax).
so the only thing left was how they are pulling other requests like going to page/profile, I opened up firebug and was just checking things there for what I get if I click on different profiles. But the problem is, firebug doen'tt record any such request and but still page gets loaded with AJAX and changes the HTML also, firebug does show change on html.
So I'm wondering, if they are using iframe to block firebug to see the request or what? Because I want to know how much data they pull on each request. Is it the complete page or only a part of page, because page layout changes as well, depending on the page it is (for example: groups, page, profile, ...).
I would be really grateful if a pro gives some feedback on this, because i cant find it anywhere for weeks.
The reason they use iframe, usually its security. iframes are like new tabs, there is no communication between your page and the iframe facebook page. The iframe has its own cookies and session, so really you need to think about it like another window rather than part of your own page (except for the obvious fact that the output is shown within your page).
That said - the developer mode in chrome does show you the communications to and from the iframe.
When I click on user's profile at facebook, then in Firebug I clearly see how request for data happens, and how div's content changing.
So, what is the question about?
After click on some user profile, Facebook does following GET request:
http://www.facebook.com/ajax/hovercard/user.php?id=100000655044XXX&__a=1
This request's response is a complex JS data, which contain all necessary information to build a new page. There is a array of profile's friends (with names, avatar thumbnails links, etc), array of the profile last entries (again, with thumbnails URLs, annotations, etc.).
There is no magic, no something like code hiding or obfuscation. =)
Looking at face book through google chromes inspector they use ajax to request files the give back javascript which is then used to make any changes to the page.
I don't know why/wether Facebook uses IFRAMEs to asynchroneously load data but I guess there is no special reason behind that. We used IFRAMEs too but now switched to XMLHttpRequest for our projects because it's more flexible. Perhaps the IFRAME method works better on (much) older browsers, but even IE6 supports XMLHttpRequest fine.
Anyway, I'm certain that there is no performance advantage when using IFRAMEs. If you need fast asynchroneous data loading to dynamically update your page, go with XMLHttpRequest since any modern browsers supports it and it's fast as HTTP can be.
If you know about bigPipe then you will be able to understand that,
As you have read about big pipe their response look like this :-
<script type="text/javascript"> bigpipe.onPageArrive({ 'css' : '', '__html' : ' ' }); </script>
So if they ajax then they will not able to use bigpipe, mean if they use ajax and one server they flush buffer, on client there will no effect of that, the ajax oncomplete only will call when complete data received and connection closed, In other words they will not able to use their one of the best page speed technique there,
but what if they use iframe for ajax,, this make point,, they can use their bigpipe in iframe and server will send data like this :-
<script type="text/javascript"> parent.bigpipe.onPageArrive({ 'some' : 'some' });
so server can flush buffer and as soon as buffer will clear, browser will get that, that was not possible in ajax case.
Important :-
They use iframe only when page url change, mean when a new page need to be downloaded that contains the pagelets, for other request like some popup box or notifications etc they simple send ajax request.
All informations are unofficial, Actually i was researching on that, so i found,
( I m not a native english speaker, sorry for spelling and grammer mistakes! )
when you click on different profile, facebook doesn't use ajax for loading the profile
you simple open a new link plain old html... but maybe I misunderstood you

Can JavaScript survive a full HTTP Request Roundtrip?

Is it possible to have JavaScript (specifically, JavaScript variables and their content) survive full HTTP requests? I'd like to 'cache' / persist information client-side across page changes, without having to use hidden form fields or anything HTML related at all.
Is this possible?
Edit: Let me add a use case for what I mean.
Let's say I have a JavaScript array
called arrayOfPersons which I
loaded as part of page /HomePage,
and now it contains 1,000 objects
client-side.
Now the user switches the page and
loads an entirely new page /MyAccount into the
browser
My Goal: Still have the arrayOfPersons that I loaded on page /HomePage available after the user requested the entirely new page /MyAccount.
Hope that clarifies what I mean. Thank you!
Just to add to Nick's answer, different browsers support the idea of persistent storage in one form or another. There have been a bunch of efforts to normalize these for all browsers over the last year.
Here's one library that wraps around HTML 5's DOM Storage, Microsoft's UserData, Session Cookies and window.name (using JSON serialization as window.name can only store strings).
Here's another that focuses on window.name only (which actually works in Opera 9+, IE6+, Firefox 1.5+, Safari [3 I think).
Here's a jQuery plugin that uses a .swf (flash) file to offer the most cross-browser support (although it does support native solutions if you configure it to do so). I can't vouch for it but it should be mentioned for this jQuery-lovin' community.
Yes it is possible. Its a bit of a hack i used to maintain the page state(in client side) throughout the entire session.
Have a base page (like master), that never refreshes through out the session and it only got the iframe within it. And all your application pages will be loaded in to that frame..
Store your state info into that master page as JS objects. And you can access the master page (parent) javacript objects from your child page in a iframe. And it ll be maintained through the session in client side.
This is the simplest way. And it works pretty neat.
Found a useful one
JSOC: JavaScript Object Cache
The JSOC framework is a a pluggable,
extensible, open source client-side
caching framework for JavaScript.
JSOC offers Web developers a
straightforward way to perform common
caching techniques (add, replace,
remove, flush, etc.) inside any
JavaScript-enabled browser.
Since JSOC is a standalone JavaScript
module, incorporating JSOC into a Web
development project is a matter of
including a script reference, and
working with common caching methods.
Low-level methods are contained in the
JSOC JavaScript module so that
developers can focus on the Web
development task at hand.
Newer browsers support DOM storage which let you store arbitrary data that can persist between pages. You can also use a hidden Flash app to remember things. There are libraries like Dojo Storage which handle the detection for you, so you just save your data and it will use whatever is available.
It won't automatically save all your Javascript variables for the next page - you'll need to add an onunload handler to store what you want when the user leaves the page.
A frameset would give you a place to persist your javascript, but full page load... I think not.
Cookies might also be useful for "persisting" data, but this isn't what you asked.
if i understand you correctly, all you need is to add your own caching functions into onSubmit of all forms and onClick of all links, smth like:
var cachedpages;
$("A").onclick(function(){
url = $(this).attr('href'); // maybe hash?
if (cachedpages[url]) {
// replacing all html
} else {
$.get(url, function(data){
cachedpages[url] = data;
// replacing all html
});
}
return false;
});
One possibility is to use a frameset and keep the objects there, another to serialize them and persist the data via either of
window.name
document.cookie
location.search
document.cookie is the canonical way to store data between invocations of pages in the same domain and provides mechanisms to control access and lifetime.
If you use window.name, the data persists over the lifetime of the browser instance.
Using window.location is more tricky and you have to explicitly modify the links to send along the data (which can be easily done using event delegation).

Categories

Resources