Currently using Firebase in my react native app. I have to manage two roles for admin and user. I am not able to manage roles in firebase authentication here is the code in which i am simply registering a user. Any one please help regarding managing roles. Thanks
register: async (email, password) => {
try {
await auth().createUserWithEmailAndPassword(email, password);
} catch (e) {
console.log(e);
}
},
Take a look at this medium auth flow tutorial, I'm using this to handle multiple user roles in my mobile app and it works flawlessly.
You don't need to use AWS, just replace it with you backend server auth api.
To handle multiple roles, alter AppNavigator return like this:
return (
<NavigationContainer>
{userToken ?
isAdmin
<AdminModule />
:
<UserModule />
:
<AuthModule />
}
</NavigationContainer>
);
All of these Modules are just StackNavigators, or BottomTabNavigators or both combined, it's up to you.
Use react hooks to get token or admin/user from auth:
const { userToken, isAdmin } = useAuthState();
Alter the reducer to handle multiple roles:
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userToken: action.token,
isAdmin: false,
};
case 'SIGN_IN_ADMIN':
return {
...prevState,
isSignout: false,
userToken: action.token,
isAdmin: true,
};
Also alter the AuthProvider to handle multiple roles (these are default values):
const [state, dispatch] = React.useReducer(AuthReducer, {
isLoading: true,
isSignout: false,
userToken: null,
isAdmin: false,
});
After successful login dispatch desired type according to role:
dispatch({ type: 'SIGN_IN_ADMIN', token: global.token });
The reason this works, is you need to wrap all your application in the AuthProvider like this:
<AuthProvider>
<AppNavigator />
</AuthProvider>
Then everytime you dispatch() something, the app re-renders UI according to the role you dispatched.
The login/register call should return admin/user role, so you can render user/admin UI. It should look something like this:
return Api.login(username, password)
.then(response => {
if (response.role == 'user') {
dispatch('SIGN_IN', token: response.token);
} else if (response.role == 'admin') {
dispatch('SIGN_IN_ADMIN', token: response.token);
}
})
I spent days on this, hope you will get it done faster with this help.