Skip to content

Enforce authentication for some routes

Josh Thomas edited this page Jun 6, 2018 · 4 revisions

There are some cases where you want to have certain routes that are only accessable to specific users or if your application is in a certain state. This can be done by create Functional Components to wrap your routes. There are other methods of solving this issue, but this is probably the most straight forward.

First we will create a fake auth service.

const auth = {
  isAuthenticated: false,
  authenticate: function() {
    this.isAuthenticated = true;
  },
  logout: function() {
    this.isAuthenticated = false;
  }
}
const isAuthenticated = (): boolean => {
  return isUserLoggedIn;
}

Then we will create a Functional Component that accepts props and returns a stencil-route. This route itself has a routeRender that checks for auth. If auth fails it redirects to a login page or whatever you supply as failureRedirect.

const PrivateRoute = ({ component, ...props}: { [key: string]: any}) => {
  const Component = component;
  const redirectUrl = props.failureRedirect | '/login';

  return (
    <stencil-route {...props} routeRender={
      (props: { [key: string]: any}) => {
        if (auth.isAuthenticated) {
          return <Component {...props} {...props.componentProps}></Component>;
        }
        return <stencil-router-redirect url="/login"></stencil-router-redirect>
      }
    }/>
  );
}

Finally we will make use of this new Functional Component in place of a normal stencil-route.

<stencil-router titleSuffix="My App - ">
  <stencil-route-switch scrollTopOffset={0}>
    <stencil-route url="/" component="landing-page" exact={true} />
    <PrivateRoute url="/user" component="user-info" />
    <PrivateRoute url="/org" component="org-info" />
  </stencil-route-switch>
</stencil-router>