LocalStorage for React Login Screen with reCaptcha - javascript

Hello everyone i try to use localStorage when user try to login my website if he/she try more than 2 times reCaptcha appear only way is click checkbox in reCaptcha but if user refresh the page reCaptcha is gone because of my state attempNumber. I want to keep attempNumber in localStorage and use firstly localStorage if user try more than 2 , when refresh page , reCaptche should be there .
I tried like that, but it is not working.If you help me i will be so appreciate for that . Thank you everyone .
this.state = {
email: '',
password: '',
load: false,
attempCount: 0,
};
handleLogin(e) {
const {
email, password, recaptcha,
} = this.state;
const cachedHits = localStorage.getItem(this.state.attempCount);
if (cachedHits) {
this.setState({ attempCount: JSON.parse(cachedHits) });
return;
}
this.setState({ attempCount: this.state.attempCount + 1 });
e.preventDefault();
e.stopPropagation();
this.props.doSignIn({ email, password, recaptcha });
return false;
}

well, code you have added doesn't show how and where you are setting value in localStorage.
I assume you will update localstorage in login button click event something like this
localStorage.setItem('clickCount', this.state.attempCount );
assuming your this.state.attempCount is incremented by 1 on click
Now to get its value use
let count = localStorage.getItem('clickCount');
if(count > 2){
// show Captcha
}

Without seeing your doSignIn code it is hard to tell what is happening with your localStorage, but your call to localStorage in the code you pasted is passing your attemptCount as the key. You should use a string as the key such as 'attemptCount' rather than a key that will change with your state changes.
That might not be all your problem, but is what I noticed so far.

I guess you're trying to get the value under key 0 if you take a look at the documentation here. Try to save it under a key you now as localStorage.setItem('attempts', this.state.attempCount) and then localStorage.getItem('attempts').
When you do a getItem I believe it will return a string, so do a parse parseInt(localStorage.getItem('attempts'), 10) before using it for any operation.
There are two issues with the code:
value is never beign set in localstorage.
First time when handleLogin is called, below line
const cachedHits = localStorage.getItem(0);
it tries to fetch value for zero which is never stored in local storage and it returns null(i.e cachedHits= null),
then it skips the if part and sets attempCount in state to 1 and show captcha.
next time when handleLogin is called,
const cachedHits = localStorage.getItem(1); which is again not present in cache and cachedHits= null and so on...
so, you need to set value in localStorage against some key like and in getItem use that key

Related

how to save state of the page when refreshing? (HTML, JS)

(DISCLAIMER: I'm new to coding so my code probably isn't optimal. If you know a better way to do it, feel free to leave it in the comments )
Most of the time I had no idea what I was doing, but with patience and with you guys' help I came up with this:
if (window.localStorage) {
// Create the Key/Value
var cNum = localStorage.getItem("currentNumber");
if (localStorage.currentNumber == undefined) {
localStorage.setItem("currentNumber","0");}
// Variables
resetCount.innerHTML = localStorage.currentNumber;
// Functions
function btnR() {
cNum++;
localStorage.currentNumber = cNum;
resetCount.innerHTML = cNum;}}
else { console.log("No"); }
HTML:
<button id="resetButton" onclick="btnR()">Reset</button>
<p id="resetCount">0</p>
I was creating a button that each time you click on it, it reset the checkboxes, but I also wanted a counter to see how many times they got rested. The problem was that every time I click the button the counter also reset. Now that is solved I can try to apply the same thing for the checkboxes, so they don't reset on refresh either.
Note: I had to put the .SetItem in an if statement cause, even tho the value was in storage it kept setting back the value to zero every time I refreshed the page. This was the way I found to stop that.
You either need to set up a back end to send data to and save the information you want to keep stored, or save data in localStorage.
Just know it is not the best practice to save sensitive info in localStorage (as they can be compromised in cross-site scripting attacks).
localStorage.setItem puts a bit of data into localStorage (and that stays there till you clear it) and localStorage.getData extracts it.
This might help get you started on localStorage, but you will have to figure out the function to set the colour to the element you have.
let boxColour = localStorage.getItem("boxColour");
if (boxColour === null) {
setBoxColour("colour");
} else {
setBoxColour(boxColour);
}
function setBoxColour(colour){ localStorage.setItem("colour");}
/* Inside the function you have to get the item and change it's style attribute or add a class to add styles */
Careful with that localStorage data!
You could use LocalStorage.
It saves data in the page to be used after when the page is refreshed or closed and opened later.
Theres a example:
(Unfortunally, it seems to not work in the stackoverflow site, but if you try at your HTML file it will work)
var loadFunc = (elem) => {
console.log("Value saved is: "+ localStorage.getItem("savedValue"));
if(localStorage.getItem("savedValue")){ //checks if value is saved or not
elem.checked = localStorage.getItem("savedValue");
}
}
var clickFunc = (elem) => {
localStorage.setItem("savedValue", elem.checked); //set te value if in localStorage
}
Click the checkbox and the value will be saved.
<input type="checkbox" onload="loadFunc(this)" onclick="clickFunc(this)">

I was wondering if someone could teach me how to use cookies in my code

I'm trying to make a "Window.alert game" in a browser window for fun, but I can't figure out how to use cookies to save player data if they mess up or close the window. Can someone help me?
LocalStorage is indeed your best option for saving data semi-permanently. One thing to remember is that localStorage only supports strings, so if you need to store more complex objects, you should JSON.stringify them (and JSON.parse the result when loading data).
A simple pattern is to use a single object to store your state, and to save this state to localStorage whenever a change is made to it (so that your latest data is always persisted). You can also listen to the window.beforeUnload method to save your state right before the window closes, but this may not always work (eg: if your browser or tab closes unexpectedly).
Here is an example of what you can do:
// saves your state to localStorage
function save(state) {
localStorage.setItem('state', JSON.stringify(state));
}
// execute code when the document is loaded
document.addEventListener('DOMContentLoaded', function () {
// load your state from localStorage if it has been previously saved
// otherwise, set the state to an empty object
var state = JSON.parse(localStorage.getItem('state')) || {};
// show your name if previously saved
// otherwise, prompt for a name and save it
if (state.name) {
alert('Your name is: ' + state.name);
} else {
state.name = prompt('What is your name?');
save(state);
}
});
To clear localStorage, you can call localStorage.clear().

Getting Last Active URL Prior to Logout in Angular 2 App

In my Angular 2 app I am trying to store the last active URL prior to a user logging out, so that that url can be re-loaded after the user re-logs in. However, this is proving problematic. Consider this logout function from my authenticationService:
logout()
{
let lastUrl = this.getActiveUrl();
console.log('Url before logout: ', lastUrl);
this.apiService.logout();
}
Notice here that "lastUrl", which calls this.getActiveUrl(), which looks like this:
getActiveUrl()
{
let activeUrl = this.router.routerState.snapshot['url'];
console.log('activeUrl: ', activeUrl);
return activeUrl;
}
...appears BEFORE this.apiService.logout(). But, nevertheless, what gets printed to the console for "lastUrl" is "/login". But that's the URL where I end up immediately after logging out.
So, help me understand this:
If this is synchronous, why doesn't the correct URL print here? What am I missing? And how can I get the active url immediately prior to logout firing and re-directing to '/login'?
EDIT: After a commenter's suggestion, I tried assigning to localStorage instead of a local variable, like so:
logout()
{
localStorage.setItem('returnUrl', JSON.stringify(this.router.routerState.snapshot['url']));
this.apiService.logout();
}
But when I dig that value out with localStorage.returnUrl, I still get "/login".
First off, many thanks to #Sam for the localStorage suggestion. I should have thought of that. So, in the end, all I needed to do was make use of RouterStateSnapshot from my canActivate() function in my AuthGuardService, and save that value to localStorage. Then I just retrieve that value to plugin in on re-authentication and re-login:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
{
// Get route content id
let contentId = Object.getPropertyValueAtPath(route, 'data.contentId');
// Store last active URL prior to logout, so user can be redirected on re-login
localStorage.setItem('returnUrl', JSON.stringify(state.url));
// DO OTHER STUFF...
}
In my login component I just get that value to pass in...
login(response)
{
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password, function (results)
{
if (results.data && results.ok === true)
{
this.returnUrl = JSON.parse(localStorage.getItem('returnUrl'));
this.router.navigate([this.returnUrl || '/']);
console.log('ReturnURL Value is: ', this.returnUrl);
this.reset();
}
else
{
this.alertService.error(null, response);
this.loading = false;
}
}.bind(this));
}
It is happening synchronously. However, you are logging an object pointer. By the time you look at the object in the console, it has changed because the route has changed.
I suggest using local storage to store the router snapshot. This will not have the same pointer issue that you see in the console.

ExtJS 5.1 Remember Me on local store

I'm trying to do Remember Me with an interesting algorithm. I was thinking, when i click the Remember Me and Login, the value of the text fields (username&password) will be saved as a default value. My login button click event here:
var username = Ext.getCmp('setNo').getValue();
var password= Ext.getCmp('setPass').getValue();
if(refs.checkStudent.value === true){
Ext.getCmp('setNo').setValue(username);
Ext.getCmp('setPass').setValue(password);
}
else{
Ext.getCmp('setNo').setValue("");
Ext.getCmp('setParola').setValue("");
}
On console, it is working. But I'm working with a local store, no server. So when i refresh the page, it's gone. Is there a way to not lose them?
on your view onAfterRender event:
Ext.getCmp('setNo').setValue(localStorage.username);
Ext.getCmp('setPass').setValue(localStorage.password);
on your button click event:
if (refs.checkStudent.value === true) {
localStorage.username = Ext.getCmp('setNo').getValue();
localStorage.password = Ext.getCmp('setPass').getValue();
} else {
localStorage.removeItem('username');
localStorage.removeItem('password');
}
Use ExtJs utility to set and get values in cookies. At time of login set
username and password in cookies and after refresh the page read username
and password value from the cookie.
Ext.util.Cookies.set('username', username); // To set value in cookie.
Ext.util.Cookies.get('username'); // to get value form cookie.

create and store user objects using localstorage

I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('user')).name);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!
I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:
function getNextUnique () {
var next = localStorage.getItem('nextUniqueId');
next = next ? parseInt(next) : 0;
var newNext = next + 1;
localStorage.setItem('nextUniqueId', newNext);
return next;
}
Call it whenever you want to save a new user:
localStorage.setItem(getNextUnique(), JSON.stringify(user));
It makes more sense to use the user's email. Simplicity is good.
BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?
If so, then this is fine. But i wonder if you are really thinking about how localStorage works...

Categories

Resources