diff --git a/plugins/talk-plugin-auth/client/login/containers/Main.js b/plugins/talk-plugin-auth/client/login/containers/Main.js index b75030e0b..d99d40872 100644 --- a/plugins/talk-plugin-auth/client/login/containers/Main.js +++ b/plugins/talk-plugin-auth/client/login/containers/Main.js @@ -4,6 +4,10 @@ import Main from '../components/Main'; import { connect } from 'plugin-api/beta/client/hocs'; import { bindActionCreators } from 'redux'; import { setView } from '../actions'; +import { + setAuthToken, + handleSuccessfulLogin, +} from 'plugin-api/beta/client/actions/auth'; import * as views from '../enums/views'; class MainContainer extends React.Component { @@ -20,6 +24,7 @@ class MainContainer extends React.Component { componentDidMount() { this.resizeHeight(); + this.listenToStorageChanges(); } componentDidUpdate(prevProps) { @@ -27,6 +32,41 @@ class MainContainer extends React.Component { this.resizeHeight(); } } + + componentWillUnmount() { + this.unlisten(); + } + + listenToStorageChanges() { + window.addEventListener('storage', this.handleAuth); + } + + unlisten() { + window.removeEventListener('storage', this.handleAuth); + } + + // External logins store auth data into `auth`, we use it to detect + // a successful sign in. + handleAuth = e => { + if (e.key === 'auth') { + const { err, data } = JSON.parse(e.newValue); + if (err) { + console.error(err); + } else if (data && data.token) { + if (data.user) { + this.props.handleSuccessfulLogin(data.user, data.token); + } else { + this.props.setAuthToken(data.token); + } + this.unlisten(); + window.close(); + } else { + console.error('auth was set, but did not contain a token'); + } + localStorage.removeItem('auth'); + } + }; + render() { return
; } @@ -35,6 +75,8 @@ class MainContainer extends React.Component { MainContainer.propTypes = { view: PropTypes.string.isRequired, setView: PropTypes.func.isRequired, + handleSuccessfulLogin: PropTypes.func.isRequired, + setAuthToken: PropTypes.func.isRequired, }; const mapStateToProps = ({ talkPluginAuth: state }) => ({ @@ -45,6 +87,8 @@ const mapDispatchToProps = dispatch => bindActionCreators( { setView, + handleSuccessfulLogin, + setAuthToken, }, dispatch );