Skip to content

Instantly share code, notes, and snippets.

@dsdenes
Last active April 19, 2017 08:37
Show Gist options
  • Save dsdenes/f65746c53b679dce8914b54a6648c08a to your computer and use it in GitHub Desktop.
Save dsdenes/f65746c53b679dce8914b54a6648c08a to your computer and use it in GitHub Desktop.
import * as firebase from 'firebase';
const actionNames = {
INPUT_CHANGED: 'INPUT_CHANGED',
TOGGLE_NOTIFICATION: 'TOGGLE_NOTIFICATION',
LOGGEDIN: 'LOGGEDIN',
LOGGEDOUT: 'LOGGEDOUT',
LOGIN_ERROR: 'LOGIN_ERROR'
}
export function checkAuthStateChange() {
return async (dispatch) => {
const user = await (new Promise(resolve => firebase.auth().onAuthStateChanged(resolve)));
if (user) {
const {
email,
displayName
} = user;
dispatch(loggedin({email, displayName}));
} else {
dispatch(loggedout(user));
}
}
}
export function login() {
return async (dispatch) => {
try {
const provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
await firebase.auth().signInWithPopup(provider);
dispatch(checkAuthStateChange());
} catch (err) {
dispatch(loginError(err));
}
}
}
function loggedin(user, token) {
return {
type: actionNames.LOGGEDIN,
user,
token
}
}
function loggedout(user) {
return {
type: actionNames.LOGGEDOUT,
user
}
}
function loginError(error) {
return {
type: actionNames.LOGIN_ERROR,
error
}
}
export function logout() {
return async dispatch => {
firebase.auth().signOut();
dispatch(checkAuthStateChange());
}
}
export function toggleLogin() {
return (dispatch, getState) => {
const { email } = getState();
if (email) {
dispatch(logout());
} else {
dispatch(login());
}
}
}
const initialState = null;
export default (state, action) => {
if (typeof state === 'undefined') {
state = initialState;
}
switch (action.type) {
case 'LOGGEDIN':
return Object.assign({}, state, action.user);
case 'LOGGEDOUT':
return initialState.user;
default:
return state;
}
}
import React from 'react';
import { connect } from 'react-redux';
import { toggleLogin } from './auth-actions';
const LoginButton = ({loggedin, toggleLogin}) => (
<button
href="#"
onClick={toggleLogin}
>{loggedin ? 'Sign out' : 'Sign in'}</button>
);
const mapStateToProps = (state, ownProps) => ({
loggedin: !!(state.email),
});
const mapDispatchToProps = (dispatch) => {
return {
toggleLogin: event => dispatch(toggleLogin())
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginButton);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment