Search⌘ K
AI Features

Final Enhancements

Explore how to refine authorization in a React app using Firebase. Learn to protect routes, handle authenticated user rendering, and test access restrictions to ensure secure user experiences and role-based controls.

We'll cover the following...

Further Security

One refinement can be made in the withAuthorization higher-order component using the authenticated user from the context:

Node.js
import React from 'react';
import { withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import AuthUserContext from './context';
import { withFirebase } from '../Firebase';
import * as ROUTES from '../../constants/routes';
const withAuthorization = condition => Component => {
class WithAuthorization extends React.Component {
componentDidMount() {
this.listener = firebase.auth.onAuthStateChanged(authUser => {
if (!condition(authUser)) {
this.props.history.push(ROUTES.SIGN_IN);
}
});
}
componentWillUnmount() {
this.listener();
}
render() {
return (
<AuthUserContext.Consumer>
{authUser =>
condition(authUser) ? <Component {...this.props} /> : null
}
</AuthUserContext.Consumer>
);
}
}
return compose(
withRouter,
withFirebase,
)(WithAuthorization);
};
export default withAuthorization;

The improvement in the render method was needed to avoid showing the protected page before the redirect happens. We want to show nothing if the authenticated user doesn’t meet the condition’s criteria.

In ...