mirror of
https://github.com/wassname/talk.git
synced 2026-07-28 11:27:05 +08:00
Listen for auth changes
This commit is contained in:
@@ -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 <Main onResetView={this.resetView} view={this.props.view} />;
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user