How admin can change password of other authenticated users
Knowledge

How admin can change password of other authenticated users

Learn how admin can change password of other authenticated user

Pankaj Sharma
Flutterflow development company
September 16, 2024
Table of content

Overview

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.

Prerequisites

  • Firebase
  • Flutter
  • Node js
  • Google Cloud Functions

Firebase Project Setup

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:

1. Create a firebase project

  • Go to the Firebase Console.
  • Click on Create a project and follow the instructions to set up a new project.

2. Enable Firebase Authentication

  • In the Firebase console, go to the Authentication section.
  • Click Get Started and enable the sign-in methods you need (e.g., Email/Password, Google).

3. Create Service Account for Admin SDK

  • Go to Project settings -> Service accounts.
  • In the Firebase Admin SDK section, select Node.js from the Admin SDK configuration snippet, and click on Generate new private key. This will download a JSON file, which you'll use in your backend service.

4. Enable Cloud Functions

  • To use Cloud Functions, your project must be on the Blaze Plan. By default, every Firebase project is on the Spark Plan.
  • In the Firebase Console, click "Upgrade" from the left menu, select the Blaze Plan, and choose a billing account. Then, navigate to the "Functions" tab on the left sidebar and follow the instructions to enable Cloud Functions for your project.
  • With the Firebase configuration complete, you can now proceed to create and deploy the "Admin Can Change Password of Other Authenticated Users" feature using Firebase Cloud Functions.

Node js

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.

Steps to Install Node.js:

  • Download the Installer:
    • Go to the official Node.js website here.
    • Choose the recommended version for your operating system (LTS is usually preferred for stability).
  • Run the Installer:
    • Open the downloaded file and follow the installation prompts. Make sure to select the option to install Node.js and npm (Node Package Manager).
  • Verify Installation:
    • Once installed, open your terminal/command prompt and type the following commands:
    node -v

    npm -v

  • Update npm (Optional)::
    • You can update npm to the latest version using the command:
    npm install -g npm@latest

Google Cloud Function

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.

Steps to Install Firebase CLI for Cloud Functions:

  • Open the Command Prompt and create a new folder using the command:
  • D:\>mkdir firebase_auth
  • Use the following command to open the folder: D:\>cd firebase_auth.
  • Ensure that npm is installed on your local machine, for doing that run the below command on your terminal :

node -v

  • Open your terminal and run the following command to install the Firebase CLI globally:

npm install -g firebase-tools.

  • To confirm that the Firebase CLI is installed correctly, run the command :

firebase --version

  • To connect the Firebase CLI to your Firebase account, run the following command:

firebase login

  • It will then ask the question: “Allow Firebase to collect CLI and Emulator Suite usage and error reporting information?” Proceed by selecting YES.
  • Initialize the Firebase project by running the command :

firebase init

  • Which Firebase features do you want to set up for this directory? Press Space to select features, then press Enter to confirm your choices. Select “Functions: Configure a Cloud Functions directory and its files.

Select your firebase project.

  • Which language would you like to use to write Cloud Functions? Select “JavaScript” .

“Do you want to use ESLint to catch probable bugs and enforce style?” Answer "Yes" to confirm.

  • “Do you want to install dependencies with npm now?” Answer "Yes" to confirm.
  • Firebase initialization is now completed.
  • After this, a folder named “functions” will be created within the “firebase_auth” folder.

Cloud Function Code

  • Now open that “functions” folder by your code editor.
  • Install “express” module by below command :

npm install express

  • Install “firebase-admin” module by below command :

npm install firebase-admin

  • Install “cors” module by below command :

npm install cors

  • Now go to the “index.js” file and write the below code there.

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);



  • Replace'./path/to/your-service-account-file.json' with the path to the JSON file you downloaded from the Firebase Admin SDK.
  • Additionally, make sure to save that JSON file in the same folder.

Deploy Cloud Function

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

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.

Steps to Install Flutter and Create Flutter Project :

1. Install Flutter

  • If you haven't already, make sure to install Flutter on your development machine. Visit the Flutter installation page and choose your operating system (Windows, macOS, or Linux).
  • Download the latest stable release of the Flutter SDK.

2. Create a New Flutter Project

  • Open a terminal and create a new Flutter project using either the command line or manually. To do it via the terminal, run the command: flutter create project_name.
  • Now open your project in your code editor.
  • Need to add http plugin in your pubspec.yaml file, we can add it by below command :

flutter pub add http

  • Replace the contents of the lib/main.dart file with the following code:

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'),

           ),

         ],

       ),

     ),

   );

 }

}



  • Just update the url which you get during cloud function deployment :

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*');

Conclusion

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.

How admin can change password of other authenticated users

Ex- Technical Lead at Paytm Money | Senior Software Developer | NIT Surathkal

Flutterflow project image

Need expert help with Firebase and Cloud Functions?

Contact Us
Flutterflow development company

View more blogs

Ready to develop your own product? Get in touch today!

Get in Touch  
Flutterflow app development
Whatsapp icon