管理用户会话与状态
学习如何监控用户身份验证状态、持久化会话,并安全地管理用户资料
管理用户会话与状态 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Firebase Auth & Realtime Database Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
User Sessions & States Intro
Welcome! In this lesson, we'll dive into managing user sessions and understanding authentication states in Firebase. These are crucial for building secure and user-friendly apps.
We'll cover how to:
- Monitor when a user logs in or out.
- Keep users logged in across app restarts.
- Update user profile information.
Tracking User Status
Firebase Authentication provides a powerful way to monitor a user's login status in real-time. This is done using an "authentication state listener."
- It tells your app if a user is currently logged in or logged out.
- It fires whenever the user's authentication state changes (e.g., login, logout, token refresh).
- This is perfect for updating UI elements or redirecting users.
Live Auth State Listener
Here's how you set up an authentication state listener. It's a key part of making your app react to user logins and logouts.
This example assumes Firebase is initialized and the auth service is available.
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
// This function will be called whenever the auth state changes
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in
console.log("User logged in:", user.email);
// You can access user.uid, user.displayName, etc.
} else {
// User is signed out
console.log("No user logged in.");
}
});
console.log("Auth state listener set up.");Session Persistence Explained
Imagine your user logs in, closes the app, and reopens it only to find they're logged out. Frustrating, right?
Firebase Auth solves this with "session persistence." It allows you to specify how long a user's login session should last, even after they close their browser or app.
- Firebase stores user credentials securely.
- It automatically re-authenticates the user when they return.
Choosing Persistence Options
Firebase offers different levels of session persistence to suit various application needs:
LOCAL: The user's session is persisted even if the browser window is closed. (Default for web)SESSION: The session is persisted only for the current browser session. It's cleared when the window is closed.NONE: No session persistence. The user is logged out when the page is refreshed or the app restarts.
Customizing Session Persistence
You can set the desired persistence level before a user signs in. This tells Firebase how to handle the session for that specific login.
Here's an example of setting it to SESSION for a temporary login.
import { getAuth, setPersistence, browserSessionPersistence } from "firebase/auth";
const auth = getAuth();
// Set persistence to SESSION
setPersistence(auth, browserSessionPersistence)
.then(() => {
console.log("Persistence set to SESSION.");
// Now you can sign in your user
// signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
console.error("Error setting persistence:", error.message);
});
console.log("Attempting to set persistence...");Accessing User Info
Once a user is logged in, you often need to access their information like their ID, email, or display name. Firebase makes this easy.
- The
currentUserproperty of theauthobject holds the currently logged-in user. - It will be
nullif no user is logged in. - Important: Always check
currentUserinside anonAuthStateChangedlistener to ensure it's up-to-date.
Managing User Profiles
Firebase Auth allows users to update basic profile information directly. This includes their display name and profile photo URL.
These updates are client-side and don't require re-authentication for the user to see the changes in their own profile object.
- Use the
updateProfilemethod on the user object. - Common updates:
displayNameandphotoURL.
Changing Display Name
Let's see how to update a user's display name. This is useful for personalizing their experience in your app.
This operation requires a logged-in user.
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser; // Get the current user
if (user) {
updateProfile(user, {
displayName: "Jane Doe",
// photoURL: "https://example.com/jane-profile.jpg"
}).then(() => {
console.log("Profile updated successfully!");
console.log("New display name:", user.displayName);
}).catch((error) => {
console.error("Error updating profile:", error.message);
});
} else {
console.log("No user is logged in to update profile.");
}
console.log("Attempting to update user profile...");Quick Check: Auth State
Consider a web application using Firebase Authentication. A user logs in, then closes their browser and reopens it a few minutes later. They find themselves still logged in.
Which Firebase Auth persistence setting was most likely active?
Recap: Sessions & States
Great job! In this lesson, you learned how to effectively manage user sessions and states in your Firebase application.
- We explored
onAuthStateChangedfor real-time user status monitoring. - You understood the importance of session persistence and its different levels (
LOCAL,SESSION,NONE). - Finally, you learned how to access and update a logged-in user's profile information.
These skills are fundamental for building dynamic and personalized user experiences!
用 AI 导师学习 Firebase Auth & Realtime Database Apps — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 11
- 课程
- 44
常见问题解答
「管理用户会话与状态」课时是免费的吗?
是的 — 「管理用户会话与状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。
「管理用户会话与状态」这节课中我会学到什么?
学习如何监控用户身份验证状态、持久化会话,并安全地管理用户资料 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Firebase Auth & Realtime Database Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「管理用户会话与状态」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?
能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 实现电子邮件/密码身份验证
- 管理用户会话与状态
- 处理身份验证错误
- 密码重置与电子邮件验证