Tuesday 6 June 2017

Facebook login in React Native

I am developing an app in React Native and I want to implement logging in with Facebook.

I have an API in Node.js where I handle the logic for users to log in, etc.

I use passport.js to let users log in with either Facebook or traditional Email.

I am opening an URL in my API with SafariView which is just a regular "WebView" directly in my app.

I have tried using the following code:

class FacebookButton extends Component {
  componentDidMount() {
    // Add event listener to handle OAuthLogin:// URLs
    Linking.addEventListener('url', this.handleOpenURL);

    // Launched from an external URL
    Linking.getInitialURL().then((url) => {
      if (url) {
        this.handleOpenURL({ url });
      }
    });
  }

  componentWillUnmount() {
    Linking.removeEventListener('url', this.handleOpenURL);
  }

  handleOpenURL({ url }) {
    // Extract stringified user string out of the URL
    const [, user_string] = url.match(/user=([^#]+)/);

    this.setState({
      // Decode the user string and parse it into JSON
      user: JSON.parse(decodeURI(user_string))
    });

    if (Platform.OS === 'ios') {
      SafariView.dismiss();
    }
  }

  openURL(url) {
    if (Platform.OS === 'ios') {
      SafariView.show({
        url: url,
        fromBottom: true,
      });
    } else {
      Linking.openURL(url);
    }
  }

  render() {
    return (
      <Button
        onPress={() => this.openURL('https://mywebsite.com/api/auth/facebook')}
        title='Continue with Facebook'
        ...

so I guess I will have to do the authentication on URL https://mywebsite.com/api/auth/facebook and then send the user to an url that looks something like OAuthLogin://..., but I am not entirely sure how to use it.

Can anyone help me move in the right direction?



via Jamgreen

No comments:

Post a Comment