You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase页面跳转后保持登录状态及用户信息更新问题

问题修复:登录状态跳转丢失+用户信息更新函数优化

问题描述

  1. 登录成功进入仪表盘后,跳转至其他页面时登录状态丢失。
  2. 需要编写基于当前登录用户的信息更新函数,现有代码存在逻辑问题。

提供的原代码(编辑资料JS)

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize variables
const auth = firebase.auth()

auth.onAuthStateChanged( auth,user => {
    var user = firebase.auth().currentUser;
    if (user) {
      alert("User active: ");

      // User is signed in.
      var email = user.email;
      var uid = user.uid;

      //Take user to a different or home page
      window.location.href ="editprofile.html?id=" + uid;
    
    } else {
      alert("No active user please signup or sign in.");

      window.location.href ="login.html?error";

    }
});

var studioName, email, password, firstName, lastName, address, country, state, city, zip, phoneNumber;

function updateStu() {

    //Get data
    studioName = document.getElementById("studioName").value;
    email = document.getElementById("email").value;
    password =  document.getElementById("password").value;
    firstName = document.getElementById("firstName").value;
    lastName = document.getElementById("lastName").value;
    address = document.getElementById("address").value;
    country = document.getElementById("country").value;
    state = document.getElementById("state").value;
    city = document.getElementById("city").value;
    zip = document.getElementById("zip").value;
    phoneNumber = document.getElementById("phoneNumber").value;

    console.log(studioName, firstName, email);

    firebase
    .database()
    .ref("/studiopick/studio/users" + studioName)
    .update({
        
    //studioName : studioName,
    firstName : firstName,
    lastName : lastName,
    email : email,
    password : password,
    address : address,
    country : country,
    state : state,
    city : city,
    zip : zip,
    phoneNumber : phoneNumber
    });

    document.getElementById("studioName").value ="";
    document.getElementById("email").value ="";
    document.getElementById("password").value ="";
    document.getElementById("firstName").value ="";
    document.getElementById("lastName").value ="";
    document.getElementById("address").value ="";
    document.getElementById("country").value ="";
    document.getElementById("state").value ="";
    document.getElementById("city").value ="";
    document.getElementById("zip").value ="";
    document.getElementById("phoneNumber").value ="";

    alert("Data Updated");
};

问题分析与修复

1. 登录状态跳转后丢失的修复

原代码问题:

  • auth.onAuthStateChanged参数错误,回调函数仅需接收user参数,无需传入auth。
  • 页面加载时强制跳转editprofile.html,逻辑错误,应仅在未登录时跳转登录页,已登录时保留当前页面并执行对应初始化逻辑。
  • 其他页面未添加登录状态监听,导致跳转后无法识别用户登录状态。

修复后的登录状态监听代码:

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();

// 监听登录状态变化
auth.onAuthStateChanged(user => {
    if (!user) {
        // 未登录时跳转登录页
        window.location.href = "login.html?error";
        return;
    }
    // 已登录时,执行当前页面初始化逻辑(如填充用户信息到表单)
    console.log("当前登录用户UID:", user.uid);
});

注意:所有需要保持登录状态的页面,都需添加上述Firebase初始化和登录状态监听代码,确保页面加载时能正确识别用户状态。

2. 用户信息更新函数的修复

原代码问题:

  • 用studioName作为数据库路径,未关联当前登录用户UID,无法确保更新的是当前用户信息,存在数据篡改风险。
  • 直接将密码写入实时数据库,Firebase Auth的用户密码需通过专属API更新,不能直接写入数据库。
  • 全局声明变量,存在变量污染风险。

修复后的更新函数:

function updateStu() {
    // 获取当前登录用户
    const user = auth.currentUser;
    if (!user) {
        alert("请先登录");
        window.location.href = "login.html";
        return;
    }

    // 获取表单数据(函数内声明变量,避免全局污染)
    const studioName = document.getElementById("studioName").value;
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;
    const firstName = document.getElementById("firstName").value;
    const lastName = document.getElementById("lastName").value;
    const address = document.getElementById("address").value;
    const country = document.getElementById("country").value;
    const state = document.getElementById("state").value;
    const city = document.getElementById("city").value;
    const zip = document.getElementById("zip").value;
    const phoneNumber = document.getElementById("phoneNumber").value;

    // 准备要更新的用户信息(排除密码,单独处理)
    const userData = {
        studioName,
        firstName,
        lastName,
        email,
        address,
        country,
        state,
        city,
        zip,
        phoneNumber
    };

    // 更新实时数据库中的用户信息(使用当前用户UID作为路径,确保唯一性)
    firebase.database()
        .ref(`/studiopick/studio/users/${user.uid}`)
        .update(userData)
        .then(() => {
            // 处理邮箱更新(如果有修改)
            if (email !== user.email) {
                return user.updateEmail(email);
            }
            return Promise.resolve();
        })
        .then(() => {
            // 处理密码更新(如果填写了新密码)
            if (password.trim()) {
                return user.updatePassword(password);
            }
            return Promise.resolve();
        })
        .then(() => {
            // 清空表单
            document.getElementById("studioName").value = "";
            document.getElementById("email").value = "";
            document.getElementById("password").value = "";
            document.getElementById("firstName").value = "";
            document.getElementById("lastName").value = "";
            document.getElementById("address").value = "";
            document.getElementById("country").value = "";
            document.getElementById("state").value = "";
            document.getElementById("city").value = "";
            document.getElementById("zip").value = "";
            document.getElementById("phoneNumber").value = "";
            alert("信息更新成功");
        })
        .catch(error => {
            alert(`更新失败:${error.message}`);
            console.error(error);
        });
}

关键优化点:

  • 使用当前登录用户的UID作为数据库路径,确保仅更新当前用户的信息。
  • 单独处理邮箱和密码的更新,遵循Firebase Auth的API规范。
  • 添加错误捕获,处理更新过程中可能出现的异常。
  • 变量改为函数内声明,避免全局变量污染。

内容的提问来源于stack exchange,提问作者user18694296

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:31:22