Created
March 13, 2018 16:11
-
-
Save jeffwillette/70d7a46af82d9c9bc47c3d7e06b60034 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { compose, graphql } from 'react-apollo'; | |
import PropTypes from 'prop-types'; | |
import React from 'react'; | |
import { GET_USER, SET_USER } from '../../state/queries'; | |
import { getCookie } from '../../../utils'; | |
import LoginButton from './loginButton'; | |
import ProfileButton from './profileButton'; | |
class UserMenu extends React.Component { | |
static propTypes = { | |
messages: PropTypes.object, | |
user: PropTypes.object, | |
setUser: PropTypes.func | |
}; | |
// check the users auth cookie and set the global user state | |
checkAuthCookie = () => { | |
var cookie = getCookie('Authorization'); | |
if (cookie) { | |
// slice off the "Bearer " and then split into the three sections, taking middle | |
cookie = cookie.split(' ')[1].split('.')[1]; | |
cookie = atob(cookie); | |
cookie = JSON.parse(cookie); | |
const { user } = cookie; | |
this.props.setUser({ | |
name: user.GivenName, | |
avatarURL: user.AvatarURL, | |
email: user.Email, | |
ID: user.ID | |
}); | |
} | |
}; | |
render() { | |
const { messages, user } = this.props; | |
if (!user.ID) { | |
this.checkAuthCookie(); | |
} | |
return user.ID ? ( | |
<ProfileButton messages={messages} /> | |
) : ( | |
<LoginButton messages={messages} /> | |
); | |
} | |
} | |
const setUser = graphql(SET_USER, { | |
props: ({ mutate }) => ({ | |
setUser: ({ name, avatarURL, email, ID }) => { | |
mutate({ variables: { name, avatarURL, email, ID } }); | |
} | |
}) | |
}); | |
const getUser = graphql(GET_USER, { | |
props: ({ data }) => ({ user: data.user }) | |
}); | |
export default compose(setUser, getUser)(UserMenu); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment