2015-10-06 18:28:15 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
import React from 'react';
|
|
|
|
import { History } from 'react-router';
|
|
|
|
|
|
|
|
import UserStore from '../../../stores/user_store';
|
|
|
|
import UserActions from '../../../actions/user_actions';
|
|
|
|
|
2015-10-09 13:51:21 +02:00
|
|
|
import AppConstants from '../../../constants/application_constants';
|
|
|
|
|
|
|
|
|
|
|
|
const { object } = React.PropTypes;
|
2015-10-06 18:28:15 +02:00
|
|
|
|
|
|
|
export default function RedirectProxyHandler({to, when}) {
|
|
|
|
return (Component) => {
|
|
|
|
return React.createClass({
|
2015-10-09 13:51:21 +02:00
|
|
|
propTypes: {
|
|
|
|
location: object
|
|
|
|
},
|
|
|
|
|
2015-10-06 18:28:15 +02:00
|
|
|
mixins: [History],
|
|
|
|
|
|
|
|
getInitialState() {
|
|
|
|
return UserStore.getState();
|
|
|
|
},
|
|
|
|
|
|
|
|
componentDidMount() {
|
|
|
|
UserStore.listen(this.onChange);
|
|
|
|
UserActions.fetchCurrentUser();
|
|
|
|
},
|
|
|
|
|
|
|
|
componentDidUpdate() {
|
|
|
|
this.redirectConditionally();
|
|
|
|
},
|
|
|
|
|
|
|
|
componentWillUnmount() {
|
|
|
|
UserStore.unlisten(this.onChange);
|
|
|
|
},
|
|
|
|
|
|
|
|
redirectConditionally() {
|
2015-10-09 13:51:21 +02:00
|
|
|
const { query } = this.props.location;
|
|
|
|
const { redirectAuthenticated, redirect } = query;
|
|
|
|
|
2015-10-06 18:28:15 +02:00
|
|
|
if(when === 'loggedIn' || when === 'loggedOut') {
|
|
|
|
|
|
|
|
let exprToValidate = when === 'loggedIn' ?
|
|
|
|
this.state.currentUser && this.state.currentUser.email :
|
|
|
|
this.state.currentUser && !this.state.currentUser.email;
|
2015-10-09 13:51:21 +02:00
|
|
|
|
2015-10-09 14:22:48 +02:00
|
|
|
if(exprToValidate) {
|
|
|
|
window.setTimeout(() => this.history.pushState(null, to, query));
|
|
|
|
} else if(!exprToValidate && when === 'loggedIn' && redirect) {
|
2015-10-09 13:51:21 +02:00
|
|
|
|
|
|
|
delete query.redirect;
|
|
|
|
window.setTimeout(() => this.history.pushState(null, '/' + redirect, query));
|
|
|
|
|
|
|
|
} else if(!exprToValidate && when === 'loggedOut' && redirectAuthenticated) {
|
|
|
|
/*
|
|
|
|
* redirectAuthenticated contains an arbirary path
|
|
|
|
* eg pieces/<id>, editions/<bitcoin_id>, collection, settings, ...
|
|
|
|
* hence transitionTo cannot be used directly
|
|
|
|
*/
|
|
|
|
window.location = AppConstants.baseUrl + redirectAuthenticated;
|
2015-10-06 18:28:15 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new Error('"loggedIn" and "loggedOut" are the only valid inputs for when');
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
onChange(state) {
|
|
|
|
this.setState(state);
|
|
|
|
},
|
|
|
|
|
|
|
|
render() {
|
|
|
|
return (
|
|
|
|
<Component {...this.props}/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|