Как добавить Firebase Admin Auth в приложение React .env? - PullRequest
0 голосов
/ 04 марта 2020

Хороший вопрос,

чтобы добавить google-аутентификацию из firebase для доступа администратора, сначала вам нужен файл. json из firebase, вы можете получить его из своей админ-панели, где у вас есть настройка аутентификации

enter image description here

go на служебную учетную запись сгенерируйте и загрузите JSON

enter image description here

используйте его в своем файле, как вы будете sh ... например, мой маршрут администратора

//Use dotenv to read .env vars into Node
require('dotenv').config();

const express = require('express');
var router = express.Router();

// Schema import
const postModel = require('../models/postModel');
const userModel = require('../models/userModel');

// parse json to use in all requests got or sent by router .. which is provided by express
router.use(express.json());

// Initialize the default app

var admin = require('firebase-admin');

admin.initializeApp({
    credential: admin.credential.cert({
  "type": process.env.FIREBASE_TYPE,
  "project_id": process.env.ID,
  "private_key_id": process.env.FIREBASE_PRIVATE,
  "private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
  "client_email": process.env.FIREBASE_CLIENT_EMAIL,
  "client_id": process.env.FIREBASE_CLIENTID,
  "auth_uri": process.env.FIREBASE_AUTHURI,
  "token_uri": process.env.FIREBASE_TOKEN,
  "auth_provider_x509_cert_url": process.env.FIREBASE_AUTH_PROVIDER,
  "client_x509_cert_url": process.env.FIREBASE_FIREBASE_CLIENT
}),
databaseURL: process.env.FIREBASE_DATABASE
});





console.log(process.env.ID)


router.post('/', (req, res, next) => {
    const admin_uid = req.body.uid;

    if (admin_uid === process.env.ADMIN_URI) {
        // // users email

        const email = req.body.email;

        admin
            .auth()
            .getUserByEmail(email)
            .then(function(userRecord) {
                // See the UserRecord reference doc for the contents of userRecord.
                console.log('Successfully fetched user data:', userRecord.toJSON());
                // res.json(userRecord.toJSON())

                admin.auth().updateUser(userRecord.uid, { disabled: true }).catch((error) => res.json(error));
            })
            .catch(function(error) {
                console.log('Error fetching user data:', error);
                // res.json(error)
            });

        // delete the posts of the user and the user

        postModel.deleteMany({ author: email }, (error, returnedDocuments) => {
            if (error) return next(error);

            userModel.findOneAndDelete({ email: email }, (error, returnedDocuments) => {
                if (error) return next(error);
                res.json(`User  ${email} deleted ...Posts from ${email} deleted`);
            });
        });
    } else {
        res.json('failure, admin ops');
    }
});

module.exports = router;

в вашем .env, он должен быть в интерфейсе, иначе реагировать не может получить ключи поэтому вам потребуется 2 .env, один для клиента, другой для сервера, в ответ .env сделайте это

enter image description here

удачи, добавьте комментарий для улучшить, если вы чувствуете склонность.

...