Example #1
0
    def get(self):
        instagram_client = InstagramAPI(**settings.INSTAGRAM_CONFIG)

        code = self.request.get("code")
        access_token = instagram_client.exchange_code_for_access_token(code)

        instagram_client = InstagramAPI(access_token = access_token)

        user = instagram_client.user("self")

        profiles = Profile.all()
        profiles.filter("ig_user_id = ", user.id)
        profile = (profiles.get() or Profile())

        profile.full_name = (user.full_name or user.username)
        profile.ig_user_id = user.id
        profile.ig_username = user.username
        profile.ig_access_token = access_token
        profile.put()

        cookieutil = LilCookies(self, settings.COOKIE_SECRET)
        cookieutil.set_secure_cookie(
                name = "ig_user_id",
                value = user.id,
                expires_days = 365)

        self.redirect("/connect")
def get_token(creds, scope=['basic', 'comments', 'public_content']):
    # Fix Python 2.x.
    try:
        import __builtin__
        input = getattr(__builtin__, 'raw_input')
    except (ImportError, AttributeError):
        pass

    client_id = creds['client_id']
    client_secret = creds['client_secret']
    redirect_uri = creds['redirect_uri']

    print 'Connecting to InstagramAPI'

    api = InstagramAPI(client_id=client_id,
                       client_secret=client_secret,
                       redirect_uri=redirect_uri)

    print 'Obtaining auth url'
    redirect_uri = api.get_authorize_login_url(scope=scope)
    webbrowser.open_new_tab(redirect_uri)

    code = (str(input(
                "Login in, then paste in code in query string after redirect: "
                ).strip()))
    access_token = api.exchange_code_for_access_token(code)
    return access_token[0]
class client_packet:
    def __init__(self, client_id, client_secret, redirect_uri, begin_user_id):
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect_uri = redirect_uri
        self.begin_user_id = begin_user_id
        print('creating new client...')

    def Access_token(self, flag):
        if flag:
            scope = []
            self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret,
                                    redirect_uri=self.redirect_uri)
            redirect_uri = self.api.get_authorize_login_url(scope=scope)

            print("Visit this page and authorize access in your browser:\n", redirect_uri)

            code = input("Paste in code in query string after redirect: ").strip()
            print('client_id: ' + self.api.client_id)
            print('client_secret: ' + self.api.client_secret)
            self.access_token = self.api.exchange_code_for_access_token(code)
            print(self.access_token)
        else:
            self.access_token = 'Insert Your actual Client Access token to not repeath this again and again'

        return self.access_token
def getToken():
   if not os.path.exists('accessToken.txt'):
      print("The first time you run this program, it will need to obtain access to Instagram via")
      print("a token generated from your account. This token will only require basic (read-only)")
      print("access to your account in order to download images. Afterwards, the token will be")
      print("stored in \'accessToken.txt\'. If you ever have problems with this script, delete")
      print("\'accessToken.txt\' and run this script again to regenerate the token.")
       
      client_id = 'd051ace450314ccd8d86fdbff2410a87'
      client_secret = '91c43e9262494f4c82c887a88b21068c'
      redirect_uri = 'http://localhost:8515/oauth_callback'
      scope = ["basic"]
       
      api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
      redirect_uri = api.get_authorize_login_url(scope = scope)
       
      print("Python will now attempt to open the following URL in a web browser:")
      print(redirect_uri)
      print("When it loads, it will go to an invalid URL that looks like")
      print("http://localhost:8515/oauth_callback?code=XXXXXXXXXXXXXXXXXXX")
      print('Copy and paste the code from the address bar (the XXXs in the above example) below.')
      webbrowser.open(redirect_uri)
      
      print("Paste in code in query string after redirect: "),
      code = (str(raw_input().strip()))
      
      access_token = api.exchange_code_for_access_token(code)
      print ("access token: " )
      print (access_token)
      pickle.dump( access_token, open( "accessToken.txt", "wb" ) )
Example #5
0
 def get_redirect_url(self, *args, **kwargs):
     code = self.request.GET.get("code")
     settings.use_editable()
     site = Site.objects.get_current()
     
     conf = {
         "redirect_uri": "http://{0}{1}".format(site.domain, reverse('instagram_oauth')),
         "client_id": settings.INSTAGRAM_CLIENT_ID,
         "client_secret": settings.INSTAGRAM_CLIENT_SECRET,
     }
     unauthorized_api = InstagramAPI(**conf)
     logger.debug(unauthorized_api)
     access_token = unauthorized_api.exchange_code_for_access_token(code)
     try:
         instagram = Instagram.objects.all()[0]
         instagram.access_token = access_token[0]
         instagram.user_id = int(access_token[1]['id'])
         instagram.full_name = access_token[1]['full_name']
         instagram.username = access_token[1]['username']
         instagram.save()
     except IndexError:
         Instagram.objects.create(access_token=access_token[0],
                                  user_id=int(access_token[1]['id']),
                                  full_name=access_token[1]['full_name'],
                                  username=access_token[1]['username'])
     return "/admin/"
Example #6
0
 def get_redirect_url(self, *args, **kwargs):
     code = self.request.GET.get("code")
     settings.use_editable()
     site = Site.objects.get_current()
     conf = {
         "redirect_uri":
         "http://{0}{1}".format(site.domain, reverse('instagram_oauth')),
         "client_id":
         settings.INSTAGRAM_CLIENT_ID,
         "client_secret":
         settings.INSTAGRAM_CLIENT_SECRET,
     }
     unauthorized_api = InstagramAPI(**conf)
     logger.debug(unauthorized_api)
     access_token = unauthorized_api.exchange_code_for_access_token(code)
     try:
         instagram = Instagram.objects.all()[0]
         instagram.access_token = access_token[0]
         instagram.user_id = int(access_token[1]['id'])
         instagram.full_name = access_token[1]['full_name']
         instagram.username = access_token[1]['username']
         instagram.save()
     except IndexError:
         Instagram.objects.create(access_token=access_token[0],
                                  user_id=int(access_token[1]['id']),
                                  full_name=access_token[1]['full_name'],
                                  username=access_token[1]['username'])
     return "/admin/"
Example #7
0
    def get(self):
        instagram_client = InstagramAPI(**settings.INSTAGRAM_CONFIG)

        code = self.request.get("code")
        access_token = instagram_client.exchange_code_for_access_token(code)

        instagram_client = InstagramAPI(access_token=access_token)

        user = instagram_client.user("self")

        profiles = Profile.all()
        profiles.filter("ig_user_id = ", user.id)
        profile = (profiles.get() or Profile())

        profile.full_name = (user.full_name or user.username)
        profile.ig_user_id = user.id
        profile.ig_username = user.username
        profile.ig_access_token = access_token
        profile.put()

        cookieutil = LilCookies(self, settings.COOKIE_SECRET)
        cookieutil.set_secure_cookie(name="ig_user_id",
                                     value=user.id,
                                     expires_days=365)

        self.redirect("/connect")
class InstagramAuth(OAuthRequestHandler):
    scope = [
        'basic',
        'comments',
        'likes',
        'relationships',
    ]

    def initialize(self):
        super(InstagramAuth, self).setProvider("instagram")
        consumer_key = self.application.settings['instagram_oauth']['key']
        consumer_secret = \
            self.application.settings['instagram_oauth']['secret']
        redir_uri = "{0}/auth/instagram".format(
            self.application.settings['base_url'])
        self.api = InstagramAPI(
            client_id=consumer_key,
            client_secret=consumer_secret,
            redirect_uri=redir_uri,
        )

    def startFlow(self):
        self.redirect(self.api.get_authorize_login_url(scope=self.scope))

    @gen.coroutine
    def handleAuthCallBack(self, code, user_id):
        access_info = self.api.exchange_code_for_access_token(code)

        # Confirmation & Saving token
        yield save_token(
            provider="instagram",
            user_id = user_id,
            token_data=access_info
        )
Example #9
0
class InstagramAuth(OAuthRequestHandler):
    scope = [
        'basic',
        'comments',
        'likes',
        'relationships',
    ]

    def initialize(self):
        super(InstagramAuth, self).setProvider("instagram")
        consumer_key = self.application.settings['instagram_oauth']['key']
        consumer_secret = \
            self.application.settings['instagram_oauth']['secret']
        redir_uri = "{0}/auth/instagram".format(
            self.application.settings['base_url'])
        self.api = InstagramAPI(
            client_id=consumer_key,
            client_secret=consumer_secret,
            redirect_uri=redir_uri,
        )

    def startFlow(self):
        self.redirect(self.api.get_authorize_login_url(scope=self.scope))

    @gen.coroutine
    def handleAuthCallBack(self, code, user_id):
        access_info = self.api.exchange_code_for_access_token(code)

        # Confirmation & Saving token
        yield save_token(provider="instagram",
                         user_id=user_id,
                         token_data=access_info)
def login_instagram(request):
    host = request.get_host()
    if ':' in host:  # nginx
        host, _ = host.split(':')

    instagram_url = os.environ.get('INSTAGRAM')
    redirect_uri = f"{host}/accounts/login_instagram/"

    # user authorizes app
    code = request.GET.get('code')
    if code is not None:
        CONFIG = {
            'client_id': settings.CLIENT_ID,
            'client_secret': settings.CLIENT_SECRET,
            'redirect_uri': 'http://localhost:8515/oauth_callback'
        }
        unauthenticated_api = InstagramAPI(**CONFIG)
        oauth_token = unauthenticated_api.exchange_code_for_access_token(code)
        instagram_account = oauth_token['user']['username']
        if not AccessToken.objects.filter(uid=instagram_account).exists():
            # no access_token found XXX
            AccessToken.objects.create(
                uid=instagram_account,
                access_token=oauth_token['access_token'])
        user = authenticate(uid=instagram_account)
        if user is not None:
            auth_login(request, user)
        return redirect('/')

    client_secret = os.environ.get('CLIENT_SECRET')
    url = "https://" + instagram_url + \
        "/oauth/authorize/?client_id=" + client_secret + "&redirect_uri=" + \
        redirect_uri + "&response_type=code&scope=basic+public_content+follower_list+relationships+likes'"
    return redirect(url)
Example #11
0
    def runConfigWizard(self):
        try:
            api = InstagramAPI(
                client_id=self.options_string['hidden_client_id'],
                client_secret=self.options_string['hidden_client_secret'],
                redirect_uri=self.options_string['redirect_uri'])
            url = api.get_authorize_login_url()

            self.wizard.setWindowTitle('Instagram plugin configuration wizard')
            page1 = QWizardPage()
            layout1 = QVBoxLayout()
            txtArea = QLabel()
            txtArea.setText(
                'Please copy the following link to your browser window. \n ' +
                'Once you authenticate with Instagram you will be redirected to '
                +
                'www.geocreepy.com and get your token. Copy the token to the input field below:'
            )
            urlArea = QLineEdit()
            urlArea.setObjectName('urlArea')
            urlArea.setText(url)
            inputLink = QLineEdit()
            inputLink.setObjectName('inputLink')
            labelLink = QLabel('Your token value:')
            openInBrowserButton = QPushButton('Open in browser')
            openInBrowserButton.clicked.connect(
                functools.partial(self.openLinkInBrowser, url))
            layout1.addWidget(txtArea)
            layout1.addWidget(urlArea)
            layout1.addWidget(openInBrowserButton)
            layout1.addWidget(labelLink)
            layout1.addWidget(inputLink)
            page1.setLayout(layout1)
            self.wizard.addPage(page1)
            self.wizard.resize(600, 400)
            if self.wizard.exec_():
                c = str(inputLink.text())
                if c:
                    try:
                        access_token = api.exchange_code_for_access_token(
                            code=c)
                        self.options_string[
                            'hidden_access_token'] = access_token[0]
                        self.saveConfiguration(self.config)
                    except Exception as err:
                        logger.error(err)
                        self.showWarning(
                            'Error Getting Access Token',
                            'Please verify that the link you pasted was correct. '
                            'Try running the wizard again.')
                else:
                    self.showWarning(
                        'Error Getting Access Token',
                        'Please verify that the link you pasted was correct. Try running the wizard again.'
                    )

        except Exception as err:
            logger.error(err)
            self.showWarning('Error', 'Error was {0}'.format(err))
Example #12
0
File: app.py Project: sicXnull/moa
def instagram_oauthorized():

    code = request.args.get('code', None)

    if code:

        client_id = app.config['INSTAGRAM_CLIENT_ID']
        client_secret = app.config['INSTAGRAM_SECRET']
        redirect_uri = url_for('instagram_oauthorized', _external=True)
        api = InstagramAPI(client_id=client_id,
                           client_secret=client_secret,
                           redirect_uri=redirect_uri)

        try:
            access_token = api.exchange_code_for_access_token(code)
        except OAuth2AuthExchangeError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))
        except ServerNotFoundError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))

        if 'bridge_id' in session:
            bridge = get_or_create_bridge(bridge_id=session['bridge_id'])

            if not bridge:
                pass  # this should be an error
        else:
            bridge = get_or_create_bridge()

        bridge.instagram_access_code = access_token[0]

        data = access_token[1]
        bridge.instagram_account_id = data['id']
        bridge.instagram_handle = data['username']

        user_api = InstagramAPI(access_token=bridge.instagram_access_code,
                                client_secret=client_secret)

        try:
            latest_media, _ = user_api.user_recent_media(
                user_id=bridge.instagram_account_id, count=1)
        except Exception:
            latest_media = []

        if len(latest_media) > 0:
            bridge.instagram_last_id = datetime_to_timestamp(
                latest_media[0].created_time)
        else:
            bridge.instagram_last_id = 0

        db.session.commit()

    else:
        flash("Instagram authorization failed")

    return redirect(url_for('index'))
Example #13
0
 def __init__(self, code=None):
     # token = self.get_token(code)
     api = InstagramAPI(
         client_id="8b6d72cafbfb449fb5330c520b5102ed",
         client_secret="6253323e9e064c10a397698f49c224b3",
         redirect_uri="http://127.0.0.1:8000",
     )
     token, user = api.exchange_code_for_access_token(code)
     self.api = InstagramAPI(access_token=token)
Example #14
0
def instagram_redirect(code):
    api = InstagramAPI(
        client_id=settings.CLIENT_ID,
        client_secret=settings.CLIENT_SECRET,
        redirect_uri=settings.HOST + INSTAGRAM_REDIRECT_PATH
    )
    access_token = api.exchange_code_for_access_token(code)

    # TODO - save access token on user model
Example #15
0
def _get_access_token():
    api = InstagramAPI(client_id=client_id,
                       client_secret=client_secret,
                       redirect_uri=REDIRECT_URL)
    redirect_uri = api.get_authorize_login_url(scope="")
    print("visit this page to get access token", redirect_uri)
    code = input("paste in key after redirect: ").strip()
    access_token, user_detail = api.exchange_code_for_access_token(code=code)
    return access_token
Example #16
0
def get_auth():
    unauth_api = InstagramAPI(**CONFIG)
    redirect_uri = unauth_api.get_authorize_login_url(scope = OTHER['scope'])

    print "Visit this page and authorize access in your browser:\n", redirect_uri
    code = raw_input('Please type in the access code you got\n')
    OTHER['access_token'], me = unauth_api.exchange_code_for_access_token(code)

    with open('config', 'w') as cf:
        config_parser.set('Access Token', 'access_token', OTHER['access_token'])
        config_parser.write(cf)
Example #17
0
def _get_access_token():
    api = InstagramAPI(client_id=client_id,
                       client_secret=client_secret,
                       redirect_uri=REDIRECT_URL)
    redirect_uri = api.get_authorize_login_url(scope=SCOPE)

    print("Visit this page in browser and authorize access:\n", redirect_uri)
    code = input("Paste in code in query string after redirect: ").strip()

    access_token, user_info = api.exchange_code_for_access_token(code)

    return access_token
Example #18
0
def getToken(request):
    api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://bestjae.com/api/getToken")
    # api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://localhost:8000/api/getToken")
    result = str(request.get_raw_uri()).split('code=')[1]
    print result

    access_token = api.exchange_code_for_access_token(str(result))

    request.session['accesstoken'] = access_token
    context = {'accesstoken': access_token}

    return render(request, 'analytics.html', context)
Example #19
0
def instagram_oauthorized():

    code = request.args.get('code', None)

    if 'twitter' in session and 'mastodon' in session and code:

        client_id = app.config['INSTAGRAM_CLIENT_ID']
        client_secret = app.config['INSTAGRAM_SECRET']
        redirect_uri = url_for('instagram_oauthorized', _external=True)
        api = InstagramAPI(client_id=client_id,
                           client_secret=client_secret,
                           redirect_uri=redirect_uri)

        try:
            access_token = api.exchange_code_for_access_token(code)
        except OAuth2AuthExchangeError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))

        # look up settings
        bridge = db.session.query(Bridge).filter_by(
            mastodon_user=session['mastodon']['username'],
            twitter_handle=session['twitter']['screen_name'],
        ).first()

        bridge.instagram_access_code = access_token[0]

        data = access_token[1]
        bridge.instagram_account_id = data['id']
        bridge.instagram_handle = data['username']

        user_api = InstagramAPI(access_token=bridge.instagram_access_code,
                                client_secret=client_secret)

        try:
            latest_media, _ = user_api.user_recent_media(
                user_id=bridge.instagram_account_id, count=1)
        except Exception:
            latest_media = []

        if len(latest_media) > 0:
            bridge.instagram_last_id = datetime_to_timestamp(
                latest_media[0].created_time)
        else:
            bridge.instagram_last_id = 0

        db.session.commit()

    else:
        flash("Instagram authorization failed")

    return redirect(url_for('index'))
Example #20
0
 def get(self, request):
     unauth_api = InstagramAPI(**self.CFG)
     url = unauth_api.get_authorize_url(scope=self.SCOPE)
     code = request.GET.get('code')
     if not code:
         # link to get CODE
         return JsonResponse({'token':None,'redirect':url})
     else:
         access_token, user_info = unauth_api.exchange_code_for_access_token(code)
         if not access_token:
             return JsonResponse({'token':None,'redirect':None})
         # save it to next responses
         return JsonResponse({'token':access_token,'redirect':None})
 def get_access_token_from_code(self):
     api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri)
     access_token = api.exchange_code_for_access_token(self.access_token_code)
     #print "got an access token: "+str(access_token[0])
     #print access_token
     access_token_timestamp = str(datetime.datetime.now())
     instagram_username = access_token[1]['username']
     instagram_user_id = access_token[1]['id']
     #print instagram_username
     config = {'access_token':access_token[0], 'access_token_timestamp':access_token_timestamp, 'instagram_auth_status':'True', 'instagram_username':instagram_username, 'instagram_user_id':instagram_user_id}
     # if(redirect_uri):
     #     response = urllib2.urlopen(redirect_uri).read()
     return config
Example #22
0
    def runConfigWizard(self):
        try:
            api = InstagramAPI(client_id=self.options_string['hidden_client_id'],
                               client_secret=self.options_string['hidden_client_secret'],
                               redirect_uri=self.options_string['redirect_uri'])
            url = api.get_authorize_login_url()

            self.wizard.setWindowTitle('Instagram plugin configuration wizard')
            page1 = QWizardPage()
            layout1 = QVBoxLayout()
            txtArea = QLabel()
            txtArea.setText('Please copy the following link to your browser window. \n ' +
                            'Once you authenticate with Instagram you will be redirected to ' +
                            'www.geocreepy.com and get your token. Copy the token to the input field below:')
            urlArea = QLineEdit()
            urlArea.setObjectName('urlArea')
            urlArea.setText(url)
            inputLink = QLineEdit()
            inputLink.setObjectName('inputLink')
            labelLink = QLabel('Your token value:')
            openInBrowserButton = QPushButton('Open in browser')
            openInBrowserButton.clicked.connect(functools.partial(self.openLinkInBrowser, url))
            layout1.addWidget(txtArea)
            layout1.addWidget(urlArea)
            layout1.addWidget(openInBrowserButton)
            layout1.addWidget(labelLink)
            layout1.addWidget(inputLink)
            page1.setLayout(layout1)
            self.wizard.addPage(page1)
            self.wizard.resize(600, 400)
            if self.wizard.exec_():
                c = str(inputLink.text())
                if c:
                    try:
                        access_token = api.exchange_code_for_access_token(code=c)
                        self.options_string['hidden_access_token'] = access_token[0]
                        self.saveConfiguration(self.config)
                    except Exception, err:
                        logger.error(err)
                        self.showWarning('Error Getting Access Token',
                                         'Please verify that the link you pasted was correct. '
                                         'Try running the wizard again.')
                else:
                    self.showWarning('Error Getting Access Token',
                                     'Please verify that the link you pasted was correct. Try running the wizard again.')

        except Exception, err:
            logger.error(err)
            self.showWarning('Error', 'Error was {0}'.format(err))
Example #23
0
def get_access_token_view(request):
  _log.info('Entering')
  if 'code' in request.GET:
    api = InstagramAPI(client_id=constants.CLIENT_ID,
                       client_secret=constants.CLIENT_SECRET,
                       redirect_uri=constants.REDIRECT_URI)

    response_dict = api.exchange_code_for_access_token(request.GET['code'])
    user_info_dict = response_dict[1]

    try:
      user = authenticate(response_dict=response_dict)
      request_and_save_user_info_from_ig(api, user.instagram_id)
      return JSONResponse({'ig_id': user.instagram_id})
    except Exception as e:
      _log.error('Exception while finding users: %s' % str(e))
Example #24
0
def auth(request):

	api = InstagramAPI(client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, redirect_uri=settings.REDIRECT_URI)
	output = {}

	if request.GET.get('code'):
		code = request.GET.get('code')
		access_token, user = api.exchange_code_for_access_token(code)
		request.session['token'] = access_token

	if not request.session.get('token'):		
		redirect_uri = api.get_authorize_login_url(scope = settings.SCOPE)

		if not request.GET.get('code'):
			return redirect(redirect_uri)

	return HttpResponse(request.session['token'])
Example #25
0
def get_instagram_access_token(code):

    url = "https://api.instagram.com/oauth/access_token"
    params = {
        'client_id': models.app_setting.INSTAGRAM_ID,
        'client_secret': models.app_setting.INSTAGRAM_SECRET,
        'grant_type': 'authorization_code',
        'redirect_uri': models.app_setting.INSTAGRAM_CALLBACK_URL,
        'code': code
    }

    api = InstagramAPI(client_id=models.app_setting.INSTAGRAM_ID,
                       client_secret=models.app_setting.INSTAGRAM_SECRET,
                       redirect_uri=models.app_setting.INSTAGRAM_CALLBACK_URL)
    access_token = api.exchange_code_for_access_token(code)

    return access_token[0]
Example #26
0
def success_view(request):
  if 'code' in request.GET:
    api = InstagramAPI(client_id=constants.CLIENT_ID,
                       client_secret=constants.CLIENT_SECRET,
                       redirect_uri=constants.REDIRECT_URI)

    # TODO: Add try-catch for expired tokens here
    response_dict = api.exchange_code_for_access_token(request.GET['code'])
    user_info_dict = response_dict[1]

    try:
      user = authenticate(response_dict=response_dict)
    except Exception as e:
      _log.error('Exception while finding users: %s' % str(e))
      redirect('/login')

    django_login(request, user)
    request_and_save_user_info_from_ig(api, user_info_dict['id'])
    return redirect('/dashboard')
  else:
    return redirect('/login')
def get_auth_tokens(stdout):
    stdout.write('Please enter the following Instagram client details\n\n')
    print('lol' + settings.INSTAGRAM_CLIENT_ID)
    if settings.INSTAGRAM_CLIENT_ID == '':
        settings.INSTAGRAM_CLIENT_ID = input('Client ID: ').strip()
    if settings.INSTAGRAM_CLIENT_SECRET == '':
        settings.INSTAGRAM_CLIENT_SECRET = input('Client Secret: ').strip()
    if settings.INSTAGRAM_REDIRECT_URI == '':
        settings.INSTAGRAM_REDIRECT_URI = input('Redirect URI: ').strip()

    scope = ['basic', 'public_content', 'likes']

    api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET, redirect_uri=settings.INSTAGRAM_REDIRECT_URI)
    redirect_uri = api.get_authorize_login_url(scope=scope)

    stdout.write('\nVisit this page and authorize access in your browser:\n\n%s\n\n' % redirect_uri)

    code = input('Paste in code in query string after redirect: ').strip()

    access_token = api.exchange_code_for_access_token(code)
    stdout.write('Access token:\n\n%s\n\n' % (access_token,))
def get_auth_tokens(stdout):
    stdout.write('Please enter the following Instagram client details\n\n')
    client_id = input('Client ID: ').strip()
    client_secret = input('Client Secret: ').strip()
    redirect_uri = input('Redirect URI: ').strip()
    raw_scope = input(
        'Requested scope (separated by spaces, blank for just basic read): ').strip()
    scope = raw_scope.split(' ')

    # For basic, API seems to need to be set explicitly
    if not scope or scope == ['']:
        scope = ['basic']

    api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
    redirect_uri = api.get_authorize_login_url(scope=scope)

    stdout.write('\nVisit this page and authorize access in your browser:\n\n%s\n\n' % redirect_uri)

    code = input('Paste in code in query string after redirect: ').strip()

    access_token = api.exchange_code_for_access_token(code)
    stdout.write('Access token:\n\n%s\n\n' % (access_token,))
Example #29
0
 def get_access_token_from_code(self):
     api = InstagramAPI(client_id=self.client_id,
                        client_secret=self.client_secret,
                        redirect_uri=self.redirect_uri)
     access_token = api.exchange_code_for_access_token(
         self.access_token_code)
     #print "got an access token: "+str(access_token[0])
     #print access_token
     access_token_timestamp = str(datetime.datetime.now())
     instagram_username = access_token[1]['username']
     instagram_user_id = access_token[1]['id']
     #print instagram_username
     config = {
         'access_token': access_token[0],
         'access_token_timestamp': access_token_timestamp,
         'instagram_auth_status': 'True',
         'instagram_username': instagram_username,
         'instagram_user_id': instagram_user_id
     }
     # if(redirect_uri):
     #     response = urllib2.urlopen(redirect_uri).read()
     return config
class client_packet :
    
    def __init__(self, client_id, client_secret, redirect_uri, begin_user_id):
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect_uri = redirect_uri
        self.begin_user_id = begin_user_id
    
    def access_token(self,flag):
        if flag:
            scope = []
            self.api = InstagramAPI(client_id = self.client_id, client_secret = self.client_secret, redirect_uri = self.redirect_uri)
            redirect_uri = self.api.get_authorize_login_url(scope = scope)

            print "Visit this page and authorize access in your browser:\n", redirect_uri

            code = raw_input("Paste in code in query string after redirect: ").strip()
            self.access_token = self.api.exchange_code_for_access_token(code)
            print self.access_token
        else:
            self.access_token = 'Insert Your actual Client Access token to not repeath this again and again'

        return self.access_token
Example #31
0
# Fix Python 2.x.
try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

client_id = input("Client ID: ").strip()
client_secret = input("Client Secret: ").strip()
redirect_uri = input("Redirect URI: ").strip()
raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip()
scope = raw_scope.split(' ')
# For basic, API seems to need to be set explicitly
if not scope or scope == [""]:
    scope = ["basic"]

api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
redirect_uri = api.get_authorize_login_url(scope = scope)

print ("Visit this page and authorize access in your browser: "+ redirect_uri)

code = (str(input("Paste in code in query string after redirect: ").strip()))

access_token = api.exchange_code_for_access_token(code)

with open('/var/www/feedagram/feedagram/json/access_token.json', 'w') as outputFile:
    json.dump(access_token, outputFile, ensure_ascii=False)

print ("Access token successfully obtained.")
Example #32
0
def instagram_redirect(code):
    api = InstagramAPI(client_id=settings.CLIENT_ID,
                       client_secret=settings.CLIENT_SECRET,
                       redirect_uri=settings.HOST + INSTAGRAM_REDIRECT_PATH)
    access_token = api.exchange_code_for_access_token(code)
Example #33
0
class instagram_platform(social_platform):
    '''
        Class used for logging into instagram using user authorisation
        @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram
    '''
    
    def __init__(self):
        '''
            Constructor defines the client_id, client_secret, HttpsConnection string, the Test connection URL, the httpsOauthstring and the access_token.
            @param self: Pointer to the current object.
            @type self: L{social_platform}.
            @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram

        '''
        from instagram.client import InstagramAPI
        self.client_id = "209d4256fd0540f6b23e6ee4c82821f4"
        self.client_secret = "6bbde185375e4ec4b4178555a0387cf8"
        self.https_connection_string = "api.instagram.com:443"
        self.test_connection_string = "http://instagram.com"
        self.https_oauth_string = "/oauth2/token"
        
        self.access_token = None
        
        self.redirect = "http://0.0.0.0:8080/redirect?platform=instagram" # this is the string instagram has as the redirect after the user logs in
        self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect)
#       self.redirect = self.api.get_authorize_login_url(scope = "")
        
    def get_platform_name(self):
        '''
            Returns the name of the social platform of the object it is applied to.
            @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram
            @param self: Pointer to the current object.
            @type self: L{social_platform}            
            @return: Returns the current platform's name.
            @rtype: L{str}
        '''
        return "instagram"    
    def request_center_radius(self, criteria=None, gps_center=None, radius=None):
        '''
            @attention: Not implemented
        '''     
        raise NotImplementedError
    def request_region(self, criteria=None, area=None):
        '''
            @attention: Not implemented
        '''     
        raise NotImplementedError        
    def authenticate(self,code=None):
        ''' Instagram authentication, must be called twice to authenticate completely, first call of authentication takes no parameters and requests \
            authentication to the instagram server by being redirected to the instagram site requesting a code.
            Once the code has been requested instagram will redirect to the servers redirect site 'superfluous.imqs.co.za/Omicron/redirect' with parameters \
            platform=instagram and code="some code" such that the site would be 'superfluous.imqs.co.za/Omicron/redirect?platform=instagram&code="some code"' \
            at this redirect site you must call this method again but with the code as the parameter to complete the authentication for the instance of this object
            @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram
            @param code: A code generated by Instagrams servers, on first call for authentication this must be None.
            @type code: String
            
            @return: Returns a redirect string to retrieve an authentication code from on the first call if code is None, if code is not None \
                        it will exchange the code for an access token and store the access token in self.access_token and return True
        '''
        if(code == None):
            return self.redirect
        else:
            self.access_token = self.api.exchange_code_for_access_token(code)
        return True
            
        
    def authenticate_headers(self):
        '''
            @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram
        '''     
        raise NotImplementedError    
    
    def strip_data(self, input_data=None, selected_properties=None):
        '''
            Strips the given raw data so that only the selected properties remain.
            @attention: Class Not implemented in project omicron, Incomplete class, requires from instagram.client import InstagramAPI #downloadable at https://github.com/Instagram/python-instagram    
            @param input_data: Raw data that needs to be  
            @type input_data: JSON Object
            @param selected_properties: List of properties that should be kept after stripping.
            @type selected_properties: List of strings - either 'tags', 'location' or 'post'.
            @return: The stripped data.
            @rtype: JSON Object 
        '''
        if(selected_properties == None):
            print "There are no properties to strip the data by"
            return None
        
        if(input_data == None):
            print "Result_set undefined"
            return None
        search_set = input_data['data']
        result_set = {}
        
        if('post' in selected_properties):
            for instapost in search_set:
                if(instapost['link'] != None):
                    result_set.update({'posts':{'link': instapost['link'], 'caption' : instapost['caption']['text']}})
    
        if('location' in selected_properties):
            for instapost in search_set:
                if(instapost['location'] != None):
                    result_set.update({'location':tuple([instapost['location']['latitude'], instapost['location']['longitude']])})
            
        if('tags' in selected_properties):
            for instapost in search_set:
                if(instapost['caption'] != None):
                    result_set.update({'tags':instapost['text']}) 
        newset = ''
        s = result_set['tags'].split(' ')
        for element in s:
            if ('#' in element):
                newset = newset+element
        reset = newset.split('#')
        reset.pop(0)
        result_set['tags'] = reset.pop(0)
        
        return result_set 
Example #34
0
class InstagramAccount(Account):
    def __init__(self,
                 client_id=None,
                 client_secret=None,
                 redirect_url=None,
                 access_token=None,
                 name=None,
                 ty=None,
                 **kwargs):
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect = redirect_url
        self.name = name
        self.ty = ty
        if access_token:
            self.access_token = access_token
            self.api = InstagramAPI(access_token=access_token)
        else:
            self.api = InstagramAPI(client_id=client_id,
                                    client_secret=client_secret,
                                    redirect_uri=redirect_url)
            url = self.api.get_authorize_login_url(
                scope=['basic', 'likes', 'comments', 'relationships'])
            print 'This account needs to be authenticated. Visit this url:'
            print url
            code = raw_input('Please enter the result code:').strip()
            self.access_token, user_info = self.api.exchange_code_for_access_token(
                code)
            db.instagram.update({'name': self.name},
                                {'$set': {
                                    'access_token': self.access_token
                                }})
            self.api = InstagramAPI(access_token=access_token)
        self.uid = self._get_uid(self.name)

    def log(self, action, details):
        Account.log(self, 'instagram', action, details)

    # Pick a popular thing and like it.
    def like_popular(self):
        self.log("like-popular", str(datetime.today()))
        popular = self.api.media_popular(count='20')
        for i in xrange(8):
            p = random.choice(popular)
            self.api.like_media(p.id)

    # Follow someone.
    def follow(self, un):
        uid = self._get_uid(un)
        # Bug in the official API call for this one. Needs direct HTTP
        payload = {'ACCESS_TOKEN': self.access_token, 'action': 'follow'}
        r = requests.post('https://api.instagram.com/v1/users/' + uid +
                          '/relationship?access_token=' + self.access_token,
                          data=payload)
        return r

    # Follow a friend of a friend.
    def follow_branch(self):
        friends = self.api.user_follows(self.uid)
        f = random.choice(friends[0])
        other_friends = self.api.user_follows(f.id)
        f2 = random.choice(other_friends[0])
        self.log("follow-branch", str(datetime.today()) + ',' + f2.username)
        self.follow(f2.username)
        return f2

    # make a generic comment
    # for now these comments are just positive
    def generic_comment_friend(self):
        #1. pick a friend
        friends = self.api.user_follows(self.uid)[0]
        f = random.choice(friends)

        #2. pick a dumb comment
        comment = random.choice(POSITIVE)

        #3. pick something they posted
        recent = self.api.user_recent_media(f.id)
        print recent
        post = random.choice(recent)
        self.log("generic-comment-friend",
                 str(datetime.today()) + ',' + str(post) + ',' + str(comment))

        #4. make a dumb comment on their dumb post
        self.api.create_media_comment(post.id, comment)

        return (post, comment)

    def generic_comment_feed(self):
        comment = random.choice(POSITIVE)
        post = random.choice(self.api.user_media_feed()[0])
        self.log("generic-comment-friend",
                 str(datetime.today()) + ',' + str(post) + ',' + str(comment))
        self.api.create_media_comment(post.id, comment)

    # like something a friend posted recently
    def like_friend(self):
        friends = self.api.user_follows(self.uid)[0]
        f = random.choice(friends)

        recent = self.api.user_recent_media(user_id=f.id, count=20)
        self.log("like-friends-post", str(datetime.today()) + ',' + f.username)
        post = random.choice(recent[0])
        self.api.like_media(post.id)
        return post

    # Helper to turn a username into a user id
    def _get_uid(self, un):
        uid = self.api.user_search(q=un)
        uid = uid[0]
        uid = uid.id
        return uid
Example #35
0
			try:
				callback = acquire_url_base+'?medium={}&username={}'.format(medium,alleged_user)
				CONFIG = {
					'client_id': session['APP_KEY'], 
					'client_secret': session['APP_SECRET'],
					'redirect_uri': callback
				}

				api = InstagramAPI(**CONFIG)

				code = request.args.get('code')

				if code:


					access_token, user_info = api.exchange_code_for_access_token(code)
					if not access_token:
						return 'Could not get access token'

					# Sessions are used to keep this data 
					OAUTH_TOKEN = access_token

					api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret'])
					userid = user_info['id'] 
					username = user_info['username'] 	
					post_ct = api.user().counts['media']
				else:
					return "Uhoh no code provided"
			except Exception,e:
				return "Error in acquire step 1: "+str(e)
Example #36
0
            try:
                callback = acquire_url_base + '?medium={}&username={}'.format(
                    medium, alleged_user)
                CONFIG = {
                    'client_id': session['APP_KEY'],
                    'client_secret': session['APP_SECRET'],
                    'redirect_uri': callback
                }

                api = InstagramAPI(**CONFIG)

                code = request.args.get('code')

                if code:

                    access_token, user_info = api.exchange_code_for_access_token(
                        code)
                    if not access_token:
                        return 'Could not get access token'

                    # Sessions are used to keep this data
                    OAUTH_TOKEN = access_token

                    api = InstagramAPI(access_token=access_token,
                                       client_secret=CONFIG['client_secret'])
                    userid = user_info['id']
                    username = user_info['username']
                    post_ct = api.user().counts['media']
                else:
                    return "Uhoh no code provided"
            except Exception, e:
                return "Error in acquire step 1: " + str(e)
Example #37
0
class InstagramAccount(Account):
    def __init__(self, client_id=None,client_secret=None,redirect_url=None,access_token=None,name=None,ty=None,**kwargs):
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect = redirect_url
        self.name = name
        self.ty = ty
        if access_token:
            self.access_token = access_token
            self.api = InstagramAPI(access_token=access_token)
        else:
            self.api = InstagramAPI(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_url)
            url = self.api.get_authorize_login_url(scope=['basic','likes','comments','relationships'])
            print 'This account needs to be authenticated. Visit this url:'
            print url
            code = raw_input('Please enter the result code:').strip()
            self.access_token, user_info = self.api.exchange_code_for_access_token(code)
            db.instagram.update({'name':self.name},{'$set':{'access_token':self.access_token}})
            self.api = InstagramAPI(access_token = access_token)
        self.uid = self._get_uid(self.name)

    def log(self,action,details):
        Account.log(self,'instagram',action,details)

    # Pick a popular thing and like it.
    def like_popular(self):
        self.log("like-popular",str(datetime.today()))
        popular = self.api.media_popular(count='20')
        for i in xrange(8):
            p = random.choice(popular)
            self.api.like_media(p.id)

    # Follow someone.
    def follow(self,un):
        uid = self._get_uid(un)
        # Bug in the official API call for this one. Needs direct HTTP
        payload = {'ACCESS_TOKEN':self.access_token,'action':'follow'}
        r = requests.post('https://api.instagram.com/v1/users/'+uid+'/relationship?access_token='+self.access_token,data=payload)
        return r

    # Follow a friend of a friend.
    def follow_branch(self):
        friends = self.api.user_follows(self.uid)
        f = random.choice(friends[0])
        other_friends = self.api.user_follows(f.id)
        f2 = random.choice(other_friends[0])
        self.log("follow-branch",str(datetime.today())+','+f2.username)
        self.follow(f2.username)
        return f2

    # make a generic comment
    # for now these comments are just positive
    def generic_comment_friend(self):
        #1. pick a friend
        friends = self.api.user_follows(self.uid)[0]
        f = random.choice(friends)

        #2. pick a dumb comment
        comment = random.choice(POSITIVE)

        #3. pick something they posted
        recent = self.api.user_recent_media(f.id)
        print recent
        post = random.choice(recent)
        self.log("generic-comment-friend",str(datetime.today())+','+str(post)+','+str(comment))

        #4. make a dumb comment on their dumb post
        self.api.create_media_comment(post.id,comment)

        return (post,comment)

    def generic_comment_feed(self):
        comment = random.choice(POSITIVE)
        post = random.choice(self.api.user_media_feed()[0])
        self.log("generic-comment-friend",str(datetime.today())+','+str(post)+','+str(comment))
        self.api.create_media_comment(post.id,comment)

    # like something a friend posted recently
    def like_friend(self):
        friends = self.api.user_follows(self.uid)[0]
        f = random.choice(friends)

        recent = self.api.user_recent_media(user_id=f.id,count=20)
        self.log("like-friends-post",str(datetime.today())+','+f.username)
        post = random.choice(recent[0])
        self.api.like_media(post.id)
        return post

    # Helper to turn a username into a user id
    def _get_uid(self,un):
        uid = self.api.user_search(q=un)
        uid = uid[0]
        uid = uid.id
        return uid
Example #38
0
try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

try:
    from config import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI
except Exception, e:
    pass

client_id = CLIENT_ID or input("Client ID: ").strip()
client_secret = CLIENT_SECRET or input("Client Secret: ").strip()
redirect_uri = REDIRECT_URI or input("Redirect URI: ").strip()
raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip()
scope = raw_scope.split(' ')
# For basic, API seems to need to be set explicitly
if not scope or scope == [""]:
    scope = ["basic"]

api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
redirect_uri = api.get_authorize_login_url(scope=scope)

print("Visit this page and authorize access in your browser: " + redirect_uri)

code = (str(input("Paste in code in query string after redirect: ").strip()))

access_token = api.exchange_code_for_access_token(code)
print("access token: ")
print(access_token)
Example #39
0
class Instagram:
    def __init__(self):
        # Stuff for the attack
        self.delay = 5
        self.victim = None

        # Stuff for the API
        self.client_id = 'd00446a61de44643bd0d1a21d78e0f5a'
        self.client_secret = 'c742af13e3a04138bad288c50e005999'
        self.redirect_uri = 'http://localhost/hiroshima/auth/insta'
        self.raw_scope = 'basic likes'
        self.scope = self.raw_scope.split(' ')
        # For basic, API seems to need to be set explicitly
        if not self.scope or self.scope == [""]:
            self.scope = ["basic"]
        self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri)
        self.redirect_uri = self.api.get_authorize_login_url(scope=self.scope)
        if os.path.exists(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg")):
            self.config = ConfigParser.ConfigParser()
            self.config.read(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg"))
            self.access_token = self.config.get('insta', 'access_token')
            if self.access_token != "None":
                self.AUTH_IN_PREFS = True
            else:
                self.AUTH_IN_PREFS = False
        else:
            print "~/.config/hiroshima/hiroshima.cfg does not exist. Run install.sh or copy defautl.cfg to ~/.config/hiroshima/hiroshima.cfg"

    def login(self):
        if not self.AUTH_IN_PREFS:
            print "You will be redirected to an authorization page in your browser. Copy the code in the prompt and paste it below."
            webbrowser.open(self.redirect_uri)
            code = (str(input("code: ").strip()))
            self.access_token = self.api.exchange_code_for_access_token(code)
            if self.access_token != None:
                self.config.set('insta', 'access_token', str(self.access_token[0]))
                f = open(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg"), 'wb')
                self.config.write(f)
                f.close()
                self.a_api = InstagramAPI(access_token=self.access_token[0])
                print "You're account has been authorized."
                return True
            else:
                return False
        else:
            self.a_api = InstagramAPI(access_token=self.access_token)
            print "You're account has been authorized."
            return True

    def set_victim(self, user):
        self.victim = self.a_api.user(user.id)
        if self.victim.username == "cryptoc1":
            print "Nice f*****g try! bruh. ;)"
            return False
        if self.victim != None:
            return  True
        else:
            return False

    def search_users(self, uname):
        return self.a_api.user(self.a_api.user_search(q=uname, count=1)[0].id)

    def like_attack(self, count):
        if str(count).lower() == "all":
            print "Liking " + str(count) + " photos. Due to rate-limits, this may take a while..."
            print "Number of photos expected to be liked: " + str(self.victim.counts['media'])
            eta = self.victim.counts['media'] * self.delay
            print self.format_eta(eta)
            for media in self.a_api.user_recent_media(user_id=self.victim.id, count=self.victim.counts['media'])[0]:
                if media.user_has_liked:
                    print "Photo with id: " + str(media.id) + " already liked, skipping."
                else:
                    self.a_api.like_media(media.id)
                    print "Photo with id: " + str(media.id) + " liked."
                time.sleep(self.delay)
        else:
            count = int(count)
            print "Liking " + str(count) + " photos. Due to rate-limits, this may take a while..."
            print "Number of photos expected to be liked: " + str(count)
            eta = count * self.delay
            print self.format_eta(eta)
            for media in self.a_api.user_recent_media(user_id=self.victim.id, count=count)[0]:
                if media.user_has_liked:
                    print "Photo with id: " + str(media.id) + " already liked, skipping."
                else:
                    self.a_api.like_media(media.id)
                    print "Photo with id: " + str(media.id) + " liked."
                time.sleep(self.delay)

    def unlike_attack(self, count):
        if str(count).lower() == "all":
            print "Unliking " + str(count) + " photos. Due to rate-limits, this may take a while..."
            print "Number of photos expected to be unliked: " + str(self.victim.counts['media'])
            eta = self.victim.counts['media'] * self.delay
            print self.format_eta(eta)
            for media in self.a_api.user_recent_media(user_id=self.victim.id, count=self.victim.counts['media'])[0]:
                if media.user_has_liked:
                    self.a_api.unlike_media(media.id)
                    print "Photo with id: " + str(media.id) + " unliked."
                else:
                    print "Photo with id: " + str(media.id) + " already not liked, skipping."
                time.sleep(self.delay)
        else:
            count = int(count)
            print "Unliking " + str(count) + " photos. Due to rate-limits, this may take a while..."
            print "Number of photos expected to be unliked: " + str(count)
            eta = count * self.delay
            print self.format_eta(eta)
            for media in self.a_api.user_recent_media(user_id=self.victim.id, count=count)[0]:
                if media.user_has_liked:
                    self.a_api.unlike_media(media.id)
                    print "Photo with id: " + str(media.id) + " unliked."
                else:
                    print "Photo with id: " + str(media.id) + " already not liked, skipping."
                time.sleep(self.delay)

    def get_attack_types(self):
        return "like, unlike"

    def format_eta(self, eta):
        if eta > 60:
            return "ETA: " + str(eta / 60) + "M"
        else:
            return "ETA: " + str(eta) + "S"

    def format_user_info(self, u):
        return "id: " + str(u.id) + "\nusername: "******"\nfull_name: " + unicode(u.full_name).encode('utf-8', 'ignore') + "\nprofile_picture: " + str(u.profile_picture) + "\nbio: " + unicode(u.bio).encode('utf-8', 'ignore') + "\nwebsite: " + str(u.website) + "\ncounts: " + str(u.counts)