2017-05-03 17:46:12 +02:00
|
|
|
import React from 'react';
|
2017-04-20 20:05:15 +02:00
|
|
|
import { format, parse } from 'url';
|
2017-03-30 18:36:26 +02:00
|
|
|
|
2017-05-03 17:46:12 +02:00
|
|
|
const findCurrentProtocol = () => (
|
|
|
|
parse(window.location.href).protocol
|
|
|
|
);
|
|
|
|
|
|
|
|
const redirectToProtocol = (protocol, { appendSource, disable = false } = {}) => {
|
|
|
|
const currentProtocol = findCurrentProtocol();
|
|
|
|
|
|
|
|
if (protocol !== currentProtocol) {
|
|
|
|
if (disable === true) {
|
|
|
|
console.info(`forceProtocol: would have redirected from "${currentProtocol}" to "${protocol}"`);
|
|
|
|
} else {
|
|
|
|
const url = parse(window.location.href, true /* parse query string */);
|
|
|
|
url.protocol = protocol;
|
|
|
|
if (appendSource === true) {
|
|
|
|
url.query.source = currentProtocol;
|
|
|
|
}
|
|
|
|
window.location = format(url);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-03-30 18:36:26 +02:00
|
|
|
/**
|
|
|
|
* A Higher Order Component that forces the protocol to change on mount
|
|
|
|
*
|
|
|
|
* targetProtocol: the protocol to redirect to on mount
|
|
|
|
* sourceProtocol: the protocol to redirect back to on unmount
|
|
|
|
* disable: if true, the redirection will not happen but what should
|
|
|
|
* have happened will be logged to the console
|
|
|
|
*/
|
2017-04-20 20:05:15 +02:00
|
|
|
const forceProtocol = ({ targetProtocol = 'https', sourceProtocol, disable = false }) => WrappedComponent => (
|
2017-03-30 18:36:26 +02:00
|
|
|
class ForceProtocol extends React.Component {
|
|
|
|
static propTypes = {}
|
|
|
|
|
|
|
|
componentDidMount() {
|
2017-05-03 17:46:12 +02:00
|
|
|
redirectToProtocol(targetProtocol, { appendSource: true, disable });
|
2017-03-30 18:36:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
componentWillUnmount() {
|
|
|
|
if (sourceProtocol != null) {
|
2017-05-03 17:46:12 +02:00
|
|
|
redirectToProtocol(sourceProtocol, { appendSource: false, disable });
|
2017-03-30 18:36:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
|
|
|
return <WrappedComponent {...this.props} />;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
2017-04-20 20:05:15 +02:00
|
|
|
const protocols = {
|
|
|
|
http: 'http:',
|
|
|
|
https: 'https:',
|
|
|
|
};
|
|
|
|
|
|
|
|
const findSourceProtocol = (state, location) => {
|
|
|
|
if (/source=https/.test(window.location.search)) {
|
|
|
|
return protocols.https;
|
|
|
|
} else if (/source=http/.test(window.location.search)) {
|
|
|
|
return protocols.http;
|
|
|
|
} else if (state.project.serveSecure === true) {
|
|
|
|
return protocols.https;
|
|
|
|
}
|
|
|
|
|
|
|
|
return protocols.http;
|
|
|
|
};
|
2017-03-30 18:36:26 +02:00
|
|
|
|
|
|
|
export default forceProtocol;
|
2017-04-20 20:05:15 +02:00
|
|
|
export {
|
2017-05-03 17:46:12 +02:00
|
|
|
findCurrentProtocol,
|
2017-04-20 20:05:15 +02:00
|
|
|
findSourceProtocol,
|
2017-05-03 17:46:12 +02:00
|
|
|
redirectToProtocol,
|
2017-04-20 20:05:15 +02:00
|
|
|
protocols,
|
|
|
|
};
|