Ask Your Question
2

Is it impossible to generate a user with a password in Firebase functions by utilizing Auth and the Firebase emulator?

asked 2023-01-05 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-02-09 18:00:00 +0000

huitzilopochtli gravatar image

It is possible to generate a user with a password in Firebase functions by utilizing Auth and the Firebase emulator. Here's an example code snippet for generating a user with email and password using the Firebase emulator:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.createUser = functions.https.onRequest((req, res) => {
  // Create a user with email and password
  admin.auth().createUser({
    email: 'example@example.com',
    password: 'password123'
  })
  .then((userRecord) => {
    console.log('Created user with uid:', userRecord.uid);
    res.status(200).send('User created successfully');
  })
  .catch((error) => {
    console.error('Error creating user:', error);
    res.status(500).send('Error creating user');
  });
});

To test this function locally in the Firebase emulator, you can use the firebase-functions-test library. Here's an example test case:

const test = require('firebase-functions-test')();
const admin = require('firebase-admin');
const myFunctions = require('../index');

describe('createUser', () => {
  beforeEach(() => {
    // Set up admin SDK mock
    admin.initializeApp({
      databaseURL: 'https://my-project.firebaseio.com',
      credential: admin.credential.applicationDefault()
    });
  });

  afterEach(() => {
    test.cleanup();
  });

  it('should create a user with email and password', () => {
    // Mock the request and response objects
    const req = { body: {} };
    const res = { send: jest.fn() };

    // Call the function
    myFunctions.createUser(req, res);

    // Check the response
    expect(res.send).toHaveBeenCalledWith('User created successfully');
  });
});

Note that in the test case, we're mocking the Firebase Admin SDK using the firebase-functions-test library. This allows us to test the function locally without actually calling the Firebase API.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-05 11:00:00 +0000

Seen: 9 times

Last updated: Feb 09 '23