Created
April 16, 2017 05:55
-
-
Save hanpama/cc3be78254f03ed0aebf51c8333b7ee9 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 React, { PropTypes } from 'react'; | |
export class AuthProvider extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
login(email, password) { | |
const client = this.props.client; | |
return client.authenticate({ | |
strategy: 'local', | |
email, password | |
}) | |
.then(response => this.assignToken(response.accessToken)); | |
} | |
logout() { | |
const client = this.props.client; | |
return client.passport.logout() | |
.then(this.setState({ | |
email: null, userId: null | |
})); | |
} | |
signup(email, password) { | |
const users = this.props.client.service('users'); | |
return users.create({ email, password }) | |
.then(() => this.login(email, password)) | |
} | |
assignToken(token) { | |
return client.passport.verifyJWT(token) | |
.then(payload => client.service('users').get(payload.userId)) | |
.then(user => { | |
console.log(user); | |
this.setState({ | |
email: user.email, | |
userId: user.id | |
}) | |
}) | |
} | |
componentDidMount() { | |
const client = this.props.client; | |
client.passport.getJWT() | |
.then(token => { | |
if (token) { | |
return client.authenticate({ | |
strategy: 'jwt', accessToken: token | |
}) | |
.then(res => this.assignToken(res.accessToken)) | |
} else { | |
return Promise.resolve(null); | |
} | |
}) | |
} | |
getChildContext() { | |
return { | |
login: this.login.bind(this), | |
logout: this.logout.bind(this), | |
email: this.state.email, | |
userId: this.state.userId | |
} | |
} | |
render() { | |
return this.props.children; | |
} | |
} | |
AuthProvider.childContextTypes = { | |
login: PropTypes.func, | |
logout: PropTypes.func, | |
signup: PropTypes.func, | |
userId: PropTypes.string, | |
email: PropTypes.string, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment