bo/src/requireAuth.js
2018-09-09 12:06:10 +02:00

42 lines
911 B
JavaScript

import React, { Component } from 'react';
import API from './Api';
export default function (ComposedComponent, Auth = true) {
class Authentication extends Component {
constructor(props) {
super(props);
this.next = this.next.bind(this);
}
next(isAuthentified) {
if (Auth) {
if (!isAuthentified) {
this.props.history.push('/');
}
}
}
componentWillMount() {
API.get('me')
.then((res) => {
this.next(res.status === 200);
})
.catch((e) => {
this.next(false);
});
}
render() {
const { authenticated, Auth } = this.props;
if (Auth) {
if (authenticated) return <ComposedComponent {...this.props} />;
return null;
}
if (authenticated) return null;
return <ComposedComponent {...this.props} />;
}
}
return Authentication;
}