基于Firebase数据库实现Android智能锁应用的用户认证与管理
Hey Dave, great to hear you're building a smart lock controlled by an Android app! Since you already know how to handle email/password authentication with Firebase, let's walk through adding the rest of the features you need step by step.
First off, never store plaintext passwords—Firebase Auth already handles secure password storage and verification. We only need to save extra user details (name, email, UID) to either Firestore (recommended for flexible, scalable data) or Realtime Database.
Here’s how to sync user data right after creating an auth account (Kotlin example; Java is similar):
val auth = FirebaseAuth.getInstance() val firestore = FirebaseFirestore.getInstance() // When creating a new user auth.createUserWithEmailAndPassword(emailInput, passwordInput) .addOnCompleteListener { task -> if (task.isSuccessful) { val currentUser = auth.currentUser currentUser?.let { user -> // Create a map with user details val userData = hashMapOf( "name" to userNameInput, "email" to user.email, "uid" to user.uid ) // Write to Firestore collection "users" (create this in Firebase console first) firestore.collection("users") .document(user.uid) // Use UID as document ID for easy lookup .set(userData) .addOnSuccessListener { // Handle success (e.g., navigate to home screen) } .addOnFailureListener { e -> // Handle database write errors } } } else { // Handle auth creation errors (e.g., email already exists) } }
Once a user logs in, you’ll want to pull their stored details (like name) from the database to use in your app:
auth.signInWithEmailAndPassword(emailInput, passwordInput) .addOnCompleteListener { task -> if (task.isSuccessful) { val currentUser = auth.currentUser currentUser?.let { user -> // Fetch user details from Firestore firestore.collection("users") .document(user.uid) .get() .addOnSuccessListener { document -> if (document.exists()) { val userName = document.getString("name") val userEmail = document.getString("email") // Use these values to update your UI (e.g., welcome message) } } } } else { // Handle login failures (e.g., wrong password, user not found) } }
Before implementing these features, set up Firebase security rules to restrict access—only admin users should be able to view/edit all user data. For Firestore, add these rules in the Firebase console:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { // Allow admins to read/write; regular users can only access their own data allow read, write: if request.auth != null && request.auth.token.admin == true; allow read, write: if request.auth != null && request.auth.uid == userId; } } }
(You’ll need to mark admin users by adding an admin: true claim to their auth token—use Firebase Admin SDK or Cloud Functions for this.)
3.1 View All Registered Users
Query the entire users collection and display it in a RecyclerView:
// Fetch all users firestore.collection("users") .get() .addOnSuccessListener { querySnapshot -> val userList = mutableListOf<User>() for (document in querySnapshot) { // Map document to a User data class val user = document.toObject(User::class.java) userList.add(user) } // Bind userList to your RecyclerView adapter }
Create a simple User data class to model the data:
data class User( val name: String? = null, val email: String? = null, val uid: String? = null )
3.2 Update User Details
To update a user’s name or email, target their document and call update():
// Update a user's name (replace targetUserId with the user's UID) firestore.collection("users") .document(targetUserId) .update("name", updatedUserName) .addOnSuccessListener { // Show success message to the user } .addOnFailureListener { e -> // Handle update errors }
3.3 Delete a User
Deleting a user requires two steps: remove them from Firebase Auth, then delete their database document. For security, this is best handled via Firebase Admin SDK or Cloud Functions, but here’s a client-side example for admin users:
// First delete the auth user auth.getUser(targetUserId) .addOnSuccessListener { userToDelete -> userToDelete.delete() .addOnSuccessListener { // Then delete the Firestore document firestore.collection("users") .document(targetUserId) .delete() .addOnSuccessListener { // User fully deleted } } }
内容的提问来源于stack exchange,提问作者Dave Fetcher

