Imagine you're managing a large-scale application where users frequently require password resets, and admins need to handle these requests efficiently. One of the common challenges is allowing administrators to change the password of an authenticated user without needing email verification, especially when dealing with time-sensitive scenarios. This can become a bottleneck as the application grows, leading to user frustration and potential security concerns.
In this blog, we will address this issue by creating a solution using Firebase Authentication and Google Cloud Functions. You’ll learn how to build a secure and scalable system where admins can change passwords for other users seamlessly, without the need for additional verification steps, while ensuring the integrity of user data. By the end, you'll be equipped with the tools and knowledge to implement this feature in your own applications.
Firebase is a Google platform offering tools to build, improve, and scale apps across mobile, web, and desktop, with services like real-time databases, authentication, and serverless backend solutions.
To set up your Firebase project, please follow the steps below:
Node.js is an open-source, cross-platform runtime that allows JavaScript to run outside the browser, making it ideal for building scalable backend services and APIs. In this guide, we'll use Node.js to handle backend logic for password changes.
node -v
npm -v
npm install -g npm@latest
Google Cloud Functions is a serverless platform that lets you run small, event-driven functions without managing servers, automatically scaling based on demand. In this guide, we'll use Cloud Functions to securely handle backend tasks for password changes.
node -v
npm install -g firebase-tools.
firebase --version
firebase login
firebase init
Select your firebase project.
“Do you want to use ESLint to catch probable bugs and enforce style?” Answer "Yes" to confirm.
npm install express
npm install firebase-admin
npm install cors
const express = require("express");
const admin = require("firebase-admin");
const cors = require("cors");
const functions = require("firebase-functions");
const serviceAccount = require("./your-service-account-file.json");
const app = express();
app.use(cors());
app.use(express.json());
// Initialize Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// Basic route for testing
app.get("/", (req, res) => {
res.send("Hello World! The server is running.");
});
// Route to change a user's password by email
app.post("/changePassword", async (req, res) => {
const {email, newPassword} = req.body;
if (!email || !newPassword) {
return res.status(400).send({
error: "Email and newPassword are required.",
});
}
try {
// Look up the user by email
const userRecord = await admin.auth().getUserByEmail(email);
const uid = userRecord.uid;
// Update the user's password
await admin.auth().updateUser(uid, {
password: newPassword,
});
res.status(200).send({
message: "Password updated successfully",
});
} catch (error) {
console.error("Error updating user:", error);
res.status(500).send({
error: error.message,
});
}
});
// Export the Express app as a Cloud Function
exports.app = functions.https.onRequest(app);
Run the command to deploy the project to Firebase:
firebase deploy
You will get url in terminal something like "functions[us-central1-yourfunction]: http function initialized (http://122.0.1.1:5111/firebase_project_id/us-central1/yourfunction)".
Flutter is Google’s open-source UI toolkit for building natively compiled applications across mobile, web, and desktop from a single codebase. It is known for creating visually appealing, high-performance apps with ease.
1. Install Flutter
2. Create a New Flutter Project
flutter pub add http
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ChangePasswordScreen(),
);
}
}
class ChangePasswordScreen extends StatefulWidget {
@override
_ChangePasswordScreenState createState() => _ChangePasswordScreenState();
}
class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
Future<void> _changePassword() async {
final email = _emailController.text.trim();
final newPassword = _passwordController.text.trim();
if (email.isEmpty || newPassword.isEmpty) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('All fields are required')));
return;
}
final url = Uri.parse('<http://122.0.1.1:5111/firebase_project_id/us-central1/yourfunction>'); // Update with your server's URL
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: jsonEncode({
'email': email,
'newPassword': newPassword,
}),
);
if (response.statusCode == 200) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Password updated successfully')));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Failed to update password')));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Change Password')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: InputDecoration(labelText: 'User Email'),
),
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'New Password'),
obscureText: true,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _changePassword,
child: Text('Change Password'),
),
],
),
),
);
}
}
final url = Uri.parse('[*<http://122.0.1.1:5111/firebase_project_id/us-central1/>](<http://127.0.0.1:5001/ffqna-1f1bb/us-central1/demo>)yourfunction*');
Giving the admin the ability to change passwords for other users is important for keeping accounts secure and managing users easily. This feature helps admins quickly deal with security issues, assist users who can't reset their passwords, and make sure only the right people have access to important information. Following this guide will help you add this function effectively, making user management simpler and safer.
If You Enjoyed Our Content
If you found this blog helpful and want to stay updated with more useful content, we invite you to follow us on our social media platforms. Connect with us on LinkedIn, Dev.to, Twitter, Reddit.
If you need any help regarding any Flutter & Firebase. Connect with us .
We are experts with a deep understanding of these platforms. We provide Flutterflow Firebase development services to our clients.