Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add authenticatingSelector. #35

Merged
merged 9 commits into from May 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ Any time the user data changes, the UserAuthWrapper will re-check for authentica

* `authSelector(state, [ownProps], [isOnEnter]): authData` \(*Function*): A state selector for the auth data. Just like `mapToStateProps`.
ownProps will be null if isOnEnter is true because onEnter hooks cannot receive the component properties. Can be ignored when not using onEnter.
* `authenticatingSelector(state, ownProps): Bool` \(*Function*): A state selector indicating if the user is currently authenticating. Just like `mapToStateProps`. Useful for async session loading.
* `LoadingComponent` \(*Component*): A React component to render while `authenticatingSelector` is `true`. If not present, will be a `<span/>`.
* `[failureRedirectPath]` \(*String*): Optional path to redirect the browser to on a failed check. Defaults to `/login`
* `[redirectAction]` \(*Function*): Optional redux action creator for redirecting the user. If not present, will use React-Router's router context to perform the transition.
* `[wrapperDisplayName]` \(*String*): Optional name describing this authentication or authorization check.
Expand Down
34 changes: 22 additions & 12 deletions src/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,30 @@ import hoistStatics from 'hoist-non-react-statics'
import isEmpty from 'lodash.isempty'

const defaults = {
LoadingComponent: 'span',
failureRedirectPath: '/login',
wrapperDisplayName: 'AuthWrapper',
predicate: x => !isEmpty(x),
authenticatingSelector: () => false,
allowRedirectBack: true
}

export default function factory(React, empty) {

const { Component, PropTypes } = React;
const { Component, PropTypes } = React

return (args) => {
const {authSelector, failureRedirectPath, wrapperDisplayName, predicate, allowRedirectBack, redirectAction} = {
const { authSelector, authenticatingSelector, LoadingComponent, failureRedirectPath, wrapperDisplayName, predicate, allowRedirectBack, redirectAction } = {
...defaults,
...args
}

const isAuthorized = (authData) => predicate(authData)

const ensureAuth = ({location, authData}, redirect) => {
const ensureAuth = ({ location, authData }, redirect) => {
let query
if (allowRedirectBack) {
query = {redirect: `${location.pathname}${location.search}`}
query = { redirect: `${location.pathname}${location.search}` }
} else {
query = {}
}
Expand All @@ -43,15 +45,18 @@ export default function factory(React, empty) {

const mapDispatchToProps = (dispatch) => {
if (redirectAction !== undefined) {
return {redirect: (args) => dispatch(redirectAction(args))}
return { redirect: (args) => dispatch(redirectAction(args)) }
} else {
return {}
}
}

@connect(
(state, ownProps) => {
return {authData: authSelector(state, ownProps, false)}
return {
authData: authSelector(state, ownProps, false),
isAuthenticating: authenticatingSelector(state, ownProps)
}
},
mapDispatchToProps,
)
Expand All @@ -74,11 +79,15 @@ export default function factory(React, empty) {
};

componentWillMount() {
ensureAuth(this.props, this.getRedirectFunc(this.props))
if(!this.props.isAuthenticating) {
ensureAuth(this.props, this.getRedirectFunc(this.props))
}
}

componentWillReceiveProps(nextProps) {
ensureAuth(nextProps, this.getRedirectFunc(nextProps))
if(!nextProps.isAuthenticating) {
ensureAuth(nextProps, this.getRedirectFunc(nextProps))
}
}

getRedirectFunc = (props) => {
Expand All @@ -97,13 +106,14 @@ export default function factory(React, empty) {
render() {
// Allow everything but the replace aciton creator to be passed down
// Includes route props from React-Router and authData
const {redirect, authData, ...otherProps} = this.props

const { redirect, authData, isAuthenticating, ...otherProps } = this.props
if (isAuthorized(authData)) {
return <DecoratedComponent authData={authData} {...otherProps} />
} else if(isAuthenticating) {
return <LoadingComponent {...otherProps} />
} else {
// Don't need to display anything because the user will be redirected
return React.createElement(empty);
return React.createElement(empty)
}
}
}
Expand All @@ -113,7 +123,7 @@ export default function factory(React, empty) {

wrapComponent.onEnter = (store, nextState, replace) => {
const authData = authSelector(store.getState(), null, true)
ensureAuth({location: nextState.location, authData}, replace)
ensureAuth({ location: nextState.location, authData }, replace)
}

return wrapComponent
Expand Down
6 changes: 3 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import factory from './factory';
import React from 'react'
import factory from './factory'

export const UserAuthWrapper = factory(React, 'div');
export const UserAuthWrapper = factory(React, 'div')
6 changes: 3 additions & 3 deletions src/native.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { View } from 'react-native';
import factory from './factory';
import React, { View } from 'react-native'
import factory from './factory'

export const UserAuthWrapper = factory(React, View);
export const UserAuthWrapper = factory(React, View)
38 changes: 38 additions & 0 deletions test/UserAuthWrapper-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ const UserIsOnlyMcDuderson = UserAuthWrapper({
predicate: user => user.lastName === 'McDuderson'
})

class LoadingComponent extends Component {
render() {
return (
<div>Loading!</div>
)
}
}

const AlwaysAuthenticating = UserAuthWrapper({
authSelector: userSelector,
authenticatingSelector: () => true,
LoadingComponent: LoadingComponent,
redirectAction: routerActions.replace,
wrapperDisplayName: 'AlwaysAuthenticating'
})

class App extends Component {
static propTypes = {
children: PropTypes.node
Expand Down Expand Up @@ -108,6 +124,7 @@ class UnprotectedParentComponent extends Component {
const defaultRoutes = (
<Route path="/" component={App} >
<Route path="login" component={UnprotectedComponent} />
<Route path="alwaysAuth" component={AlwaysAuthenticating(UnprotectedComponent)} />
<Route path="auth" component={UserIsAuthenticated(UnprotectedComponent)} />
<Route path="hidden" component={HiddenNoRedir(UnprotectedComponent)} />
<Route path="testOnly" component={UserIsOnlyTest(UnprotectedComponent)} />
Expand Down Expand Up @@ -165,6 +182,27 @@ describe('UserAuthWrapper', () => {
expect(store.getState().routing.locationBeforeTransitions.search).to.equal('?redirect=%2Fauth')
})

it('does not redirect if authenticating', () => {
const { history, store } = setupTest()

expect(store.getState().routing.locationBeforeTransitions.pathname).to.equal('/')
expect(store.getState().routing.locationBeforeTransitions.search).to.equal('')
history.push('/alwaysAuth')
expect(store.getState().routing.locationBeforeTransitions.pathname).to.equal('/alwaysAuth')
expect(store.getState().routing.locationBeforeTransitions.search).to.equal('')
})

it('renders the specified component when authenticating', () => {
const { history, store, tree } = setupTest()

history.push('/alwaysAuth')

const comp = findRenderedComponentWithType(tree, LoadingComponent)
// Props from React-Router
expect(comp.props.location.pathname).to.equal('/alwaysAuth')

});

it('preserves query params on redirect', () => {
const { history, store } = setupTest()

Expand Down