prescottprue / react-redux-firebase

Redux bindings for Firebase. Includes React Hooks and Higher Order Components.
https://react-redux-firebase.com
MIT License
2.55k stars 559 forks source link

Custom user claims not being fetched with enableClaims: true #1114

Open Seth-McKilla opened 3 years ago

Seth-McKilla commented 3 years ago

Hello,

I'm trying to fetch custom user claims with the rrfConfig flags of "enableClaims: true" & "userProfile: users" but it is failing to fetch the custom claims. I've confirmed that the custom user claims are being created on the back with the admin SDK but they are not being set in state.firebase.profile.token.claims.

I'm expecting the following for the profile data:

{
  isEmpty: false,
  isLoaded: true,
  claims: <all claims data including "role: owner">
}

But am instead receiving:

{
   isEmpty: true,
   isLoaded: false,
}

Here is my current index.js file for the application:

import "./index.css";
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// Redux
import { Provider } from "react-redux";
import { store } from "./redux/store";

// Firebase
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/database";
import firebaseConfig from "./config/firebase-config";
import { ReactReduxFirebaseProvider } from "react-redux-firebase";

// CUSTOM COMPONENTS
import { AuthIsLoaded } from "./components/Authentication";

const rrfConfig = {
  userProfile: "users",
  enableClaims: true,
};

firebase.initializeApp(firebaseConfig);

const rrfProps = {
  firebase,
  config: rrfConfig,
  dispatch: store.dispatch,
};

ReactDOM.render(
  <Provider store={store}>
    <ReactReduxFirebaseProvider {...rrfProps}>
      <AuthIsLoaded>
        <App />
      </AuthIsLoaded>
    </ReactReduxFirebaseProvider>
  </Provider>,
  document.getElementById("root")
);

The config file:

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appID: process.env.REACT_APP_FIREBASE_APP_ID,
};

export default firebaseConfig;

And my custom user claim setting on the backend for email/password and Google logins:

const createOwner = async ({ email, firstName, lastName, password }) => {
  // Firebase
  const { uid, displayName } = await admin.auth().createUser({
    email,
    password,
    displayName: `${firstName} ${lastName}`,
    emailVerified: false,
  });

  await admin.auth().setCustomUserClaims(uid, { role: "owner" });

  // MongoDB
  const user = new User({
    _id: uid,
    name: displayName,
    role: "owner",
  });
  await user.save();

  return user;
};

const createGoogleOwner = async ({ uid }) => {
  // Firebase
  const userRecord = await admin.auth().getUser(uid);
  if (userRecord.customClaims) return userRecord;
  await admin.auth().setCustomUserClaims(uid, { role: "owner" });
  const { displayName } = await admin.auth().getUser(uid);

  // MongoDB
  const existingUser = await User.findById(uid);
  if (existingUser) return existingUser;

  const user = new User({
    _id: uid,
    name: displayName,
    role: "owner",
  });
  await user.save();

  return user;
};

I can verify that the claims are set by calling this:

firebase
  .auth()
  .currentUser.getIdTokenResult()
  .then((token) => {
    console.log(token.claims);
  })
  .catch((error) => {
    console.log(error);
  });

Some FYI's: I'm using Chrome, version 3.10.0 of react-redux-firebase, and plan to use these custom claims for HOC Authentication routing.

Any help with this matter would be very much appreciated as it is causing me quite the headache!

Thanks! Seth

Seth-McKilla commented 3 years ago

Also, I meant to include my redux store configuration:

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { getFirebase } from "react-redux-firebase";
import { composeWithDevTools } from "redux-devtools-extension";
import initialState from "./initialState";

import rootReducer from "./reducers/rootReducer";

const middleware = [thunk.withExtraArgument(getFirebase)];

const composedEnhancer = composeWithDevTools(applyMiddleware(...middleware));

const store = createStore(rootReducer, initialState, composedEnhancer);

export { initialState, store };

And my root reducer looks like this:

import { combineReducers } from "redux";
import { firebaseReducer } from "react-redux-firebase";
import { constants } from "react-redux-firebase";

const appReducer = combineReducers({
  firebase: firebaseReducer,
  // other reducers here omitted for sake of brevity
});

const rootReducer = (state, action) => {
  if (action.type === constants.actionTypes.LOGOUT) {
    return appReducer(undefined, action);
  }

  return appReducer(state, action);
};

export default rootReducer;