Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor, React Router 4, and Authentication

I've been scouring the inet trying to find anywhere that defines how to handle authentication in meteor and react router 4 .

Basically, I want certain routes to only be available to authenticated users. Is there any documentation on it?

Aseel

like image 800
Asool Avatar asked Mar 07 '23 20:03

Asool


1 Answers

Meteor has a very well developed User Accounts system. It provides ready libraries for OAuth authentication with Twitter, Facebook, etc. as well as a basic but useful UI packages. Check Meteor's official guide here first.

For implementing routing you need to track Meteor.userId() and change route via Meteor's reactive system called Tracker. Meteor.userId() returns a userId if currently connected user is logged in, and null otherwise. I provide an example code where React Router is used for routing, below. Notice that you'll will also need the historypackage to be installed and imported while working with React Router v4.

In your client/main.js;

import { Meteor } from 'meteor/meteor';
import React from 'react';
import ReactDOM from 'react-dom';
import { Tracker } from 'meteor/tracker'
import {onAuthChange, routes} from "../imports/routes/routes";


Tracker.autorun(function(){
    const authenticated = !! Meteor.userId();
    onAuthChange(authenticated);
});

Meteor.startup(() => {
    ReactDOM.render(routes, document.getElementById('app'));
});

And in your routes.js file;

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

import Home from './../ui/components/Home';
import Login from './../ui/components/Login';
import NotFound from './../ui/components/NotFound';
import Signup from './../ui/components/Signup';

const history = createBrowserHistory();
const unauthenticatedPages = ['/', '/signup'];
const authenticatedPages = ['/link'];

const publicPage = function  () {
    if (Meteor.userId()) {
        history.replace('/link');
    }
};

const privatePage = function  () {
    if(! Meteor.userId()) {
        history.replace('/');
    }
};

export const routes = (
    <Router history = {history}>
        <Switch>
          <Route exact path='/:id' component= {Login} onEnter={publicPage}/>
          <Route exact path='/signup' component={Signup} onEnter={publicPage}/>
          <Route exact path='/link' render={ () => <Home greet='User'/> } onEnter={privatePage} /> 
          <Route component={NotFound}/>
        </Switch>
    </Router>
);

export const onAuthChange = function (authenticated) {
    console.log("isAuthenticated: ", authenticated);
    const path = history.location.pathname;
    const isUnauthenticatedPage = unauthenticatedPages.includes(path);
    const isAuthenticatedPage = authenticatedPages.includes(path);
    if (authenticated && isUnauthenticatedPage) {   // pages: /signup and /
        console.log(`Authenticated user routed to the path /link`);
        history.replace('/link'); 
    } else if (!authenticated && isAuthenticatedPage) {
        console.log(`Unauthenticated user routed to the path /`);
        history.replace('/');
    }
};
like image 147
Gokhan Karadag Avatar answered Mar 14 '23 23:03

Gokhan Karadag