Giter Site home page Giter Site logo

hungdev / react-native-instagram-login Goto Github PK

View Code? Open in Web Editor NEW
182.0 7.0 101.0 2.06 MB

a react native instagram login component (support android & ios). Pull requests are welcome!

Home Page: https://www.npmjs.com/package/react-native-instagram-login

JavaScript 49.56% Java 17.58% Objective-C 12.44% Ruby 15.00% Starlark 5.41%
react-native ios android instagram-login instagram instagram-api instagram-oauth auth authentication oauth

react-native-instagram-login's Introduction

React Native Instagram login

npm version npm downloads

IMPORTANT NOTES:

react-native-instagram-login version 2 switches to the Instagram Graph API.

If you want to use old version 1, please read docs

Install

npm install react-native-instagram-login react-native-webview --save

Then link the native iOS package:

npx pod-install

Setup (React Native < 0.60.0):

Automatic (recommended)

react-native link

with manual, see more

How to get appId, appSecret of instagram?

Simple setup, you only need to complete first 3 steps.

Then go to Instagram> Basic Display> Instagram App ID field

This is going to give you an access_token, which one can be used on the new Graph Api, go to https://developers.facebook.com/docs/instagram-basic-display-api/guides/getting-profiles-and-media for docs.

Usage:

For function component:

import React, { useState, useRef } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import InstagramLogin from 'react-native-instagram-login';
import CookieManager from '@react-native-community/cookies';

export default function App() {
  const insRef = useRef();
  const [token, setToken] = useState(null);

  const onClear = () => {
    CookieManager.clearAll(true)
      .then((res) => {
        setToken(null);
      });
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => insRef.current.show()}>
        <Text style={{ color: 'white', textAlign: 'center' }}>Login now</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.btn, { marginTop: 10, backgroundColor: 'green' }]}
        onPress={onClear}>
        <Text style={{ color: 'white', textAlign: 'center' }}>Logout</Text>
      </TouchableOpacity>
      <Text style={{ margin: 10 }}>Token: {token}</Text>
      <InstagramLogin
        ref={insRef}
        appId='your-app-id'
        appSecret='your-app-secret'
        redirectUrl='your-redirect-Url'
        scopes={['user_profile', 'user_media']}
        onLoginSuccess={(token) => setToken(token)}
        onLoginFailure={(data) => console.log(data)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  btn: {
    borderRadius: 5,
    backgroundColor: 'orange',
    height: 30,
    width: 100,
    justifyContent: 'center',
    alignItems: 'center',
  }
});

For Class component

import React, { Component } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import InstagramLogin from 'react-native-instagram-login';
import CookieManager from '@react-native-community/cookies';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      token: '',
    };
  }

  setIgToken = (data) => {
    console.log('data', data)
    this.setState({ token: data.access_token })
  }

  onClear() {
    CookieManager.clearAll(true)
      .then((res) => {
        this.setState({ token: null })
      });
  }
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <TouchableOpacity
          style={styles.btn}
          onPress={() => this.instagramLogin.show()}>
          <Text style={{ color: 'white', textAlign: 'center' }}>Login now</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.btn, { marginTop: 10, backgroundColor: 'green' }]}
          onPress={() => this.onClear()}>
          <Text style={{ color: 'white', textAlign: 'center' }}>Logout</Text>
        </TouchableOpacity>
        <Text style={{ margin: 10 }}>Token: {this.state.token}</Text>
        {this.state.failure && (
          <View>
            <Text style={{ margin: 10 }}>
              failure: {JSON.stringify(this.state.failure)}
            </Text>
          </View>
        )}
        <InstagramLogin
          ref={ref => (this.instagramLogin = ref)}
          appId='your-app-id'
          appSecret='your-app-secret'
          redirectUrl='your-redirect-Url'
          incognito={false}
          scopes={['user_profile', 'user_media']}
          onLoginSuccess={this.setIgToken}
          onLoginFailure={(data) => console.log(data)}
          language='tr' //default is 'en' for english
        />
      </View>
    );
  }
}


const styles = StyleSheet.create({
  btn: {
    borderRadius: 5,
    backgroundColor: 'orange',
    height: 30,
    width: 100,
    justifyContent: 'center',
    alignItems: 'center',
  }
});

Props

Property Type Description
appId PropTypes.string Instagram client_id
appSecret PropTypes.string Instagram client_secret
responseType PropTypes.string 'code' or 'token', default 'code'
scopes PropTypes.array Login Permissions, default ['user_profile', 'user_media']
redirectUrl PropTypes.string Your redirectUrl
incognito PropTypes.boolean Incognito true/false
onLoginSuccess PropTypes.func Function will be call back on success
onLoginFailure PropTypes.func Function will be call back on error
onClose PropTypes.func Function will be call back on close modal
modalVisible PropTypes.bool true or false
renderClose PropTypes.func Render function for customize close button
containerStyle PropTypes.object Customize container style
wrapperStyle PropTypes.object Customize wrapper style
closeStyle PropTypes.object Customize close style
language PropTypes.string Override language of modal,alpha-2 eg:"es","tr" etc.

Server side explicit: Discuss here

If you dont want to expose appSecret on the client, you dont need to pass appSecret props on client. And onLoginSuccess will callback a code.

On your server (Backend) you have to call an api https://api.instagram.com/oauth/access_token with method post to exchange the code for a token, and params:

client_id: your-app-id
client_secret: your-app-secret
grant_type: 'authorization_code'
redirect_uri: your-redirect-url
code: code-get-from-onLoginSuccess-props

For example

The response will look like this:

{
  "access_token": "IGQVJ...",
  "user_id": 17841405793187218
}

Logout

To logout use clear cookies by using https://github.com/react-native-community/cookies

import CookieManager from '@react-native-community/cookies';

  logout() {
    CookieManager.clearAll(true)
      .then((res) => {
        console.log('CookieManager.clearAll =>', res);
        this.setState({ token: '' })
      });
  }

Contributing

Special thanks @AlbertoIHP for v2.

This project exists thanks to all the people who contribute. [Contribute].

Pull request

Pull requests are welcome!

react-native-instagram-login's People

Contributors

akhil-tripathi avatar amirdoreh avatar areazus avatar dacre-denny avatar dlas1212 avatar hungdev avatar jacobogart avatar jaredude avatar jkmf avatar kh1msh0 avatar naturalclar avatar tryhardfifi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-instagram-login's Issues

Scope error when logging in

Error Received:
{“error_type”: “OAuthException”, “code”: 400, “error_message”: “Invalid scope field(s): public_content”}

Solution: Change scope from "public_content" to "basic"

Chỉ login được với tài khoản dùng để đăng kí client id

Khi mình dùng ex của bạn để login( đã thay client id... bằng id của mình) nhưng khi login nó chỉ login được với tài khoản dùng để đăng ký client id.. còn với tài khoản khác thì hiện lỗi : you are not a sandbox user or this client.
Mong bác giúp mình khắc phục lỗi này với

Webview always logged.

I would like to be able to log out and log back in with another user.
It seems that webview remember login.

Any ideas?
Thank you!

V2.0.0 against Facebook TOS

The new version is using the basic display api for authentication, which is against Facebooks rules.

"If your app uses API data to authenticate users, it will be rejected during App Review."

No production app will be able to use this like that - without taking the risk to get banned at any time.

Did anyone actually test this? Is this plugin basically useless these days?
You have to go into review for the user_profile scope and add a screencast. Facebook is rejecting this use case.

Random error loading login page "too many HTTP redirects"

Most of the time this works great! However, occasionally I receive the following error when the modal appears:

Error loading page
Domain: NSURLErrorDomain
Error Code: -1007
Description: too many HTTP redirects

I am on version 1.0.8.

This error clears after reloading the app and waiting a bit. Overall not a good experience for our users though.
IMG_4661

Clarification about the login webview of instagram

I am using the react-native-instagram-login package for sign in my app. The login webview shows only Username and password. But now it redirecting to different UI.

Initially the webview was like this. Now it redirecting to the below attached UI. Kindly clarify

screen shot 2018-06-06 at 10 45 18 am

Proposal of channel discussion

Hi, I took the liberty of creating a public chat in the discord facing React-Native. With the intention of uniting the React-native community and improving communication.

I'm creating a channel for public discussions about your project. To avoid flooding "chat" on your github. If you can support the initiative, great! Just share the link below xD

I'm adding RN only projects to this public chat service. And I commit myself to manage chat rooms.
You would just need to observe the chat related to your project.

here's the link
https://discord.gg/RvFM97v

Cheers.

Android not working

on ios I get the data
but for some reason on android it stoped working a few days ago

all i get is a pop up screen of my reirectUrl and no token provided

Webview modal is not closing

After I get token, I have to close modal or something close automatically?
Here is my code:

<InstagramLogin
	ref={ref => this.instagramLogin = ref}
	clientId={INSTA_CLIENT_ID}
	scopes={['public_content']}
	onLoginSuccess={(instagramToken) => {
		this.instagramLogin.hide()
		this.setState({ instagramToken });
		alert(instagramToken);
	}}
	onLoginFailure={(data) => {
		console.log(data);
	}}
/>

Dev Info:

React Native Environment Info:
 System:
   OS: macOS High Sierra 10.13.6
   CPU: (4) x64 Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
   Memory: 664.43 MB / 8.00 GB
   Shell: 3.2.57 - /bin/bash
 Binaries:
   Node: 10.13.0 - /usr/local/bin/node
   npm: 6.4.1 - /usr/local/bin/npm
   Watchman: 4.9.0 - /usr/local/bin/watchman
 SDKs:
   iOS SDK:
     Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
   Android SDK:
     API Levels: 23, 25, 26, 27, 28
     Build Tools: 26.0.3, 27.0.3, 28.0.3
     System Images: android-26 | Google APIs Intel x86 Atom_64, android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom
 IDEs:
   Android Studio: 3.2 AI-181.5540.7.32.5056338
   Xcode: 10.0/10A255 - /usr/bin/xcodebuild
 npmPackages:
   react: 16.5.0 => 16.5.0 
   react-native: https://github.com/expo/react-native/archive/sdk-31.0.1.tar.gz => 0.57.1 
 npmGlobalPackages:
   eslint-plugin-react-native: 3.5.0
   react-native-cli: 2.0.1

Testing Device: iOS simulator

After token alert come up, automatically disappear and app crashed. close button also not working.

How is supposed to work?

I can't make it work at all.
The modal appears, put the info, and it just give me lots of promises warnings, but that's all, it does nothing, doesn't return a token or any kind of data.
And after you login, the only thing you get is your instagram page, but no token, no nothing.

I'm using Macbook pro, OSX 10.13.6.
Node version 10.10.0
"react": "16.4.1",
"react-native": "0.56.0",
"react-native-instagram-login": "1.0.7",

no response when completed

i have the code below, like the example. it does not log anything after redirect?

    <View>
        <TouchableOpacity onPress={()=> this.instagramLogin.show()}>
            <Text style={{color: 'black', margin: '20%'}}>Login</Text>
        </TouchableOpacity>
        <InstagramLogin
            ref= {ref => this.instagramLogin= ref}
            responseType="token"
            clientId=''
            scopes={['public_content', 'follower_list']}
            onLoginSuccess={(token) => console.log(token)}
            onLoginFailure={(data) => console.log(data)}
            onClose={(data) => console.log(data)}
            redirectUrl="https://us-central1-scautapp.cloudfunctions.net/url_get&response_type=token"
        />
    </View>

Redirect uri not matches?

What would be the redirect uri?

On instagram when I tried to register a ne
oauth_exce
w client it ask me to enter redirect uri.

Error on login webview

After I login I get redirected to the following:
screenshot_20180522-155046

I tried deleting cookies but the problem still exists. any ideas?

App redirect user to "redirectUrl"

I am using this library with react native 0.57.3 but it redirect user to "redirectUrl", in my case it is redirecting user to "google.com" url which is my redirect url.

please any one can help me to solve this issue.

Thanks!

How do you logout?

I tried the logging out as said in the documentation but got undefined is not an object (evaluating 'CookieManager.clearCookies'). I have attached the screenshot. Can anyone please help me with this?
screen shot 2017-10-09 at 5 54 57 pm

Change language of the webview

Hi,

I'm asking myself if we can change the language of the instagram webview (like put it in french). I'm trying to add ?hl=fr in the link, but it doesn't work. That could be cool to manage from the component. Any idea ? Is it possible ?

Thanks

How to get user profile(name, profile picture)

I m using the latest version but I m getting a success response with this data

{"access_token":"IGQVJXVE15WEpxY2ZAlSkldfsfcxqV3M3NWVhVmZAMb2NrT29WcWZAIU3FWWjdoUUNaU0tRTjsdasdhYZATVHVmxQOWlBMnVJejRkbGss9iZAmxDTHN3aUp4SEdOTmZAYa0pBT3RTb0ZAPenpOcGo2asdUXVxdDczasdaQUxlUTQ3QkhFZA1ktTkNFN2RfNWJv","user_id":178xxxxxxxxxx}

but I need the user's name and profile picture, so could you please help me how to get this information

I cannot change Instagram Login account after login

Hi, Thank you for your effort with this package.
It helped me much with my work for instagram login.
But I have found an issue on webview.
The webview in the modal works fine at the first login.
But after login successfully, if I try to use another account to login, webview doesn't show the Instagram Login page.
So I cannot change to another account.
As I checked the code there was a code block to change key which is responsible for refreshing webview.
But it doesn't work properly. This is the code.
... .... ...
const { url } = webViewState
const { key } = this.state
if (webViewState.title === 'Instagram' && webViewState.url ===
'https://www.instagram.com/') {
this.setState({ key: key + 1 })
}
... ... ...
I think the issue is related to title and webViewState.url.
As I checked the title and url when load instagram page, the title was 'Login Instagram' and the url was "https://api.instagram.com/oauth/authorize/?client_id=XXXXX&redirect_uri=XXXXX&response_type=token".
So the key hadn't changed.
I hope you please check the code and if this is a bug, please fix asap.
Thank you and regards.
insta1
insta2

this.webView.injectJavascript is not a function

I get this error. Any ideas? This is the code below

import React, { Component } from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  Dimensions,
  PixelRatio,
  AsyncStorage
} from 'react-native';
import { Actions, ActionConst } from 'react-native-router-flux';
import GoogleAnalytics from 'react-native-google-analytics-bridge';
import Meteor from 'react-native-meteor';
import styles from '../../styles/styles';
import InstagramLogin from 'react-native-instagram-login';
import CookieManager from 'react-native-cookies';

export class InstagramLoginButton extends Component {
  constructor(props) {
    super(props);

    this.state = {
      token: null
    };

    this.loginSucess = this.loginSucess.bind(this);
    this.logout = this.logout.bind(this);
  }

  componentDidMount() {
    Meteor.call('getInstagramToken', Meteor.user()._id, (err, result) => {
      if (!err) {
        this.setState({
          token: result
        });
        Meteor.call('accessUserInfo', result, (err2, res) => {
          if (res === -1) {
            this.setState({
              token: null
            });
            this.logout();
          }
        });
      }
    });
  }

  loginSucess(token) {
    this.setState(
      {
        token: token
      },
      () => {
        Meteor.call('addInstagramToken', Meteor.user()._id, token);
      }
    );
  }

  logout() {
    CookieManager.clearAll().then(res => {
      this.setState({
        token: null
      });
      Meteor.call('removeInstagramToken', Meteor.user()._id);
    });
  }

  render() {
    if (!this.state.token) {
      return (
        <View>
          <TouchableOpacity
            style={[styles.loginButton, { backgroundColor: 'white' }]}
            onPress={() => {
              this.refs.instagramLogin.show();
            }}
          >
            <Text
              style={{
                fontFamily: 'Montserrat-Light',
                color: '#424949',
                backgroundColor: 'transparent',
                fontSize: 14
              }}
            >
              C O N N E C T T O I N S T A G R A M
            </Text>
          </TouchableOpacity>
          <InstagramLogin
            ref='instagramLogin'
            clientId='clientid'
            scopes={['public_content']}
            onLoginSuccess={token => {
              this.loginSucess(token);
            }}
            redirectUrl='redirecturl'
          />
        </View>
      );
    } else {
      return (
        <View>
          <TouchableOpacity
            style={[styles.loginButton, { backgroundColor: 'white' }]}
            onPress={() => {
              this.logout();
            }}
          >
            <Text
              style={{
                fontFamily: 'Montserrat-Light',
                color: '#424949',
                backgroundColor: 'transparent',
                fontSize: 14
              }}
            >
              {' '}
              I N S T A G R A M L O G O U T
            </Text>
          </TouchableOpacity>
        </View>
      );
    }
  }
}

Connection Issue

Connecting to Instagram in most cases works, however randomly the app cannot connect and instead shows the Instagram logo without any fields to enter. Did anyone have this issue before?

Using the latest version of react-native-webview and react-native-instagram-login.
onLoginFailure doesn't get called.

IMG_1801

doesn't work with expo any more

Since last commit Expo compatibility has been broken.
Expo developers can't do: react-native link react-native-webview

Invariant Violation: requireNativeComponent: "RNCWebView" was not found in the UIManager.

Webview don't display Instagram Login Page at the second Longin attempt.

Hi, Thank you for your effort with stuff.
I am building iOS app with ReactNative 0.59.8.
The Instagram login component works fine and shows the Login page on webview successfully.
But the problem is here.
I failed to login due to the redirect_url issue, so I closed modal and tried again.
But the web view didn't show the login page, showed only loading spinner image.
In order to log in again, I had to uninstall the app from the device.
I want to know what the cause was.
Hope to be fixed asap if this is an issue.
Thank you.

Error Compile react-native run-android

when i run-android give this error

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':react-native-webview'.

Could not resolve all artifacts for configuration ':react-native-webview:classpath'.
Could not resolve org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.11.
Required by:
project :react-native-webview
> Could not resolve org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.11.
> Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.3.11/kotlin-gradle-plugin-1.3.11.pom'.
> Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.3.11/kotlin-gradle-plugin-1.3.11.pom'.
> sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

package.json
"dependencies": {
"axios": "^0.19.0",
"react": "16.8.3",
"react-native": "0.59.3",
"react-native-elements": "^1.1.0",
"react-native-instagram-login": "^1.1.1",
"react-native-vector-icons": "^6.0.0",
"react-navigation": "^2.11.2"
}

Exposing secret on the client side is bad practice

I was looking at using your package, but when I read your code and compare it with the manual it says that you should not share the app_secret client side. It suggests you should use the client side implicit authentication. link

Are you aware of this? This looks like an issue that is resolvable. The implicit authentication does not need the secret.

How to resolve "RNCWKWebView" was not found in the UI Manager

1. Run “npm install --save react-native-instagram-login”
2. Delete the “react-native-webview” folder from node_modules.
3. Run “npm install --save react-native-webview”
4. Remove “/node_modules/react-native-webview” folder and react-native-webview dependency from package.json (all inside react-native-instagram-login folder).
5. Type in “react-native link react-native-webview”
6. Navigate to the “iOS” folder and type in “pod install”

None of the solutions I found on SO or GitHub worked for me. So I finally figured out a solution that works for me.

Invalid scope response

hi,
when i have submit id password then json response with 'invalid scope " error!!

below code snippet
ver 2.0.0

<InstagramLogin
ref={ref => (this.instagramLogin = ref)}
appId={config.instaAppId}
appSecret={config.instaappSecret}
redirectUrl={config.instaRedirectURL}
scopes={['user_profile', 'user_media']}
onLoginSuccess={token => {
this.handleInstaLogin(token);
this.setState({ isLoginViaWhich: 'instagram' });
}}
onLoginFailure={data => console.log(data)}
/>

Implicit authentication is disabled

this is my Component:

<InstagramLogin
ref='instagramLogin'
clientId='eeeee'
redirectUrl='eee'
scopes={['basic']}
onLoginSuccess={(token) => console.log(token)}
onLoginFailure={(data) => console.log(data)}
/>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.