簡體   English   中英

使用 firebase admin sdk 創建用戶,可以使用 email 和密碼登錄

[英]Create user with firebase admin sdk that can signIn using email and password

我在雲功能上使用 firebase admin SDK 創建用戶使用

  admin.auth().createUser({
email: someEmail,
password: somePassword,
})

現在我希望用戶使用signInWithEmailAndPassword('someEmail', 'somePassword')但我不能。 我收到以下錯誤

{code: "auth/user-not-found", message: "There is no user record corresponding to this identifier. The user may have been deleted."}

在 2022 年,Admin SDK 中仍然沒有內置允許在模擬器中創建用戶的方法。

可以做的是使用模擬器的 REST API 直接在那里創建用戶。 API 記錄在此處: https://firebase.google.com/docs/reference/rest/auth#section-create-email-password

如果你已經安裝nanoid ,你可以使用下面的代碼在模擬器中創建用戶。

import { nanoid } from 'nanoid'
import httpClientFor from '../lib/http-client/client.js'
const httpClient = httpClientFor('POST')

export const createTestUser = async ({ email = `test-${nanoid(5)}@example.io`, password = nanoid(10), displayName = 'Tony' } = {}) => {
const key = nanoid(31)

const { body: responseBody } = await httpClient(`http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=${key}`, {
    json: {
        email,
        password,
        displayName
    }
})

const responseObject = JSON.parse(responseBody)
const { localId: userId, email: userEmail, idToken, refreshToken } = responseObject

return { userId, userEmail, idToken, refreshToken }
}

請注意:由於沒有實施錯誤處理,此代碼段不適合生產使用。

似乎沒有理由進行字符串化/解析。 在我與一個無關的錯字作斗爭之后,這奏效了......

來自 React JS 按鈕單擊的函數調用

     <Button onClick={() => {
                    var data = {
                        "email": "name@example.com",
                        "emailVerified": true,
                        "phoneNumber": "+15551212",
                        "password": "randomPW",
                        "displayName": "User Name",
                        "disabled": false,
                        "sponsor": "Extra Payload #1 (optional)",
                        "study": "Extra Payload #2 (optional)"
                    };
                    var createUser = firebase.functions().httpsCallable('createUser');
                    createUser( data ).then(function (result) {
                        // Read result of the Cloud Function.
                        console.log(result.data)
                    });
                }}>Create User</Button>

在 /functions 子目錄中的 index.js 中:

const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();

// CREATE NEW USER IN FIREBASE BY FUNCTION
exports.createUser = functions.https.onCall(async (data, context) => {
  try {
    const user = await admin.auth().createUser({
      email: data.email,
      emailVerified: true,
      password: data.password,
      displayName: data.displayName,
      disabled: false,
    });
    return {
      response: user
    };
} catch (error) {
    throw new functions.https.HttpsError('failed to create a user');
  }
});

控制台輸出的屏幕截圖

像這樣嘗試

請確保用戶是從面板創建的

    admin.auth().createUser({
  email: "user@example.com",
  emailVerified: false,
  phoneNumber: "+11234567890",
  password: "secretPassword",
  displayName: "John Doe",
  photoURL: "http://www.example.com/12345678/photo.png",
  disabled: false
})
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log("Successfully created new user:", userRecord.uid);
  })
  .catch(function(error) {
    console.log("Error creating new user:", error);
  });

萬一別人遇到這樣我能夠的幫助下修復

這是onCreate雲函數內部的一個工作示例:

exports.newProjectLead = functions.firestore
  .document('newProjectForms/{docId}')
  .onCreate(async (snapshot) => {
    const docId = snapshot.id
    // this is what fixed it the issue
    // stringify the data
    const data = JSON.stringify(snapshot.data())
    // then parse it back to JSON
    const obj = JSON.parse(data)
    console.log(obj)
    const email = obj.contactEmail
    console.log(email)
    const password = 'ChangeMe123'
    const response = await admin.auth().createUser({
      email,
      password
    })
    data
    const uid = response.uid

    const dbRef = admin.firestore().collection(`clients`)
    await dbRef.doc(docId).set({
      id: docId,
      ...data,
      uid
    }, {
      merge: true
    })

    console.log('New Client Created')

  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM