49 lines
1.1 KiB
JavaScript
49 lines
1.1 KiB
JavaScript
import React from "react"
|
|
import { Route, Redirect } from "react-router-native"
|
|
import { PropTypes } from "prop-types"
|
|
import { api } from "../API"
|
|
import { reactAutoBind, autoBind } from "auto-bind2"
|
|
|
|
export class ProtectedRoute extends React.Component {
|
|
static propTypes = {
|
|
location: PropTypes.shape({
|
|
pathname: PropTypes.string,
|
|
search: PropTypes.string,
|
|
}),
|
|
admin: PropTypes.bool,
|
|
}
|
|
|
|
constructor(props) {
|
|
super(props)
|
|
reactAutoBind(this)
|
|
}
|
|
|
|
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} />
|
|
}
|
|
}
|
|
}
|
|
}
|