Setup authentication & authorization in Reactjs

Adding devtools

Devtools are the primary way you will work with the state in your app. We’ll install the default log and dock monitors, but you may develop your own if they don’t suit you.

Add a file called devtools.js to your source folder and add this code:

'use strict';
import React from 'react';

import { createDevTools } from 'redux-devtools';

import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';

Monitors are separate packages, and you can make custom ones, let’s take a look at the following code:

const DevTools = createDevTools(

Monitors are individually adjustable with props. Take a look at the source code for the devtools to learn more about how they’re built. Here, we put LogMonitor inside a DockMonitor class:

  <DockMonitor toggleVisibilityKey='ctrl-h'
    changePositionKey='ctrl-q'>
    <LogMonitor theme='tomorrow' />
  </DockMonitor>
);

export default DevTools;

Tying the files together

It’s time to tie the app together. Open index.jsx and replace the existing content with this code:

import React, { Component, PropTypes } from 'react'
import { Grid, Row, Col, Button, Input } from 'react-bootstrap';
import { render, findDOMNode } from 'react-dom';
import store from './stores/store';
import { login } from './actions/login'
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
import DevTools from './devtools';

This adds all the files we created and the methods we needed from ReactJS. Now refer to the following code:

class App extends Component {

  handleSelect() {
    const { dispatch } = this.props;
    dispatch(
    login(
    {
      username: findDOMNode(this.refs.username).value,
      password: findDOMNode(this.refs.password).value
    }))
  }

This function dispatches the login action we defined in actions/login.js with the contents of the username and password input fields defined in the render() method, as follows:

  renderWelcomeMessage() {
    const { user } = this.props;
    let response;
    if(user.userData.name) {
      response = "Welcome "+user.userData.name;
    }
    else {
      response = user.error;
    }
    return (<div>
      { response }
      </div>);
  }

This is a small piece of JSX code that we use to display either a welcome message or an error message after a login attempt. Now check out the following code:

  renderInput() {
    return <form>
      <div>
        <FormGroup>
          <ControlLabel>Username</ControlLabel>
          <FormControl type= "text"
            ref = "username"
            placeholder= "username"
          />
        <FormControl.Feedback />
        </FormGroup>
      </div>

      <div>
        <FormGroup>
          <ControlLabel>Password</ControlLabel>
          <FormControl type= "password"
            ref = "password"
            placeholder= "password"
          />
          <FormControl.Feedback />
        </FormGroup>
      </div>

      <Button onClick={this.handleSelect.bind(this)}>Log in</Button>
    </form>)
  }

These are the input fields for logging in a user.

Pro Tip

Note that we must bind the context ourselves with .bind(this).

With createClass, binds were created automatically, but no such magic exists when you use JavaScript 2015 classes. The next iteration of JavaScript may bring a proposed new syntactic sugar for bind (::), which means that we could have used this.handleSelect without explicitly binding it, but it’s still a way off from being implemented:

  render () {
    const { user } = this.props;
    return (
      <Grid>
        <DevTools store={store} />
        <Row>
          <Col xs={ 12 }>
            <h3> Please log in </h3>
          </Col>

          <Col xs={ 12 }>
            { this.renderInput() }
          </Col>

          <Col xs={ 12 }>
            { this.renderWelcomeMessage() }
          </Col>
        </Row>
      </Grid>
    );
  }
};

This render block simply presents the visitor with the option to log in. The app will attempt to log in when the user clicks on Enter, and it will either present the visitor with a welcome message or the invalid login message.

This function converts the app state to a set of properties that we can pass to the children components:

function mapStateToProps(state) {
  const { user } = state;
  const {
    message
  } = user || {
    message: ""
  }

  return {
    user
  }
}

This is where we define the app with the Redux connect() method, which connects a React component to a Redux store. Rather than modifying the component in place, it returns a new component class that we can render:

const LoginApp = connect(mapStateToProps)(App);

We create a new component class that wraps the LoginApp component inside a Providercomponent:

class Root extends Component {
  render() {
    return (
      <Provider store={store}>
        <LoginApp />
      </Provider>
    )
  }
}

The Provider component is special because it is responsible for passing the store as a property to the children components. It’s recommended that you create a root component wrapping the app inside Provider, unless you want to manually pass the store yourself to all children components. Finally, we pass the Root component to render it and to ask it to display the contents inside div with the ID App in index.html:

render(
  <Root />,
  document.getElementById('app')
);

The app itself looks very unassuming, but it’s worth looking at the devtools to the right of the screen. This is the Redux dev tools, and it tells you that you have an app state with a user object with two keys. If you click on user, it will open and show you that it consists of an object with an empty message string and an empty userData object.This is exactly how we configured it in source/index.jsx, so if you see this, it’s working as expected.

Pro tip

Try to log in by typing in a username and password. Hint: the combo darth/vader or john/sarahwill let you log in.

Notice that you can now instantly navigate through your app state by clicking on the action buttons in your developer toolbar.

Pin It on Pinterest

Shares

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)