html5 login localstorage for days - javascript

Html5 login localstorage for days. This HTML5 Login script uses localstorage to stores users that and everything works fine.
But I need to add one more thing. I want once the user log in for the first time, the app will store the users info in html5
browser for like 30 days, when 30 days elapse, the user will be redirected back to login again. Can someone help me with that?
Thanks.
<script>
$(document).ready(function(){
$('.send').click(function(){
var uname=$('#uname').val();
var pass=$('#pass').val();
if(uname==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter Your Username');
}
else if(pass==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter your password');
}
else{
$('.error').hide();
var userdata= "uname="+uname+"&pass="+pass;
window.localStorage["uname"] = uname;
window.localStorage["pass"] = pass;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Checking your details</span>');
$.ajax({
type:"post",
data:userdata,
url:"http://localhost/login.php",
cache:false,
success:function(msg){
$("#loader").hide();
$('.error').fadeIn(200).html(msg);
}
});
}
});
});
</script>

1) localstorage data won't expire like cookie. it will stay like it for years.
2) if you want to set expiration date add expiration date as value to localstorage then retrieve this info every time and check you condition like number of days, or hours, or months.
or
3) use cookie where you can set expiration date.

Simply set when the data is set in the localStorage (via another variable in it), and each time the app loads, check for that value and compare it with the current date/time.

As I mentioned in a comment (and Shomz mentioned in his answer), you need to set the current date in the local storage just as you store the username and password (are you sure you need to store the password in local storage -- doesn't seem necessary) and then check if that value is set and compare it to the current date.
Update: fixing the code (forgot to convert the local storage date from a string back to a date object, plus I had a missing close bracket, oops!).
jsfiddle with an example usage: http://jsfiddle.net/uqpywLv3/17/
<script>
$(document).ready(function(){
$('.send').click(function(){
var uname=$('#uname').val();
var pass=$('#pass').val();
if(uname==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter Your Username');
}
else if(pass==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter your password');
}
else{
$('.error').hide();
var userdata= "uname="+uname+"&pass="+pass;
window.localStorage["uname"] = uname;
window.localStorage["pass"] = pass;
// is storing the password this necessary?
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Checking your details</span>');
$.ajax({
type:"post",
data:userdata,
url:"http://localhost/login.php",
cache:false,
success:function(msg){
// store the current date
window.localStorage["ldate"] = new Date();
$("#loader").hide();
$('.error').fadeIn(200).html(msg);
}
});
}
}); // end .send click handler
// check if the user is logged in
if (typeof window.localStorage["ldate"] != "undefined") {
// localstorage seems to store the date as a string
// so convert it to a date object
var memDate = new Date(window.localStorage["ldate"]);
var expDate = new Date(); // current date.
expDate.setDate(-30); // set to 30 days ago.
if (memDate > expDate) {
// user's last login still valid
// do whatever you think is appropriate here
} else {
// user's last login was past 30 days ago
// perhaps call function to log them out on server side
// and show login form?
}
} else {
// the user is not logged in.
// put your code for showing the login form here
}
});
</script>

Related

PHP not accessing Javascript cookie

I am creating a small CRUD web app where I need the user to enter their password when they wish to delete an item from the database, I have an onClick() on the delete button on the HTML table which passes the ID of the product to be deleted to the js function.
When the function runs I wish to confirm that they really want to delete the product and then ask for their password and store it in a cookie. BUT IT DOES NOT SEEM TO WORK :(
I am setting a cookie using javascript like
document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php;
With this line of code, when I console.log(document.cookie), it shows me the cookie in the console like
password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja
when I redirect to another PHP page using window.open() I can not access this cookie.
print_r($_COOKIE); <- only shows me the PHPSESSID only.
When I explicitly try to access the cookie using the following line
$userPassword = $_COOKIE[password]; it gives me undefined index 'password'
This is my code.
myproject/admin/view-products.php (This is the page where I try to set the cookie using javascript)
function deletePrompt(id) {
const now = new Date();
const time = now.getTime();
const expiresIn = time + (50 * 1000);
now.setTime(expiresIn);
const path = `../includes/delete-product.inc.php`;
const intent = confirm("Are you sure you want to delete this products");
if (intent === true) {
const userPassword = prompt("Enter password");
document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
console.log(document.cookie);
return;
window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
}
}
myproject/includes/delete-product.inc.php (This is the PHP page where I need to access the cookie)
<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";
if (isset($_SESSION["adminId"])) {
$productId = $_GET["id"];
$userPassword = $_COOKIE["password"]; //<- This throws undefined index error
if (deleteProduct($connection, $productId, $userPassword)) {
header("location: ../admin/view-products.php?msg=deleted");
exit();
}
else {
header("location: ../admin/view-products.php?msg=incorrectPass");
exit();
}
}
else {
header("location: ../admin/login.php");
exit();
}
To anyone else facing this the problem, the solution is that cookies don't get sent across directories, so you need to have the recipient file in the same domain if you wish to transfer cookies across them otherwise it won't work.
eg.
Following pattern will work
youProject/someDirectory/file1
youProject/someDirectory/file2
Following will NOT WORK
youProject/someDirectory/file1
youProject/someOtherDirectory/file2

Getting website's time to set time range

Is there any way to get the current time of website in order to set range time for reaction?
e.g if current time of website >= 14:00 && current time of website < 15:00
do reaction
else
another reaction
I want to do this checking type of fuction every 30' sec
EDITED
e.g If in my country the time is 14:00 and in another one is 19:00 I want to do the reaction to another country based in my country's time. Correct my if I do smthng wrong.
here is the code for php file to fetch server time, name it t.php.
<?php
$b = time ();
echo date("H",$b);
?>
and here is the code for other file on which you use ajax: Run this file using xamp/wamp.
Place both files in sane directory .
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.ajax({
url : "t.php",
type: 'GET',
success: function(data){
if(data >= 9 && data < 10){
alert('yes');
// do something
} else{
alert('no');
// do something
}
}
});
}, 1000);
</script>
Here is the Solution:
you can find current time of website using javascript because it is a client side scripting language
In php I think there is no way to find client's time (not sure), That's why I am using jquery.
to use it in php file use ajax.
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
function call_notification_count() {
var todaydate = new Date(); // current time of browser. or you can say Time of client's location
var month = todaydate.getMonth()+1+"";if(month.length==1) month="0" +month;
var date = todaydate.getDate()+"";if(date.length==1) date="0" +date;
var year = todaydate.getFullYear();
var hours = todaydate.getHours();
var minutes = todaydate.getMinutes();
var seconds = todaydate.getSeconds();
var todaytime = hours+":"+minutes+":"+seconds;
var todaydateonly = year+"-"+month+"-"+date+" ";
alert(todaytime);
if(hours >= 14){
// do something
}else{
// do something
}
}
setInterval(call_notification_count, 3000); // Set time intervel here like for every 30 sec.
});
</script>

is it possible to redirect the user to same page after login using client side technology

I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.

Javascript - checking if cookie exists on page load isn't working for me

I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?

How to set your input fields with local storage variables using jquery

I am making a mobile web app using jquery mobile and jquery.
Now I have it so far that when I check my checkbox it saves my variables into the local storage from your browser. But it won't put these variables back into my input fields.
Here is my script. The function validate() saves the variables into local storage.
$(document).ready(function () {
if (localStorage["mail"]) {
$('#mail').val(localStorage["mail"]);
}else{
$('#mail').val("");
}
if (localStorage["password"]) {
$('#password').val(localStorage["password"]);
}else{
$('#password').val("");
}
});
function validate(){
if ($("remember:checked")) {
var mail= $("#mail").val();
var password= $("#password").val();
localStorage["mail"] = mail ;
localStorage["password"] = password;
localStorage.setItem("mail", mail) ;
localStorage.setItem("password", password) ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
Can anybody help me ?
thank you
it seems that $("remember:checked") is not a valid selector (a . or a # is missing). So probably your values are never saved into localstorage
when you check for existence of an element you should use length property instead
if ($("<your selector>").length) {
...
}
You are doing it wrong for setting and getting an item in local storage Use
localStorage.setItem('someval',1)
localStorage.getItem('someval'); // 1

Categories

Resources