Unlocking route access through server-side Firebase authentication

I have integrated sessionStorage and firebase authentication for user email and password in my project.

Currently, I am facing an issue in my server.js where I need to prevent access to a route if the user is not logged in, and instead redirect them to the login route. The challenge is that the firebase SDK I am using can only be used on the client side. I have been unable to find any documentation that could help me with this problem.

If more clarification is needed regarding my question, please let me know and I will provide it.

This is a snippet from my server.js file:

const express = require('express');
const admin = require('firebase-admin');
const bcrypt = require('bcrypt');
const path = require('path');

let serviceAccount = require("./1234.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

let staticPath = path.join(__dirname,"public");

const app = express();

app.use(express.static(staticPath));
app.use(express.json());

    app.get('/login', (req,res) => {
        res.sendFile(path.join(staticPath, "form.html"));
    })
    
    app.get('/seller', (req,res) => {
    // if(!user) res.redirect('/login');
        res.sendFile(path.join(staticPath, "seller.html"));
    })

Update: I have tried creating a seller.js file to handle this issue, but I am unsure about its security or if there is a way to prevent it from being tampered with:

body = document.getElementsByTagName('BODY')[0];
user = JSON.parse(sessionStorage.user);
if(user && user.seller){
    console.log('Allow Access')
} else{
    console.log('Deny')
    body.innerHTML = `
    <div class="sticky" id="nav"></div>
    <div style="padding:300px">
    <center>You do not have permission to view this page.</center>
    </div>
    <div id="footer"></div>
    `;

}

Answer №1

Utilize the firebase-admin package for token verification on the server side. Once the token is verified, proceed with route logic. To streamline the process, consider implementing a middleware in Express to handle token verification for authenticated routes.

For more information, refer to: https://firebase.google.com/docs/auth/admin/verify-id-tokens#web

Avoid depending solely on client-side scripts for user authentication validation when restricting access to server resources. Without server-side authentication logic, unauthorized individuals could exploit endpoints and potentially access sensitive data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

The Conundrum of Material UI Picker and date-fns Compatibility

I'm facing an issue with the material-ui-pickers example in my React application using Material UI. Here is the online example provided by Material UI: https://codesandbox.io/s/52p74362pl The error message I'm encountering is: index.js:1446 .. ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

Executing PHP Code following a JavaScript Confirmation Box: Best Practices

How can I run the following code in PHP? var answer = window.confirm("Do you want to overwrite the file..."); Based on the user's selection of "OK" or "CANCEL"; If the user chooses "OK", I need to execute the following PHP code without using AJAX. ...

The functionality of if and else statements within local storage is not functioning as

I've been working on implementing a styleswitcher for my website. I successfully created a dropdown menu and saved it in localstorage. However, I'm facing an issue when trying to use the localstorage information to trigger an alert() through if a ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

How can I remove unnecessary components from an API result in discord.js before sending it?

The particular API being discussed is a pun-themed one, specifically this one. Here is the code snippet I am currently utilizing: const superagent = require("superagent") module.exports = { run: async(client, message, args) => { const pun = a ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Combining Asynchronous and Synchronous Operations in a Function: Using Cache and Ajax Requests in JavaScript

I am currently exploring how to combine two different types of returns (async / sync) from a function that is structured like this : retrieveVideo(itemID){ let data = localStorage.getItem(itemID) if ( data ) { return data; } else{ axios.ge ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Store image selection in state

I am currently working on building an imagePicker in ReactNative, but I am running into an issue when trying to select the image. The error message I am receiving is: TypeError: this.setState is not a function. (In 'this.setState ({ avatar: data}) &a ...

How do I change the 'CSS Theme' of my website?

With Halloween approaching, I am eager to transform my website's BODY css into a spooky Halloween theme. The challenge is that my .Net pages are Templates. Is there a way for me to ensure that the body class checks for an existing CSS theme override? ...

Emit data asynchronously upon returning

In my node.js application, I have a background process implemented using the EventEmitter. Here is a snippet of how it is used: var event = { returnValue: undefined }; eventEmitter.emit('name', event, argument); return event.returnValue; // This ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...

Automatically forward to m.example.com on mobile devices using nodejs

Is there a way to create a subdomain in Node.js, such as m.example.com, and have it redirect to m.example.com on mobile devices? I've searched for answers but haven't found a satisfactory solution. One suggestion is to use nginx in front of Node, ...

Having trouble retrieving the desired information within the JSON format. What exactly is the discrepancy between the two sets of data?

I've researched extensively on similar issues but have not been able to find a solution. My goal is to retrieve the name and value of a coin. The Coinmarketcap API has 2 endpoints. The first endpoint, as indicated in the comment, provides the desired ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

The error of "Uncaught ReferenceError" is being triggered by the use of `process?.env?

A bug was discovered in our front-end code related to the following snippet: <span style={{ color: 'red' }}>{process?.env?.REACT_APP_HEADER_SUFFIX ?? ''}</span> The bug triggered the following error message: Uncaught Refere ...