Home > Net >  Firebase9 - How can i restrict non-registered users from signing in?
Firebase9 - How can i restrict non-registered users from signing in?

Time:09-30

I'm implementing Firebase auth with React context and this is my first time using context with it, so my question is that how can I restrict non-registered users from signing in? right now when I sign in with some random emails it's redirecting me to the home page

this is what I have

firebase config:

const firebaseConfig = {
  apiKey: XXXXXXXXXX,
  authDomain: XXXXXXXXXX,
  projectId: XXXXXXXXXX,
  storageBucket: XXXXXXXXXX,
  messagingSenderId: XXXXXXXXXX,
  appId: XXXXXXXXXX,
};

const app = initializeApp(firebaseConfig);
export const authentication = getAuth(app);

Context:

const UserContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState({});

  const createUser = (email, password) => {
    createUserWithEmailAndPassword(authentication, email, password);
  };
  const signUser = (email, password) => {
    signInWithEmailAndPassword(authentication, email, password);
  };

  const logOut = () => {
    return signOut(authentication);
  };

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(authentication, (currenUser) => {
      setUser(currenUser);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <UserContext.Provider value={{ createUser, signUser, user, logOut }}>
      {children}
    </UserContext.Provider>
  );
};

export const UserAuth = () => {
  return useContext(UserContext);
};

Sign in Page:


const SignIn = ({ navigation }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showErr, setShowErr] = useState('');

  const { user, signUser } = UserAuth();

  const handleSignIn = async () => {
    try {
      await signUser(email, password);
      
        navigation.navigate('Home');
      
    } catch (e) {
      console.log(e.message);
    }
  };

  return (
    <View
    {...}
    </View>
  );
};

export default SignIn;



CodePudding user response:

As you have probably experienced, you cannot prevent (undesired) users to sign up to your app (one can quite easily get your project API key and use it with the Auth REST API for example).

One common solution is to assign a specific Custom Claim to each "registered" user and use this claim in the security rules of the Firebase services used by your app.

You don’t explain what is registered user so I cannot share some code but we usually use a Cloud Function to assign Custom Claims. So you’ll need to adapt your onboarding workflow to include a processing via a Cloud Function.

This article may help you.

  • Related