Home > Back-end >  Firebase how to get the current user
Firebase how to get the current user

Time:04-03

I use express js and firebase for user authorization. After registration, the user enters the profile.

How do I get the current account on the profile page and get its data? So that even after updating the page, you don't lose the current user?

I've read about onAuthStateChanged, but I don't understand how to use it in my code. (I wanted to in my profile.write js, but I don't understand how). Or get a token from cookies and receive it? Can I have an example?

server.js

const cookieParser = require("cookie-parser");
const csrf = require("csurf");
const bodyParser = require("body-parser");
const express = require("express");
const path = require('path');
const admin = require("firebase-admin"); // firebase администрирование

const serviceAccount = require("./public/serviceAccountKey.json"); // загружаем файл ключа

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://paradox-website-cd25b.firebaseapp.com",
});

const csrfMiddleware = csrf({ cookie: true });

let initial_path = path.join(__dirname, "public"); // директория работы
const app = express();

app.engine("html", require("ejs").renderFile);
app.use(express.static(initial_path)); // инициализация рабочей директории

app.use(bodyParser.json());
app.use(cookieParser());
app.use(csrfMiddleware);

app.all("*", (req, res, next) => {
  res.cookie("XSRF-TOKEN", req.csrfToken());
  next();
});

app.get('/login', (req, res) => {
  res.sendFile(path.join(initial_path, "login.html"));
})

app.get('/register', (req, res) => {
  res.sendFile(path.join(initial_path, "register.html"));
})

app.get('/signup', (req, res) => {
  res.sendFile(path.join(initial_path, "signup.html"));
})

app.get("/profile", function (req, res) {
  const sessionCookie = req.cookies.session || "";

  admin
    .auth()
    .verifySessionCookie(sessionCookie, true /** checkRevoked */)
    .then((userData) => {
      console.log("Logged in:", userData.email)
      res.sendFile(path.join(initial_path, "profile.html"));
    })
    .catch((error) => {
      res.redirect("/login");
    });
});

app.get('/', (req, res) => {
  res.sendFile(path.join(initial_path, "index.html"));
})

app.post("/sessionLogin", (req, res) => {
  const idToken = req.body.idToken.toString();

  const expiresIn = 60 * 60 * 24 * 5 * 1000; // вычисляем, сколько файл куки будет храниться (5 дней в миллисикундах)

  admin
    .auth()
    .createSessionCookie(idToken, { expiresIn }) // создаем файл куки со сроком хранения
    .then(
      (sessionCookie) => {
        const options = { maxAge: expiresIn, httpOnly: true };  // параметры (http only)
        res.cookie("session", sessionCookie, options); // файл с парамертрами
        res.end(JSON.stringify({ status: "success" }));
      },
      (error) => {
        res.status(401).send("UNAUTHORIZED REQUEST!");
      }
    );
});

app.post("/sessionRegister", (req, res) => {
  const idToken = req.body.idToken.toString();

  const expiresIn = 60 * 60 * 24 * 5 * 1000; // вычисляем, сколько файл куки будет храниться (5 дней в миллисикундах)

  admin
    .auth()
    .createSessionCookie(idToken, { expiresIn }) // создаем файл куки со сроком хранения
    .then(
      (sessionCookie) => {
        const options = { maxAge: expiresIn, httpOnly: true };  // параметры (http only)
        res.cookie("session", sessionCookie, options); // файл с парамертрами
        res.end(JSON.stringify({ status: "success" }));
      },
      (error) => {
        res.status(401).send("UNAUTHORIZED REQUEST!");
      }
    );
});

app.get("/sessionLogout", (req, res) => {
  res.clearCookie("session");
  res.redirect("/login");
});

app.listen("3000", () => {
    console.log('listening......');
})

public/js/firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";
import { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
let firebaseConfig = {
  // this my config
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export let db = getFirestore(app);

// Авторизация
const auth = getAuth();
setPersistence(auth, inMemoryPersistence)

public/js/register.js

import { getAuth, createUserWithEmailAndPassword, signOut, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js";

let auth = getAuth();
window.addEventListener("DOMContentLoaded", () => {

    document
      .getElementById("register")
      .addEventListener("submit", (event) => {
        event.preventDefault();
        const email = event.target.login.value;
        const password = event.target.password.value;

        console.log('Login: '   email   ' Password: '   password);

        
        createUserWithEmailAndPassword(auth, email, password)
        .then(({ user }) => {
            return user.getIdToken().then((idToken) => {
              return fetch("/sessionRegister", {
                method: "POST",
                headers: {
                  Accept: "application/json",
                  "Content-Type": "application/json",
                  "CSRF-Token": Cookies.get("XSRF-TOKEN"),
                },
                body: JSON.stringify({ idToken }),
              });
            });
          })
          .then(() => {
            signOut(auth).then(() => {
                window.location.assign("/profile");
              }).catch((error) => {
                console.log("Не удалось завершить сессию. Ошибка:"   error);
              });
          });

        return false;

      });

  });
  onAuthStateChanged(auth, user => {
    if (user) {
      console.log('Logged in as ${user.email}' );
    } else {
      console.log('No user');
    }
  });

CodePudding user response:

Firebase automatically persists the current user's credentials when they sign in, and tries to restore those credentials when the page/app is reloaded. To detect when that restore has completed, or other state changes, you'll want to use a so-called onAuthStateChanged listener as shown in the documentation on getting the currently signed-in user. From there:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});
  • Related