Simple form submission with Firebase; can I detect when offline? - javascript

I'm using Firebase perhaps slightly unconventionally -for simple form submission. Submission of my website's contact form simply results in:
ref.push({name:'dr foo', email:'1#2.com', message:'bar'}, myCallback);
The Firebase is hooked up to Zapier to send the site owner an email. All works well, but I'd like to be able to handle the user loosing their connection. When Firebase can't reach the server I'd like to display: "Please check your connection", or a similar message when the user hits the send button. The "Thanks, we'll be in touch"-type message should only be displayed on a successful write.
At first I tried including an if (error) branch in the callback, but of course disconnection is not something that Firebase considers an error as it "catches up" when it can.
I also tried the code in the docs which monitors .info/connected. While this wouldn't display a message on a form submission attempt, I was thinking I could instead display a warning if disconnected. The sample worked intermittently (Chrome 39, Firefox 30, Linux Mint), but the lag between disconnection and the event firing means it's probably not suitable for this case.
Is what I'm trying to do possible?

It indeed seems that the .info/connected values only changes once some other data transfer occurs (and fails).
The only way I can come up with is by using the transaction mechanism with applyLocally set to false. E.g.
function testOnlineStatus() {
var ref = new Firebase('https://your.firebaseio.com/');
ref.child('globalcounter').transaction(function(count) {
return (count || 0) + 1;
}, function(error, committed, snapshot) {
if (error) {
alert('Are you offline?');
}
}, false /* force roundtrip to server */);
}
setInterval(testOnlineStatus, 2000);
This one triggered for me after about 15 seconds.

Related

React : Handle multiple browser(s), browser tabs to restrict duplicate operations

I have a button Submit when clicked performs some operation calling an API. Post click, the button is disabled or basically the initial state of the button and the operation is changed.
I have two or multiple browser tabs which shows same screen of Submit. If in any one of the tab, the Submit operation is performed, the other tabs should show the updated version. The other tabs should show the disabled version and should not show the initial state.
How do I achieve this? I am using React, JS
#1 Data duplication MUST be restricted at the server side.
I would recommend some cache like node-cache. Node-cache will having scalability issues, so better to go with redis. (The logic should be smt. like: If the form has submited with the user_id, or with form_id, you can create a cache for that, and if you proceed it, store it in the db, other case throws an error. On the other browser you must validate before the submit if the unique_id neither in the cache nor in the db. If exists, you can throws an error in the nr.2 browser.
#2 If you want to disable the button, you have to use websockets
If you're looking for a client-only solution, here is a great article about sharing state between browser tabs. The limitation is that it won't work on different browsers/machines.
The best way to handle this from a UI/UX perspective is to use validation. If User A clicks submit, then User B clicks submit from a different browser or tab, an error should be displayed to User B indicating that "This action has already taken place".
That being said, what you are trying to achieve is possible.
One way is by using a WebSocket. A WebSocket is a persistent connection between the client and server, that allows bi-directional communication.
The page with the submit button in your React app would be a "subscriber" to some websocket channel. When the submit button is clicked for the first time(it doesn't matter from where), a message can be "published" from a WebSocket server to ALL subscribers, regardless of the browser or tab being used.
Basically, you would add an onMessage handler in your React app where you can disable the submit button when a specific message is received.
I don't know what tech you are using on the server side, but for a WebSocket server, there are many options out there. For the React app, there is react-websocket which is straight-forward to use.
you can do it in client-side
const Form = () => {
const [buttonDisabled, setButtonDisable] = useState(false);
// first tab fire
const onSubmit = () => {
.
.
.
localStorage.setItem("formSubmited", "true");
};
useEffect(() => {
const disableButton = (e) => {
if (e.storageArea.formSubmited) {
setButtonDisable(true);
}
};
// second tab fire
window.addEventListener("storage", disableButton);
return () => {
window.removeEventListener("storage", disableButton);
};
}, []);
.
.
.
};

Cypress - Check a user logs in successfully or fails

In my Cypress code, I want to decide action based upon the response from the backend. Please note, I am not mocking a server, rather wanting to hit & get response from API server & base next commands off the response.
cy.visit("http://localhost:3000/login");
cy.get(".cookieConsent button").click();
cy.get("#email-input").type(userLoginDetail.email);
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.wait(3000);
// logic being it user is redirected to homepage, then login was successful. Not happy with this O(
if (cy.url() === "http://localhost:3000/") {
console.log("eeeeeeeeeee");
} else {
console.log(
"aaaaaaaaaaaaaaaaaaa ");
How can I check the response from the form submission & use if condition based off that.
I think the problem is, that you want to do conditional testing. Using cy.wait() is bad practice and is even mentioned in the docs itself.
Anti-Pattern
You almost never need to wait for an arbitrary period of
time. There are always better ways to express this in Cypress.
You should not execute different actions upon response. In cypress testing it is expected, that you know the result of your action beforehand.
If user enters invalid email, you might expect form submisson to fail and an error to be displayed.
cy.get("#email-input").type('invalid_email.com');
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.get(".email-error").should('be.visible');
In this case cypress will check them DOM until it finds the error or hits the defaultCommandTimeout from cypress config.
On the other hand, if you want to check if user is redirected correclty, you can simply check for a div on the success/redirected page.
cy.get("#email-input").type('valid#email.com');
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.get(".success-page").should('be.visible');
However, if you still decide to execute an action depending on the servers response, cypress enables you to declaratively cy.wait() for requests and their responses.
cy.server()
cy.route({
method: 'POST',
url: '/myApi',
}).as('apiCheck')
cy.visit('/')
cy.wait('#apiCheck').then((xhr) => {
assert.isNotNull(xhr.response.body.data, 'api call successfull')
})

Firebase custom claim how to set?

I'm struggling with firebase custom claims.
I have tested a lot of approaches nothing works. Obviously, I miss something important in the concept itself.
So I'm back to the root. This script from the google example should apply customs rule on a newly created user
exports.processSignUp = functions.auth.user().onCreate(event => {
const user = event.data; // The Firebase user.
const customClaims = {
param: true,
accessLevel: 9
};
// Set custom user claims on this newly created user.
return admin.auth().setCustomUserClaims(user.uid, customClaims)
});
Then on a client, I check the result with
firebase.auth().currentUser.getIdTokenResult()
.then((idTokenResult) => {
// Confirm the user is an Admin.
console.log(idTokenResult.claims)
if (!!idTokenResult.claims.param) {
// Show admin UI.
console.log("param")
} else {
// Show regular user UI.
console.log("no param")
}
})
.catch((error) => {
console.log(error);
});
Everything just a raw copy-paste still doesn't work. I've tested both from the local machine(there could be troubles with cors?) and deployed
This is a race situation. If the Function end first then, you will get the updated data.
The getIdTokenResult method does force refresh but if the custom claim is not ready then, it is pointless.
You need to set another data control structure to trigger the force refresh on the client. By example a real-time listener to the rtd;
root.child(`permissions/${uid}`).on..
And the logic inside the listener would be: if the value for that node exists and is a number greater than some threshold, then trigger the user auth refresh
During that time the ui can reflect a loading state if there is no datasnapshot or the not admin view if the datasnapshot exists but is a lower permission level.
In Functions you have to set the node after the claim is set:
..setCustomUserClaims(..).then(
ref.setValue(9)
);
I have a more detailed example on pastebin
The claims on the client are populated when the client gets an ID token from the server. The ID token is valid for an hour, after which the SDK automatically refreshes it.
By the time the Cloud Functions auth.user().onCreate gets called, the client has already gotten the ID token for the new user. This means that it can take up to an hour before the client sees the updated claims.
If you want the client to get the custom claims before that, you can force it to refresh the token. But in this video our security experts recommend (that you consider) using a different storage mechanism for claims that you want to be applied straight away.

Java script, PHP

I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code
<script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
location.href = 'Logout.php';
}
function pageHidden(evt){
if (str==='delete')
logout();
}
window.addEventListener("pagehide", pageHidden, false);
</script >
Examples I tried....
// 1st approach
//window.addEventListener("beforeunload", function (e) {
/// var confirmationMessage = "Do you want to leave?";
// (e || window.event).returnValue = confirmationMessage;
// return confirmationMessage;
// });
// 2nd approach
// window.onbeforeunload = myUnloadEvent;
// function myUnloadEvent() {
// console.log("Do your actions in here")
// }
// 3rd approach
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....
Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.
You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:
session_set_cookie_params(0);
session_start();
session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.
Hope this helps! :)
The correct way to logout is related to how they are logged in.
In PHP, the login state is typically managed by sessions. By default the timeout is 24 minutes of inactivity, but you can easily reduce it.
When a user logs out, you typically reset one or more session variables, and, while you’re at it, kill off the current session, and delete the session cookie.
However, you cannot rely on a user to log out, and many typically just wander off. This is why there is always a relatively short timeout on sessions.
If you want to automatically logout when the tab is closed, you will need JavaScript to intercept the process with window.onbeforeunload and then use Ajax to send the logout to the server.
As regards the database, you normally do not record the login state in the database. You may record the login time, and if you like, the logout time, but remember that may be never.

Meteor log out do not sync between tabs

I am using Meteor with React and is facing a problem on log out function. When I open more than 2 tabs on the same browser, If I logged out from one tab then the other opening tabs would not be logged out but will be hang if I using it. There are only 2 ways to log out: close the tab or refresh it.
I try the same for log in function and it worked, log in status is synced between all opening tabs.
My current code to call the log out function:
signOut: function(event) {
event.preventDefault();
Meteor.logout();
this.props.history.pushState(null, "/");
},
Thank for the helps.
Update:
I checked the websocket, it's seem that the server did send the logout status but my client code did not call the logout method (or it is hang). Then every data in the hang tab is still existing. But I don't know how to check further more.
I found the cause. It was because I try to avoid sending data on Meteor.publish() if users is not logged in. The problem is I do not return anything on that case.
My solution is return this.ready() when the user is not logged in like this:
Meteor.publish("myCollections", function (){
if (!this.userId) return this.ready();
return MyCollections.find({owner: this.userId});
});
From the meteor documentation, you can use Meteor.logoutOtherClients() before calling Meteor.logout().
Normal (as in non-incognito) browser tabs share the same session resume token. The Meteor server will update them all when the user status changes for the associated session.
It is possible to reactively track the login status using 2 reactive calls:
Meteor.userId() - return the user's id or null if no user is logged in.
Meteor.loggingIn() - returns true if the user is currently in the transient state of logging in and false otherwise.
The status may take a few seconds to update across tabs, but it will happen eventually. It is up to you to detect those changes and act upon them.
You can easily test this by running the following reactive code in the consoles of 2 open tabs connected to the same Meteor server:
Tracker.autorun(function() {
if (Meteor.loggingIn()) {
console.info('logging in');
} else if (Meteor.userId()) {
console.info('logged in');
} else {
console.info('logged out');
}
});
Try to log in and log out from one of the tab and watch the other follow along.
Using this technique, you could track the login state and change your application state and do something accordingly (e.g, redirect/render a different view or layout) when the login state changes.

Categories