Javascript Meteor.js

Meteor.js page restrictions with react router v4

We can imagine that we have already meteor.js authentication as like Signup Signin & Signout but we have to worry about some pages restriction such as Todo page which is available right now without a user authentication but we need user can access this page after Signin & after Signin he can’t access the Signin & Signuot page.

On react router 4 it has some changes such as history , on the react router < 4 it included with browserHistory but now in 4 it’s not present so we need to install this package from npm such as `npm install history` and then in routes

import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();
const publicPages = ['/', '/signup'];
const privatePages = ['/todo'];

const onEnterPublicPage = () => {
    if (Meteor.userId()) {
        history.replace('/todo');
    }
};
  
const onEnterPrivatePage = () => {
    if (!Meteor.userId()) {
        history.replace('/');
    }
};

export const onAuthenticationChange = (isAuthenticated) => {
    console.log('is authenticated...', isAuthenticated);

    const pathname = this.location.pathname;
    const isUnauthenticatedPage = publicPages.includes(pathname);
    const isAuthenticatedPage = privatePages.includes(pathname);
  
    if (isAuthenticated && isUnauthenticatedPage) {
        console.log('Autenticated');
        history.replace('/todo');
    } else if (!isAuthenticated && isAuthenticatedPage) {
        console.log('Not Authenticated');
        history.replace('/');
    }
}

export const routes = (
    <Router history = {history}>
        <Switch>
            <Route exact path="/" component={Signin} onEnter={onEnterPublicPage} />
            <Route exact path="/signup" component={Signup} onEnter={onEnterPublicPage} />
            <Route exact path="/todo" component={Todo} onEnter={onEnterPrivatePage} />
            <Route path="*" component={NotFound}/>
        </Switch>
    </Router>
);

Now in the main.js file add the following

import { routes, onAuthenticationChange } from '../imports/routes/routes';

Tracker.autorun(() => {
    const isAuthenticated = !!Meteor.userId();
    onAuthenticationChange(isAuthenticated);
});

That’s it.

Fool Dev

I didn't get trained by the school system like other kids, and when I did concentrate on learning, my mind was cluttered and locked by the programming of the system. © Huey Newton