npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-identity

v0.3.0

Published

Higher order components for authorization

Downloads

35

Readme

react-identity

Higher order components for composing authorization into react apps


Build Status Coverage Status

Features

  • Integrates with your existing components seamlessly
  • Works with redux and other stores

Installation

Using npm:

npm install react-identity

Importing:

// Using ES6 transpiler
import ReactIdentity from 'react-identity'

// Or else
const ReactIdentity = require('react-identity')

Usage

react-identity provides withAuthorization HOC for composing authorization

Example component:
class ExampleComponent extends Component {
  render() {
    return (<div>{this.props.user.name}</div>)
  }
}

Lets see how we can add authorization to this component

withAuthorization HOC

withAuthorization takes a config which in this case is [ 'admin', 'moderator' ] which is later used by the authorize function to check if the component can be rendered.

import React, { Component } from 'react'
import { withAuthorization } from 'react-identity'

class SampleComponent extends Component {
  render() {
    return (<div>Sample Component</div>)
  }
}

export default withAuthorization(['admin', 'moderator'])(SampleComponent)

In order for this to work, we need to configure AuthProvider with the authorize function

AuthProvider

AuthProvider maintains the authData state and authorize function in its state and is passed as childContext, and the same is utilized by the withAuthorization HOC.

authorize function receives the requirements passed by the withAuthorization and userData from the state. The implementation of authorize function is left for the user.

import React, { Component } from 'react'
import { render } from 'react-dom'
import { AuthProvider } from 'react-identity'

import App from './components/App'

let authorize = (requirements, authData) => {
  let userRole = authData.user.role
  return requirements.some((role) => (role == userRole))
}

render(
    <AuthProvider authorize={authorize}>
        <App />
    </AuthProvider>
, document.getElementById('app'))

We have now setup the AuthProvider and withAuthorization but the userData is not yet present in the AuthProvider. authData can be directly sent as a prop to the AuthProvider, but for most cases this won't suffice, as authData needs to be dynamic and can be updated at any point of time. So, updater function can be used to update the authData at any point of time. This can be provided as a prop to the AuthProvider or can be accessed within the components using withUpdater HOC.

Implementing the updater function:
import React, { Component } from 'react'
import { render } from 'react-dom'
import { AuthProvider } from 'react-identity'

import App from './components/App'

let authorize = (requirements, authData) => {
  let userRole = authData.user.role
  return requirements.some((role) => (role == userRole))
}

let updater = (setAuthData) => {
  let authData = { name: 'Sample User', role: 'admin' }
  setAuthData(authData)
}

render(
    <AuthProvider authorize={authorize} updater={updater}>
        <App />
    </AuthProvider>
, document.getElementById('app'))

withUpdater HOC

import React, { Component } from 'react'
import { withUpdater } from 'react-identity'

class SampleComponent extends Component {
    handleOnClick = () => {
        let authData = { user: { name: 'Sid', role: 'moderator' } }
        this.props.updater(authData)
    }

    render() {
        return (
            <div>
                Sample Component
                <input type="button" value="Change user to Sid" onClick={this.handleOnClick} />
            </div>
        )
    }
}

export default withUpdater()(SampleComponent)

Configuring updater for redux

If the authData is stored in the redux, updates to the store can be subscribed by passing the updater function to the AuthProvider as follows

import React, { Component } from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { AuthProvider } from 'react-identity'
import { Provider as ReduxProvider } from 'react-redux'

import reducers from './reducers'
import App from './components/App'

const store = createStore(reducers)

let updater = (setAuthData) => {
  // set the authData initially
  setAuthData(store.getState().authData)
  // subscribe to updates on the store to update the authData
  store.subscribe(() => setAuthData(store.getState().authData))
}

render(
    <ReduxProvider>
        <AuthProvider updater={updater}>
            <App />
        </AuthProvider>
    </ReduxProvider>
, document.getElementById('app'))

Rendering custom Element for unauthorized users

If you want to render a custom element for unauthorized users, you can pass a react element to the withAuthorization's config as follows

import React, { Component } from 'react'
import { withAuthorization } from 'react-identity'

class SampleComponent extends Component {
  render() {
    return (<div>SampleComponent</div>)
  }
}

Rendering custom Component for unauthorized users

If you want to render a custom component for unauthorized users, you can pass a component to the withAuthorization's config as follows

import React, { Component } from 'react'
import { withAuthorization } from 'react-identity'

class SampleComponent extends Component {
  render() {
    return (<div>SampleComponent</div>)
  }
}

class SampleUnauthorizedComponent extends Component {
  render() {
    return (<div>SampleUnauthorizedComponent</div>)
  }
}

export default withAuthorization([ 'admin', 'moderator' ], { UnauthorizedComponent: SampleUnauthorizedComponent })(SampleComponent)

Accessing authData from components

The authData which is passed to the AuthProvider can be accessed via react context. We also provide a decorator withAuthData

import React, { Component } from 'react'
import { withAuthData } from 'react-identity'

class SampleComponent extends Component {
  render() {
    return (<div>{this.props.authData.user.name}</div>)
  }
}

export default withAuthData()(SampleComponent)

Rendering components only when unauthorized

When a component needs to be rendered only when unauthorized, inverseAuth config can be sent to the withAuthorization

import React, { Component } from 'react'
import { withAuthorization } from 'react-identity'

class SampleComponent extends Component {
  render() {
    return (<div>SampleComponent</div>)
  }
}

export default withAuthorization([], { inverseAuth: true })

License

react-identity is released under the MIT license.