Set cookie using jquery on form submit / log in - javascript

Looking for direction or input on something I'm not familiar with. I created a two page site with a log in form that redirects user to the second page with the correct "access code" I created. It works as expected. What I would like to do is set a cookie when user is logged with jquery or vanilla js, then check if the user has logged in before and if they have not redirect back to log in form. I know I have not "tried anything" but just looking to learn and get an idea or advice
HTML:
<form class="form--log-in" id="log-in-form">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First Name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="Last Name">
</div>
<div class="form-group">
<label for="userEmail">Email Address</label>
<input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Email Address">
</div>
<div class="form-group">
<label for="accessCode">Access Code</label>
<input type="text" class="form-control" name="accessCode" id="accessCode" placeholder="Access Code">
</div>
<div class="form--log-in__submit-container">
<button type="submit" class="btn button-submit form--log-in__submit" id="form_submit">
Log in
</button>
</div>
</form>
jquery:
// doc ready
$(function () {
checkCookie();
}
submitHandler: function (form) {
var formData = {
'method': 'register',
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'userEmail': $('input[name=userEmail]').val(),
'accessCode': $('input[name=accessCode]').val(),
};
var validationObj = this;
$.ajax({
type: 'POST',
url: form_submit_endpoint,
data: formData,
success: function (res) {
var parsedResponse = JSON.parse(res);
if (parsedResponse.status === 'success') {
console.log('success');
_siteNS.Utils.setCookie('x-access',true,365);
logInModal();
} else if (parsedResponse.status === 'error') {
validationObj.showErrors({'accessCode': 'Incorrect Access Code.'});
console.log('error');
}
}
})
}
function _readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
function _setCookie(cookiename, value, numberofdays) {
var d = new Date();
d.setTime(d.getTime() + (numberofdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookiename + "=" + value + ";" + expires + ";path=/";
}
function checkCookie() {
// set cookie to boolean var
var myCookie = document.cookie === null;
//if the cookie is true and location is not the video page set location to video page
if(myCookie === true && (!location.href.match(/video-page/))){
window.location.replace('video-page');
}
//if the cookie is false and location is not the site root set location to site root
if(myCookie === false && (!location.href.match(/index/))){
window.location.replace('index');
}
}

Here is how you would do it.
After the ajax success, set a localstorage item like 'isLoggedIn', 'true'
In another JS file that is loaded for every page globally, you should check if localstorage flag is set to true.
Redirect to required page based on the result
NOTE: The above method is only to learn about how you can achieve auth. This is definitely not secure. You would have to use some kind of authentication like JWT and set the token in your localhost or cookie that will be sent to the server for each request.
Please do read about authentication before you build a real world app.
$.ajax({
type: 'POST',
url: form_endpoint,
data: formData,
success: function(res) {
var parsedResponse = JSON.parse(res);
if (parsedResponse.status === 'success') {
// set localstorage flag if successfully logged in
// NOTE: this is not secure. You need to have some kind of JWT token to be implemented
if (typeof(Storage) !== "undefined") {
localstorage.setItem('isLoggedIn', 'true');
} else {
// Sorry! No Web Storage support..
}
}
}
});
// In another JS file that is loaded globally
window.on('load', function() {
if (typeof(Storage) !== "undefined") {
const loginStatus = localstorage.getItem('isLoggedIn');
if (loginStatus === 'true') {
// redirect him to logged in page
} else {
// redirect him to unauthorized in page
}
} else {
// Sorry! No Web Storage support..
}
})

Related

JavaScript login with cookies

I've been trying to figure out how to do one of the tasks that im given for the past 3 hours and I just can't seem to do it.
This is the task:
Add a login page (login.html) with a login form to the system. When logging in, it creates
a cookie in which the username, password and duration of the login cookie are saved. While there is a login cookie, other sites can be visited. If the cookie doesn't exist it switches to login.html from either page. Clicking on logout deletes the login cookie (moves us back to the login.html) .
this is my HTML code for the login form:
<form action="index.html" id="loginForm" method="post">
<div>
Username: <input type="text" name="uname" id="uname">
</div>
<div>
Password:<input type="text" name="pwd" id="pwd">
</div>
<div>
<button type="submit" id="myBtn"> Sign in </button>
</div>
</form>
Hope someone could help me, I've got little time left. Thank you in advance! :,)
document.querySelector('#loginForm').addEventListener('submit', () => {
setCookie('user', document.querySelector('#uname').value, '/')
setCookie('pass', document.querySelector('#pwd').value, '/')
})
if(!getCookie('user')||!getCookie('pass')) if(location.href != 'https://somelocation.example/index.html/') location.replace('https://somelocation.example/index.html/')
// Cookies setting and getting functions
function setCookie(name, value, path, options = {}) {
options = {
path: path,
...options
}; if (options.expires instanceof Date) {
options.expires = options.expires.toUTCString();
} let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value)
for (let optionKey in options) {
updatedCookie += "; " + optionKey
let optionValue = options[optionKey]
if (optionValue !== true) {
updatedCookie += "=" + optionValue
}
}
document.cookie = updatedCookie;
}
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : undefined
}
Explaining:
1.0 Event:
There is event to set values in cookie when using submitting form (functions explaining at 1.2)
1.1 Checking cookies:
Then there is checking if cookie "user" and "pass" do not exist, then you are being redirected
1.2 Functions:
1.2.0 setCookie:
First we are getting path and options that user set, then checking if expires function is in Date format (e.g. 1653420565221), and if it's true then converting to UTC string. (Skipped part with for...in loop because not in use) After all, cookies setting to new one.
1.2.1 getCookie:
Just getting and encoding cookie property using match(), and if it's not exist, returning undefined.
In my experience, you need to use PHP and a database because if you just use javascript, the users won't be able to access their accounts if they simply clear their cookies.
Sorry for not being very insightful on how to answer your question, but PHP would be the first step, someone else can elaborate on how to get the PHP set up, because it is not my specialty.
Edit:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()"></body>
</html>
source of code: w3schools

Contact Form Backend needed, Frontend given

I used to host a website at carrd.co with the pro plus plan. I chose the expensive plan because of the possibility to download the website and host it on an own server.
What I did not know, was that this did not include server-side code.
My problem is, that I have the front end code, but every PHP code I try fails to interact with this code. Since I can only develop with Java, I cannot get to a solution by myself.
The issue is that I do not know what the next step is to make this code work on my server so that it successfully sends me an email when this form is submitted by a user. I do not have any backend code and do not know where to start.
1) where can i put a PHP file to answer to this request? How do i have to name it?
2) how can i parse the arguments?
3) how do i have to format the answer from the php script to the ajax script?
Could you guys please help here? Thanks a lot!!!
(i might even be able to solve this with some good hints if you cannot be bothered to provide a full solution! I'm thankful for any advice!)
The frontend code:
Form:
<form id="form02" method="post">
<div class="inner">
<div class="field"><input type="text" name="name" id="name" placeholder="Name"
maxlength="128"/></div>
<div class="field"><input type="email" name="email" id="email"
placeholder="Email" maxlength="128"/></div>
<div class="field"><input type="text" name="fname" id="-fname" placeholder="Fname"
maxlength="128"/></div>
<div class="field"><textarea name="message" id="message" placeholder="Message"
maxlength="16384"></textarea></div>
<div class="actions">
<button type="submit">Send Message</button>
</div>
</div>
<input type="hidden" name="id" value="form02"/>
</form>
Script:
function form(id, settings) {
var _this = this;
this.id = id;
this.mode = settings.mode;
this.method = settings.method;
this.success = settings.success;
this.preHandler = ('preHandler' in settings ? settings.preHandler : null);
this.failure = ('failure' in settings ? settings.failure : null);
this.optional = ('optional' in settings ? settings.optional : []);
this.$form = $('#' + this.id);
this.$form.addEventListener('submit', function (event) {
_this.submit(event);
});
this.$form.addEventListener('keydown', function (event) {
if (event.keyCode == 13 && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
_this.submit(event);
}
});
var x = $('#' + this.id + ' input[name="' + settings.hid + '"]');
if (x) {
x.disabled = true;
x.parentNode.style.display = 'none';
}
this.$submit = $('#' + this.id + ' button[type="submit"]');
this.$submit.disabled = false;
};form.prototype.notify = function (type, message) {
if (message.match(/^(#[a-zA-Z0-9\_\-]+|[a-z0-9\-\.]+:[a-zA-Z0- 9\~\!\#\#$\%\&\-\_\+\=\;\,\.\?\/\:]+)$/)) location.href = message; else alert((type == 'failure' ? 'Error: ' : '') + message);
};
form.prototype.submit = function (event) {
var _this = this, result, handler, fd, k, x, $f, $ff;
event.preventDefault();
if (this.$submit.disabled) return;
result = true;
$ff = this.$form.elements;
for (k in $ff) {
$f = $ff[k];
if ($f.type != 'text' && $f.type != 'email' && $f.type != 'textarea' && $f.type != 'select-one') continue;
if ($f.disabled) continue;
if ($f.value === '' || $f.value === null) {
if (this.optional.indexOf($f.name) !== -1) continue;
result = false;
} else {
x = '';
switch ($f.type) {
case 'email':
x = "^([a-zA-Z0-9\\_\\-\\.\\+]+)#([a-zA-Z0-9\\- \\.]+)\\.([a-zA-Z]+)$";
break;
case 'select':
x = "^[a-zA-Z0-9\\-]$";
break;
default:
case 'text':
case 'textarea':
x = "^[^\\<\\>]+$";
break;
}
result = result && $f.value.match(new RegExp(x));
}
if (!result) break;
}
if (!result) {
this.notify('failure', 'Missing and/or invalid fields. Please try again.');
return;
}
if (_this.method == 'get') {
_this.$form.submit();
return;
}
if (x = $(':focus')) x.blur();
this.$submit.disabled = true;
this.$submit.classList.add('waiting');
handler = function (values) {
var x, k, data;
data = new FormData(_this.$form);
if (values) for (k in values) data.append(k, values[k]);
x = new XMLHttpRequest();
x.open('POST', ['', 'post', _this.mode].join('/'));
x.send(data);
x.onreadystatechange = function () {
var result = false, message = 'Sorry, something went wrong. Please try again later.', alert = true, o;
if (x.readyState != 4) return;
if (x.status == 200) {
o = JSON.parse(x.responseText);
if (o) {
if ('result' in o) result = (o.result === true);
if (('message' in o) && o.message) message = o.message;
if ('alert' in o) alert = (o.alert === true);
}
}
_this.$submit.classList.remove('waiting');
if (result) {
_this.$form.reset();
if (alert) window.alert(message); else _this.notify('success', (_this.success ? _this.success : message));
} else {
if (alert) window.alert(message); else _this.notify('failure', (_this.failure ? _this.failure : message));
}
_this.$submit.disabled = false;
};
};
if (_this.preHandler) (_this.preHandler)(_this, handler); else (handler)();
};
new form('form02', {mode: 'contact', method: 'post', hid: 'fname', success: '#contact-done',});
An html form normally uses an action parameter to specify a url for the script to submit the form data to. However it looks like your javascript code is hard-coded to create an ajax post back to a url at /post/contact, which may explain why the examples you have tried do not work.
Yes, you do need a script of some kind on your server to process the response, but it doesn't have to be PHP - whatever your hosting provider supports, and whatever is capable of handling what you want to do with the data.

Login using UrlFetchApp function and scrape private data

I need to scrape private data from portal which doesn't support API.
IMPORTXML can't do this because of login.
I have a link with information of from & to date and the content is table with cost data. I need to login and scrape simple table into my Google Sheet.
I need to log in into this website:
https://www.glami.cz/registrace/prihlasit
and than scrape this url:
https://partner.glami.cz/s/e-commerce/days/866/?from=2016-12-01&to=2016-12-09
The form on this site is:
<form action="/registrace/prihlasit/" method="post" id="frm-signIn">
<dl class="form">
<dt><label for="frm-signIn-username" class="required">Emailová adresa</label></dt>
<dd><input type="text" name="username" id="frm-signIn-username" required data-nette-rules='[{"op":":filled","msg":"Prosím, vyplňte emailovou adresu."}]' class="text"></dd>
<dt><label for="frm-signIn-password" class="required">Heslo</label></dt>
<dd><input type="password" name="password" id="frm-signIn-password" required data-nette-rules='[{"op":":filled","msg":"Prosím, vyplňte heslo."}]' class="text"></dd>
<dt></dt>
<dd><input type="submit" name="send" value="Přihlásit se" class="button"></dd>
</dl>
<div><input type="hidden" name="_do" value="signIn-submit"></div>
</form>
I have this code which works for other websites. In this case the response from logger is still "didnt log in".
function fetchAdminPage() {
var url = "https://www.glami.cz/registrace/prihlasit";
var options = {
"method": "post",
"payload": {
'username': 'LOGIN',
'password': 'PASSWORD',
'send': 'Přihlásit se',
'_do': 'signIn-submit',
"testcookie": 1
},
"followRedirects": false
};
var response = UrlFetchApp.fetch(url, options);
if ( response.getResponseCode() == 200 ) {
// Incorrect user/pass combo
Logger.log("didnt log in");
} else if ( response.getResponseCode() == 302 ) {
// Logged-in
var headers = response.getAllHeaders();
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
// Make sure that we are working with an array of cookies
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
// We only need the cookie's value - it might have path, expiry time, etc here
cookies[i] = cookies[i].split( ';' )[0];
};
url = "https://partner.glami.cz/s/e-commerce/days/866/?from=2016-12-01&to=2016-12-09";
options = {
"method": "get",
// Set the cookies so that we appear logged-in
"headers": {
"Cookie": cookies.join(';')
}
};
response = UrlFetchApp.fetch(url, options);
};
Logger.log(response.getContentText());
};
}
The problem has to be I guess somewhere in payload/options or in url adress. Can't figure out what's wrong and how to log in succesfully.

Why is my newsletter form not working on Amazon CloudFront?

I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.
Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods

Img not fading out jQuery

I'm having some trouble with this JS / Jquery script, it was working completely yesterday, but today, it just wont work properly.
The loading .gif fades in, but just wont fade out...
This is my HTML
...
<div class="banner">
<img src="img/selosiade.png"/><br />
<form>
<input id="username" class="login" type="text" name="username" autocapitalize="off" placeholder="Nome de Usuário"><br />
<input id="password" class="login" type="password" name"password" autocapitalize="off" placeholder="Senha"><br />
<input type="button" value="Login" onClick="login.db();">
<img id="loading" src="img/loading.gif" />
...
(All tags are properly closed)
This what is set to the #loading id.
#loading{
display:none;
z-index:999;
margin-top:5px;
margin-left:50px;
position:absolute;
}
And this is the login.db() script:
var login = {
db: function () {
$('#loading').fadeIn(800, function () {
if (($('#username').val().length === 0) && ($('#password').val().length === 0)) {
$('#user_pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#username').val().length === 0) {
$('#user_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#password').val().length === 0) {
$('#pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
}
var pass1 = $('#password').val();
var pass = CryptoJS.SHA1(pass1);
var user = $('#username').val();
var flag = false;
$.ajax({
url: "http://apt-ghaschel.webatu.com/php/check.php",
type: "POST",
async: false,
data: {
user: user,
pass: pass
},
success: function (msg) {
var b = msg.match(/^.*$/m)[0];
$('#store').text(b);
flag = true;
}
});
if (flag) {
return;
}
b = $('#store').text();
if (b == '1') {
$('#login_certo').fadeIn(800).delay(800).fadeOut(800, function () {
$('div.banner').fadeOut(800, function () {
var encrypted = CryptoJS.AES.encrypt(pass, a);
$.cookie('username', user, {
expires: 365
});
$.cookie('username', encrypted, {
expires: 365
});
window.open("unidades.html?username=" + user + "");
});
});
} else if (b == '2') {
$('#login_errado').fadeIn(800).delay(800).fadeOut(800, function () {});
} else {
$('#erro_desconhecido').fadeIn(800).delay(800).fadeOut(800);
}
});
}
}
Sorry if this is something silly, but I just can figure it out what is wrong.
check whether this will help you, use
$("#loading").stop().fadeOut(800);
instead of
$("#loading").delay(800).fadeOut(800);
The fade out works properly when I disable CryptoJS in your fiddle.
By the way, the login-form div doesn't fade in at the start. I suggest you to use
$(document).ready(function() {
pisca.telalogin();
});

Categories

Resources