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

如何通过MongoDB Realm Web SDK检查邮箱密码认证用户是否已登录

实现登录状态检查与UI切换

嘿,很高兴你已经搞定了邮箱密码的注册和登录核心功能!接下来要实现的「根据登录状态自动切换登录页/登出按钮」其实很直接,主要靠Realm SDK提供的用户状态相关API就能完成,我给你一步步拆解具体实现:

1. 页面初始化时检查登录状态

页面加载完成后,首先可以通过app.currentUser快速判断用户是否处于登录状态——这个属性会返回当前已认证的用户实例,若为null则说明用户未登录或会话已失效。为了确保状态准确,建议顺便刷新一下用户会话:

// 假设你已经初始化了Realm App实例
const app = new Realm.App({ id: "你的App ID" });

// 页面加载时检查登录状态
async function checkAuthStatus() {
  if (app.currentUser) {
    try {
      // 刷新用户会话,避免token过期导致的状态不一致
      await app.currentUser.refreshCustomData();
      // 切换到已登录UI:隐藏登录页,显示登出按钮
      showLoggedInUI();
    } catch (error) {
      // 会话失效,重置为未登录状态
      console.error("用户会话已过期", error);
      showLoginUI();
    }
  } else {
    // 无登录用户,显示登录页面
    showLoginUI();
  }
}

// 页面加载完成后执行检查
document.addEventListener("DOMContentLoaded", checkAuthStatus);

2. 监听用户状态变化事件

除了初始化检查,还要监听用户的登录/登出事件——这样用户在当前页面操作登录、登出,或者在其他标签页完成登录后,UI能自动同步更新:

// 监听登录成功事件
app.addListener("login", () => {
  console.log("用户已成功登录");
  showLoggedInUI();
});

// 监听登出事件
app.addListener("logout", () => {
  console.log("用户已登出");
  showLoginUI();
});

3. 实现登出功能

既然要显示登出按钮,就得配套写好登出函数:

async function logoutUser() {
  if (app.currentUser) {
    try {
      await app.currentUser.logOut();
      // 登出后Realm会自动触发logout事件,无需手动切换UI
    } catch (error) {
      console.error("登出失败", error);
    }
  }
}

4. 整合到你已有的代码中

你已经完成了注册和登录函数,可以在注册成功后自动帮用户登录(可选),并且确保登录成功后UI能正确响应:

async function registerEmailPassword(email, password) {
  try {
    const user = await app.emailPasswordAuth.registerUser({ email, password });
    // 注册成功后自动登录(可选逻辑,根据你的业务需求调整)
    await app.logIn(Realm.Credentials.emailPassword(email, password));
    return user;
  } catch (error) {
    console.error("Failed to register", error);
  }
}

async function loginEmailPassword(email, password) {
  const credentials = Realm.Credentials.emailPassword(email, password);
  try {
    const user = await app.logIn(credentials);
    console.assert(user.id === app.currentUser.id);
    return user;
  } catch (error) {
    console.error("Failed to log in", error);
  }
}

5. 简单的UI切换示例

最后,你需要实现两个控制UI显示隐藏的函数,比如:

function showLoginUI() {
  // 隐藏登出按钮,显示登录/注册表单
  document.getElementById("logout-btn").style.display = "none";
  document.getElementById("login-register-container").style.display = "block";
}

function showLoggedInUI() {
  // 显示登出按钮,隐藏登录/注册表单
  document.getElementById("logout-btn").style.display = "block";
  document.getElementById("login-register-container").style.display = "none";
  // 可选:显示用户邮箱等信息
  document.getElementById("user-info").textContent = `当前登录:${app.currentUser.profile.email}`;
}

这样一套流程下来,就能完美实现「根据用户登录状态自动切换页面内容」的需求啦!

内容的提问来源于stack exchange,提问作者The Little Cousin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:50:16