42 lines
1016 B
JavaScript
42 lines
1016 B
JavaScript
import React from 'react'
|
|
import { Route, Redirect } from 'react-router-native'
|
|
import { PropTypes } from 'prop-types'
|
|
import { api } from '../API'
|
|
import autobind from 'autobind-decorator'
|
|
|
|
export class ProtectedRoute extends React.Component {
|
|
static propTypes = {
|
|
location: PropTypes.shape({ pathname: PropTypes.string, search: PropTypes.string }),
|
|
admin: PropTypes.bool,
|
|
}
|
|
|
|
@autobind
|
|
updateComponent() {
|
|
this.forceUpdate()
|
|
}
|
|
|
|
componentDidMount() {
|
|
api.addListener('login', this.updateComponent)
|
|
api.addListener('logout', this.updateComponent)
|
|
}
|
|
|
|
componentWillUnmount() {
|
|
api.removeListener('login', this.updateComponent)
|
|
api.removeListener('logout', this.updateComponent)
|
|
}
|
|
|
|
render(props) {
|
|
const user = api.loggedInUser
|
|
|
|
if (user.pending) {
|
|
return null
|
|
} else {
|
|
if (!user._id || (this.props.admin && !user.administrator)) {
|
|
return <Redirect to='/login' />
|
|
} else {
|
|
return <Route {...this.props} />
|
|
}
|
|
}
|
|
}
|
|
}
|