Пример #1
0
        def callback():
            client = OAuth2Session(
                self.client_id,
                state=session["oauth_state"],
                redirect_uri=url_for(".callback", _external=True),
            )

            if self.name == "facebook":
                facebook_compliance_fix(client)

            self.token = client.fetch_token(
                self.token_url,
                client_secret=self.client_secret,
                authorization_response=request.url,
            )

            # Get additional data for the user
            user_data = self.get_user_info()

            # Ensure the user is registered
            user = self.get_or_create_user(user_data)

            # Store the (serialized) user info on the sessions
            session["user"] = self.serialize_user(user)

            # Redirect the user to the requested page
            if session.get("next") is not None:
                url = session["next"]
                del session["next"]
                return redirect(url)

            # Default is to redirect to the root
            return redirect("/")
Пример #2
0
 def __init__(self):
     super(FacebookGraph, self).__init__(
         app.config['FACEBOOK_APP_ID'],
         redirect_uri=url_for('facebook_auth_return', _external=True),
         token=runtime_config.get('facebook_token'),
     )
     facebook_compliance_fix(self)
Пример #3
0
def start_facebook_session():
    global facebook_session

    # 0 - get token from cache
    try:
        token = get_saved_token()
    except FileNotFoundError:
        token = None

    if token:
        facebook_initial_session = OAuth2Session(APP_ID, token=token)
        facebook_session = facebook_compliance_fix(facebook_initial_session)

    else:
        # 1 - session
        facebook_initial_session = OAuth2Session(APP_ID, redirect_uri=REDIRECT_URI, scope=scope)
        facebook_session = facebook_compliance_fix(facebook_initial_session)

        # 2 - authorization
        authorization_url, state = facebook_session.authorization_url(AUTHORIZATION_BASE_URL)
        print('Opening browser to {} for authorization'.format(authorization_url))
        webbrowser.open(authorization_url)

        # 3 - token
        redirect_response = input('Paste the full redirect URL here: ')
        token = facebook_session.fetch_token(TOKEN_URL, client_secret=APP_SECRET,
            authorization_response=redirect_response.strip())

        # 4 - save token
        save_token(token)
Пример #4
0
 def get_session(self):
     fb = OAuth2Session(
         self.settings['client_id'],
         scope=self.settings['scope'],
         redirect_uri=self.callback_url()
     )
     facebook_compliance_fix(fb)
     return fb
Пример #5
0
def start_flow(request: Request, redirect_uri: str = None) -> dict:
    """
    Starts the oauth flow. This will return a dict which causes a redirect to the providers page.

    :param request: The Pyramid Request associated with the OAuth request.
    :param redirect_uri: The URL to redirect to.
    :return:
    """
    next_url = request.application_url + '/discuss' if not redirect_uri else redirect_uri
    LOG.debug("Read OAuth id/secret: none? %s/%s", CLIENT_ID is None,
              CLIENT_SECRET is None)
    oauth_session = OAuth2Session(CLIENT_ID,
                                  scope=','.join(SCOPE),
                                  redirect_uri=(request.application_url +
                                                REDIRECT_PATH))
    oauth_session = facebook_compliance_fix(oauth_session)

    authorization_url, state = oauth_session.authorization_url(
        AUTHORIZATION_BASE_URL)
    request.session['oauth_session'] = oauth_session
    request.session['csrf'] = state
    request.session['next'] = next_url

    LOG.debug("Please go to %s and authorize access", authorization_url)
    return {'authorization_url': authorization_url, 'error': ''}
Пример #6
0
    def get(self, request, *args, **kwargs):
        facebook = OAuth2Session(settings.FACEBOOK_CLIENT_ID,
                                 redirect_uri=settings.FACEBOOK_REDIRECT_URI)
        facebook = facebook_compliance_fix(facebook)

        if 'code' not in self.request.GET:
            authorization_url, state = facebook.authorization_url(
                self.authorization_base_url)
            return HttpResponseRedirect(authorization_url)
        else:
            auth_code = self.request.GET['code']
            facebook.fetch_token(
                self.token_url.format(version=self.graph_api_version),
                client_secret=settings.FACEBOOK_CLIENT_SECRET,
                code=auth_code)
            user_info = json.loads(
                facebook.get(
                    self.me_url.format(version=self.graph_api_version,
                                       fields=self.fields)).text)
            username = "******".format(user_info['id'])
            email = user_info['email'] or ''

            ott = self.save_user(username, email, user_info)
            context = {'ott': ott, 'redirect_url': '/stations/list'}
            return self.render_to_response(context)
Пример #7
0
def start_flow(redirect_uri):
    """

    :param redirect_uri:
    :return:
    """
    client_id = os.environ.get('OAUTH_FACEBOOK_CLIENTID', None)
    client_secret = os.environ.get('OAUTH_FACEBOOK_CLIENTKEY', None)

    logger(
        'Facebook OAuth',
        'Read OAuth id/secret: none? {}/{}'.format(client_id is None,
                                                   client_secret is None))

    if 'service=facebook' not in redirect_uri:
        bind = '#' if '?' in redirect_uri else '?'
        redirect_uri = '{}{}{}'.format(redirect_uri, bind, 'service=facebook')

    authorization_base_url = 'https://www.facebook.com/dialog/oauth'

    facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
    facebook = facebook_compliance_fix(facebook)

    authorization_url, state = facebook.authorization_url(
        authorization_base_url)

    logger('Facebook OAuth',
           'Please go to {} and authorize access'.format(authorization_url))
    return {'authorization_url': authorization_url, 'error': ''}
Пример #8
0
def callback():
    facebook = requests_oauthlib.OAuth2Session(FB_CLIENT_ID,
                                               scope=FB_SCOPE,
                                               redirect_uri=URL +
                                               "/fb-callback")

    # we need to apply a fix for Facebook here
    facebook = facebook_compliance_fix(facebook)

    facebook.fetch_token(
        FB_TOKEN_URL,
        client_secret=FB_CLIENT_SECRET,
        authorization_response=flask.request.url,
    )

    # Fetch a protected resource, i.e. user profile, via Graph API

    facebook_user_data = facebook.get(
        "https://graph.facebook.com/me?fields=id,name,email,picture{url}"
    ).json()

    # Fb user data
    email = facebook_user_data["email"]
    name = facebook_user_data["name"]
    picture_url = facebook_user_data.get("picture", {}).get("data",
                                                            {}).get("url")

    #login details
    return f"""
Пример #9
0
 def get_authorization_url(self, request, config, callback_url):
     oauth = OAuth2Session(
         config.client_id, scope=config.scope, redirect_uri=callback_url
     )
     oauth = facebook_compliance_fix(oauth)
     authorization_url, _ = oauth.authorization_url(config.authorize_url)
     return authorization_url
Пример #10
0
def makeFacebookRequest(baseURL, params={}):
    global facebook_session
    if not facebook_session:
        #OAuth endpoints given in the Facebook API documentation
        authorization_base_url = 'https://www.facebook.com/dialog/oauth'
        token_url = 'https://graph.facebook.com/oauth/access_token'
        redirect_uri = 'https://www.programsinformationpeople.org/runestone/oauth'

        scope = [
            'user_posts', 'pages_messaging', 'user_managed_groups',
            'user_status', 'user_likes'
        ]
        facebook = OAuth2Session(APP_ID,
                                 redirect_uri=redirect_uri,
                                 scope=scope)
        facebook_session = facebook_compliance_fix(facebook)

        authorization_url, state = facebook_session.authorization_url(
            authorization_base_url)
        print('Opening browser to {} for authorization'.format(
            authorization_url))
        webbrowser.open(authorization_url)

        redirect_response = input('Paste the full redirect URL here: ')
        facebook_session.fetch_token(
            token_url,
            client_secret=APP_SECRET,
            authorization_response=redirect_response.strip())

    return facebook_session.get(baseURL, params=params)
Пример #11
0
    def __call__(self):
        oauthWorkFlow = OauthWorkFlow(oauthServerName="facebook")
        client_id, client_secret, scope, redirect_uri = oauthWorkFlow.getRegistryValue()
        code = getattr(self.request, 'code', None)
        facebook = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
        facebook = facebook_compliance_fix(facebook)
        if code == None:
            if hasattr(self.request, 'error'):
                self.request.response.redirect("/")
                return
            authorization_url, state = facebook.authorization_url(self.authorization_base_url)
            self.request.response.redirect(authorization_url)
            return
        user = oauthWorkFlow.getUserInfo(facebook, self.token_url, client_secret, code, self.getUrl).json()

        # check has id, if True, is a relogin user, if False, is a new user
        userid = safe_unicode("fb%s") % user["id"]
        if api.user.get(userid=userid) is not None:
            self.context.acl_users.session._setupSession(userid.encode("utf-8"), self.context.REQUEST.RESPONSE)
            self.request.RESPONSE.redirect("/")
            return
        userInfo = dict(
            fullname=safe_unicode(user.get("name", "")),
            description=safe_unicode(user.get("about", "")),
            location=safe_unicode(user.get("locale", "")),
            fbGender=safe_unicode(user.get("gender", "")),
            home_page=safe_unicode(user.get("link", "")),
        )
        oauthWorkFlow.createUser(userid, safe_unicode((user.get("email", ""))), userInfo)
        self.context.acl_users.session._setupSession(userid.encode("utf-8"), self.context.REQUEST.RESPONSE)
        self.request.RESPONSE.redirect("/")
        return
Пример #12
0
def process_fb_login_callback_sync(code):
    conf = load_fb_login_configuration()
    fb_app_id = conf['app_id']
    fb_app_secret = conf['app_secret']
    callback_url = conf['callback_url']
    token_url = 'https://graph.facebook.com/oauth/access_token'
    from requests_oauthlib import OAuth2Session
    from requests_oauthlib.compliance_fixes import facebook_compliance_fix
    facebook = OAuth2Session(fb_app_id, redirect_uri=callback_url)
    facebook = facebook_compliance_fix(facebook)
    token = facebook.fetch_token(token_url,
                                 client_secret=fb_app_secret,
                                 code=code)
    r = facebook.get('https://graph.facebook.com/me')
    logger.debug('facebook /me without fields: %s', r.content)
    r = facebook.get('https://graph.facebook.com/me?fields=id,name,email')
    logger.debug('facebook /me with fields: %s', r.content)
    # response:{"id":"102...61723","name":"Pe...er","email":"pe...com"}
    me = r.json()
    user_info = {
        'fb_id': me['id'],
        'name': me['name'],
        'email': me['email'],
    }
    return token, user_info
Пример #13
0
 def get_authorization_url(self, request, config, callback_url):
     oauth = OAuth2Session(config.client_id,
                           scope=config.scope,
                           redirect_uri=callback_url)
     oauth = facebook_compliance_fix(oauth)
     authorization_url, _ = oauth.authorization_url(config.authorize_url)
     return authorization_url
Пример #14
0
def facebook_auth(request):
    oauth = OAuth2Session(client_id,
                          redirect_uri=redirect_uri,
                          scope='user_posts')
    oauth = facebook_compliance_fix(oauth)
    authorization_url, state = oauth.authorization_url(authorization_base_url)
    return redirect(authorization_url)
Пример #15
0
def callback():
    URL = request.url_root.strip("/")
    print(URL)
    facebook = requests_oauthlib.OAuth2Session(FB_CLIENT_ID,
                                               scope=FB_SCOPE,
                                               redirect_uri=URL +
                                               "/fb-callback")

    facebook = facebook_compliance_fix(facebook)

    facebook.fetch_token(
        FB_TOKEN_URL,
        client_secret=FB_CLIENT_SECRET,
        authorization_response=flask.request.url,
    )

    facebook_user_data = facebook.get(
        "https://graph.facebook.com/me?fields=id,name,email,picture{url}"
    ).json()

    email = facebook_user_data["email"]
    name = facebook_user_data["name"]
    picture_url = facebook_user_data.get("picture", {}).get("data",
                                                            {}).get("url")
    result = get_products()
    session["USERNAME"] = email
    return render_template('index.html', data=result, user_data=email)
Пример #16
0
 def __init__(self, user):
     self.fb = OAuth2Session(
         settings.SOCIAL_AUTH_FACEBOOK_KEY,
         redirect_uri=redirect_uri
     )
     self.fb = facebook_compliance_fix(self.fb)
     self.accounts = user.social_auth.filter(provider="facebook")
Пример #17
0
def get_fb_oauth2_session(conf):
    from requests_oauthlib.compliance_fixes import facebook_compliance_fix
    if not conf.client_id:
        raise web.HTTPInternalServerError(text='credentials not configured')
    sess = OAuth2Session(client_id=conf.client_id, redirect_uri=conf.callback_url)
    sess = facebook_compliance_fix(sess)
    return sess
Пример #18
0
def fb_callback():
    facebook = requests_oauthlib.OAuth2Session(
        FB_CLIENT_ID, scope=FB_SCOPE, redirect_uri=URL + "/fb-callback"
    )

    # we need to apply a fix for Facebook here
    facebook = facebook_compliance_fix(facebook)

    facebook.fetch_token(
        FB_TOKEN_URL,
        client_secret=FB_CLIENT_SECRET,
        authorization_response=URL + flask.request.full_path,
    )

    # Fetch a protected resource, i.e. user profile, via Graph API

    facebook_user_data = facebook.get(
        "https://graph.facebook.com/me?fields=id,name,email,picture{url}"
    ).json()

    email = facebook_user_data.get("email")
    name = facebook_user_data["name"]
    avatar_url = facebook_user_data.get("picture", {}).get("data", {}).get("url")

    return flask.render_template(
        "user_info.html",
        name=name,
        email=email,
        avatar_url=avatar_url,
        provider="Facebook",
    )
Пример #19
0
def _get_oauth2_info(client_id, client_secret, scope, redirect_uri, token_url, user_info_url, request, params, is_facebook=False):
    headers = dict(request.headers)
    cookies = dict(request.cookies)

    cfg.logger.debug('params: %s headers: %s cookies: %s', params, headers, cookies)

    the_auth = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)

    if is_facebook:
        the_auth = facebook_compliance_fix(the_auth)

    # fetch token
    #the_path = params.get('url', '')
    qs = urllib.urlencode(params)
    redirect_url = redirect_uri + '?' + qs

    token = the_auth.fetch_token(token_url, client_secret=client_secret, 
                           authorization_response=redirect_url)

    cfg.logger.debug('after fetch_token: token: (%s, %s)', token, token.__class__.__name__)

    # get user info
    r = the_auth.get(user_info_url)

    return r.content
Пример #20
0
def get_fb_oauth2_session(conf):
    from requests_oauthlib.compliance_fixes import facebook_compliance_fix
    if not conf.client_id:
        raise web.HTTPInternalServerError(text='credentials not configured')
    sess = OAuth2Session(client_id=conf.client_id,
                         redirect_uri=conf.callback_url)
    sess = facebook_compliance_fix(sess)
    return sess
Пример #21
0
    def __init__(self):
        super().__init__(
            'facebook',
            authorization_url='https://www.facebook.com/v2.1/dialog/oauth',
            get_token_url='https://graph.facebook.com/v2.1/oauth/access_token',
        )

        self.oauth = facebook_compliance_fix(self.oauth)
Пример #22
0
    def __init__(self):
        super().__init__(
            "facebook",
            authorization_url="https://www.facebook.com/v2.1/dialog/oauth",
            get_token_url="https://graph.facebook.com/v2.1/oauth/access_token",
        )

        self.oauth = facebook_compliance_fix(self.oauth)
Пример #23
0
def fblogin(request):
    authorization_base_url = 'https://www.facebook.com/dialog/oauth'

    facebook = OAuth2Session(fb_client_id, redirect_uri=fb_redirect_uri)
    facebook = facebook_compliance_fix(facebook)
    authorization_url, state = facebook.authorization_url(
        authorization_base_url)
    return HttpResponseRedirect(authorization_url)
Пример #24
0
def facebook_login(request):
    client_id = settings.FB_OAUTH_CLIENT_ID
    client_secret = settings.FB_OAUTH_CLIENT_SECRET
    authorization_base_url = 'https://www.facebook.com/dialog/oauth'
    token_url = 'https://graph.facebook.com/oauth/access_token'
    redirect_uri = '%s://%s/user/facebook-login' % (request.scheme,
                                                    request.get_host())

    if settings.DEBUG:
        os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

    try:
        oauth_state = request.session['oauth_state']
        del request.session['oauth_state']
    except KeyError:
        oauth_state = None

    facebook = OAuth2Session(client_id,
                             scope='email',
                             redirect_uri=redirect_uri,
                             state=oauth_state)
    facebook = facebook_compliance_fix(facebook)

    if request.GET.get('error') == 'access_denied':
        return redirect('/user/login/')
    elif not request.GET.get('code'):
        authorization_url, state = facebook.authorization_url(
            authorization_base_url)
        request.session['oauth_state'] = state
        return redirect(authorization_url)
    else:
        facebook.fetch_token(
            token_url,
            client_secret=client_secret,
            authorization_response=request.build_absolute_uri())

    r = facebook.get(
        'https://graph.facebook.com/me?fields=first_name,last_name,email')
    data = r.json()

    try:
        profile = UserProfile.objects.get(facebook_user_id=data.get('id'))
        login(request,
              profile.user,
              backend='allauth.account.auth_backends.AuthenticationBackend')
        return redirect('/')
    except UserProfile.DoesNotExist:
        pass

    return render(
        request, 'account/signup.html', {
            'facebook_user_id': data.get('id'),
            'first_name': data.get('first_name'),
            'last_name': data.get('last_name'),
            'email': data.get('email'),
            'date_of_birth': data.get('birthday'),
        })
Пример #25
0
 def get_auth_link(self, user_manager):
     facebook = OAuth2Session(self._client_id,
                              redirect_uri=web.ctx.home +
                              self._callback_page)
     facebook = facebook_compliance_fix(facebook)
     authorization_url, state = facebook.authorization_url(
         authorization_base_url)
     user_manager.set_session_oauth_state(state)
     return authorization_url
Пример #26
0
    def get_oauth2session(self):
        """
        Returns a Facebook requests_oauthlib OAuth2Session
        """
        self.oauth = OAuth2Session(client_id = self.client_id,
                redirect_uri = self.redirect_uri)
        self.oauth = facebook_compliance_fix(self.oauth)

        return self.oauth
Пример #27
0
def get_access_token(provider, authorization_response, redirect_uri):
    if provider == Provider.GOOGLE:
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['GOOGLE']['client_id'],
            redirect_uri=redirect_uri
        )
        ret = p.fetch_token(
            GOOGLE_TOKEN_URL,
            client_secret=settings.STORMPATH_SOCIAL['GOOGLE']['client_secret'],
            authorization_response=authorization_response
        )

        return ret['access_token']
    elif provider == Provider.FACEBOOK:
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['FACEBOOK']['client_id'],
            redirect_uri=redirect_uri
        )

        from requests_oauthlib.compliance_fixes import facebook_compliance_fix

        p = facebook_compliance_fix(p)
        ret = p.fetch_token(
            FACEBOOK_TOKEN_URL,
            client_secret=settings.STORMPATH_SOCIAL['FACEBOOK']['client_secret'],
            authorization_response=authorization_response
        )

        return ret['access_token']
    elif provider == Provider.GITHUB or provider.upper() == Provider.GITHUB:
        p = OAuth2Session(client_id=settings.STORMPATH_SOCIAL['GITHUB']['client_id'])
        ret = p.fetch_token(
            GITHUB_TOKEN_URL,
            client_secret=settings.STORMPATH_SOCIAL['GITHUB']['client_secret'],
            authorization_response=authorization_response
        )

        return ret['access_token']
    elif provider == Provider.LINKEDIN:
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['LINKEDIN']['client_id'],
            redirect_uri=redirect_uri
        )

        from requests_oauthlib.compliance_fixes import linkedin_compliance_fix

        p = linkedin_compliance_fix(p)
        ret = p.fetch_token(
            LINKEDIN_TOKEN_URL,
            client_secret=settings.STORMPATH_SOCIAL['LINKEDIN']['client_secret'],
            authorization_response=authorization_response
        )

        return ret['access_token']
    else:
        return None
Пример #28
0
 def get_auth_link(self, auth_storage, share=False):
     facebook = OAuth2Session(
         self._client_id,
         scope=scope + (["publish_actions"] if share else []),
         redirect_uri=web.ctx.home + self._callback_page)
     facebook = facebook_compliance_fix(facebook)
     authorization_url, state = facebook.authorization_url(
         authorization_base_url)
     auth_storage["oauth_state"] = state
     return authorization_url
Пример #29
0
        def login():
            client = OAuth2Session(
                self.client_id,
                scope=self.scopes,
                redirect_uri=url_for(".callback", _external=True),
            )

            if self.name == "facebook":
                facebook_compliance_fix(client)

            authorization_url, state = client.authorization_url(
                self.authorization_base_url,
                access_type="offline",
                prompt="select_account",
            )

            # State is used to prevent CSRF, keep this for later.
            session["oauth_state"] = state
            return redirect(authorization_url)
Пример #30
0
    def request_auth(self, request):
        from requests_oauthlib.compliance_fixes import facebook_compliance_fix
        self.session = OAuth2Session(self.client_id,
                                     redirect_uri=self.redirect_uri,
                                     scope=self.scope)
        self.session = facebook_compliance_fix(self.session)

        authorization_url, state = self.session.authorization_url(
            self.authorization_base_url)
        return authorization_url
Пример #31
0
def get_facebook(session=None):
    if session:
        facebook = OAuth2Session(FACEBOOK_CLIENT_ID, token=session['oauth_token'])
    else:
        facebook = OAuth2Session(
            FACEBOOK_CLIENT_ID,
            redirect_uri=FACEBOOK_REDIRECT_URI,
            scope=['user_photos']
        )
    return facebook_compliance_fix(facebook)
Пример #32
0
def login_fb(request):
	q=request.GET.get("url",None)
	if q:
		request.session["url"]=q
	authorization_base_url = 'https://www.facebook.com/dialog/oauth/?scope=user_friends,email,public_profile'
	token_url = 'https://graph.facebook.com/oauth/access_token'
	#redirect_uri = 'https://pacific-shelf-88987.herokuapp.com/redirect_facebook/'
	facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
	facebook = facebook_compliance_fix(facebook)
	authorization_url, state = facebook.authorization_url(authorization_base_url)
	return HttpResponseRedirect(authorization_url)
Пример #33
0
def fbCallback():
    facebook = requests_oauthlib.OAuth2Session(FB_CLIENT_ID,
                                               scope=FB_SCOPE,
                                               redirect_uri=URL +
                                               "/fb-callback")

    # we need to apply a fix for Facebook here
    facebook = facebook_compliance_fix(facebook)

    facebook.fetch_token(
        FB_TOKEN_URL,
        client_secret=FB_CLIENT_SECRET,
        authorization_response=request.url,
    )

    # Fetch a protected resource, i.e. user profile, via Graph API

    facebook_user_data = facebook.get(
        "https://graph.facebook.com/me?fields=id,name,email,picture{url}"
    ).json()

    unique_id = facebook_user_data["id"]
    email = facebook_user_data["email"]
    name = facebook_user_data["name"]
    picture_url = facebook_user_data.get("picture", {}).get("data",
                                                            {}).get("url")

    # Create a user in your db with the information provided
    # by Facebook
    id = unique_id
    profile_pic = picture_url

    user = User(id, name, email, profile_pic)

    # Doesn't exist? Add it to the database.
    if not db.session.query(User).filter(User.id == id).count():
        db.session.add(user)
        db.session.commit()

    # Begin user session by logging the user in
    login_user(user)

    # Send user to dance page
    if current_user.is_authenticated:
        return redirect("/")
    # else:
    dances = db.session.query(Dance).filter(Dance.user_id == id).all()

    # Send user to dance page
    return render_template('dance.html',
                           name=name,
                           email=email,
                           avatar_url=profile_pic,
                           dances=dances)
Пример #34
0
def logfb(request):
    authorization_base_url = (
        "https://www.facebook.com/dialog/oauth/?scope=user_friends,email,public_profile"
    )
    token_url = "https://graph.facebook.com/oauth/access_token/"
    # redirect_uri = 'https://pacific-shelf-88987.herokuapp.com/redirect_facebook/'
    facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
    facebook = facebook_compliance_fix(facebook)
    authorization_url, state = facebook.authorization_url(
        authorization_base_url)
    return HttpResponseRedirect(authorization_url)
    def setUp(self):
        mocker = requests_mock.Mocker()
        mocker.post(
            "https://graph.facebook.com/oauth/access_token",
            text="access_token=urlencoded",
            headers={"Content-Type": "text/plain"},
        )
        mocker.start()
        self.addCleanup(mocker.stop)

        facebook = OAuth2Session("someclientid", redirect_uri="https://i.b")
        self.session = facebook_compliance_fix(facebook)
Пример #36
0
 def facebook_oauth(self, **kw):
     Oauth = request.env['oauth.oauth']
     facebook = Oauth.sudo().get_provider('Facebook')
     callback_uri = self.get_callback_url('facebook')
     scope = ["email"]
     oauth_session = OAuth2Session(facebook.client_id,
                                   scope=scope,
                                   redirect_uri=callback_uri)
     oauth_session = facebook_compliance_fix(oauth_session)
     authorization_url, state = oauth_session.authorization_url(
         facebook.auth_endpoint)
     return http.redirect_with_hash(authorization_url)
Пример #37
0
def facebook():

    from requests_oauthlib.compliance_fixes import facebook_compliance_fix
    facebook = OAuth2Session(facebook_client_id,
                             redirect_uri=facebook_redirect_uri)
    facebook = facebook_compliance_fix(facebook)

    facebook_authorization_url, state = facebook.authorization_url(
        facebook_authorization_base_url)

    session['oauth_state'] = state
    return redirect(facebook_authorization_url)
    def setUp(self):
        mocker = requests_mock.Mocker()
        mocker.post(
            "https://graph.facebook.com/oauth/access_token",
            text="access_token=urlencoded",
            headers={"Content-Type": "text/plain"},
        )
        mocker.start()
        self.addCleanup(mocker.stop)

        facebook = OAuth2Session('foo', redirect_uri='https://i.b')
        self.session = facebook_compliance_fix(facebook)
Пример #39
0
 def __init__(self,
              client_id=creds['CLIENT_ID'],
              scope=_SCOPE,
              redirect_uri=_REDIRECT_URI,
              token=None,
              state=None):
     super().__init__(client_id=cred['CLIENT_ID'],
                      scope=scope,
                      redirect_uri=redirect_uri,
                      token=token,
                      state=state)
     self = facebook_compliance_fix(self)
Пример #40
0
    def get_user_info(self) -> Dict:
        """Method to get user info for the logged in user.

        Raises:
            UnauthorizedException: When the user is not authenticated

        Returns:
            Dict: The user profile
        """

        try:

            # Get the token
            token = self.token

            # Helper method to update the token in the session
            def token_updater(token):
                self.token = token

            # Get a session with auto-refresh of the token
            client = OAuth2Session(
                self.client_id,
                token=token,
                auto_refresh_kwargs={
                    "client_id": self.client_id,
                    "client_secret": self.client_secret,
                },
                auto_refresh_url=self.refresh_url,
                token_updater=token_updater,
            )

            if self.name == "facebook":
                facebook_compliance_fix(client)

            # Return the user info
            return client.get(self.user_profile_endpoint + "fields=" +
                              ",".join(self.fields)).json()

        except Exception:
            raise UnauthorizedException()
Пример #41
0
def fbauth(request):
    redirect_response = request.GET.get("code")
    facebook = OAuth2Session(fb_client_id, redirect_uri=fb_redirect_uri)
    facebook = facebook_compliance_fix(facebook)
    token_url = 'https://graph.facebook.com/oauth/access_token'
    token = facebook.fetch_token(token_url,
                                 client_secret=fb_client_secret,
                                 code=redirect_response)
    print("*" * 100)
    access_token = token.get("access_token")
    resp = requests.get('https://graph.facebook.com/me?access_token=%s' %
                        access_token)
    return HttpResponse(resp.content)
    def test_fetch_access_token(self):
        facebook = OAuth2Session('foo', redirect_uri='https://i.b')
        facebook = facebook_compliance_fix(facebook)

        facebook.post = mock.MagicMock()
        response = requests.Response()
        response.status_code = 200
        response._content = 'access_token=urlencoded'.encode('UTF-8')
        response.headers['Content-Type'] = 'text/plain'
        facebook.post.return_value = response

        token = facebook.fetch_token('https://mocked.out',
                                     client_secret='bar',
                                     authorization_response='https://i.b/?code=hello')
        self.assertEqual(token, {'access_token': 'urlencoded', 'token_type': 'Bearer'})
Пример #43
0
 def get_user(self, request, config, callback_url):
     oauth = OAuth2Session(
         config.client_id, scope=config.scope, redirect_uri=callback_url
     )
     oauth = facebook_compliance_fix(oauth)
     oauth.fetch_token(
         config.access_token_url,
         client_secret=config.secret,
         authorization_response=request.url,
     )
     response = oauth.get(config.request_url)
     data = response.json()
     uid = data["id"]
     display_name = data.get("name")
     return User(uid, display_name, data)
Пример #44
0
def fbredirect():
    """
    :URL: /login_with_facebook
    :Methods: GET, POST

    Redirects the user to a Facebook login page
    """

    facebook = OAuth2Session(FB_CLIENT_ID, redirect_uri=redirect_uri())
    facebook = facebook_compliance_fix(facebook)
    authorization_url, state = facebook.authorization_url(authorization_base_url)

    logger.info('Facebook redirect for ip {}, referrer was {}'.format(request.remote_addr, request.referrer))
    session['facebook_state'] = state
    return redirect('{}&scope=public_profile,email'.format(authorization_url))
Пример #45
0
	def authorization_url(self):

		try:

			redirect_uri = ''.join(('http://', IN.APP.config.app_domain, '/', 'social/callback/!', self.__type__))

			fb = OAuth2Session(self.config['client_id'], scope = self.config['scope'], redirect_uri = redirect_uri)
			fb = facebook_compliance_fix(fb)

			authorization_url, state = fb.authorization_url(self.config['authorization_url'])

			return authorization_url

		except Exception as e:
			IN.logger.debug()
    def test_fetch_access_token(self):
        facebook = OAuth2Session("foo", redirect_uri="https://i.b")
        facebook = facebook_compliance_fix(facebook)

        facebook.post = mock.MagicMock()
        response = requests.Response()
        response.status_code = 200
        response.request = mock.MagicMock()
        response._content = "access_token=urlencoded".encode("UTF-8")
        response.headers["Content-Type"] = "text/plain"
        facebook.post.return_value = response

        token = facebook.fetch_token(
            "https://mocked.out", client_secret="bar", authorization_response="https://i.b/?code=hello"
        )
        self.assertEqual(token, {"access_token": "urlencoded", "token_type": "Bearer"})
Пример #47
0
def fb_login(request):
    '''Facebook login request call.'''
    url = 'https://www.facebook.com/dialog/oauth'

    facebook = OAuth2Session(
        settings.FACEBOOK_ID,
        redirect_uri='http://localhost:8000/fb-callback/',
    )
    facebook = facebook_compliance_fix(facebook)

    authorization_url, _ = facebook.authorization_url(
        url,
        verify=False
    )

    return redirect(authorization_url)
Пример #48
0
def get_authorization_url(provider, redirect_uri):
    if provider == Provider.GOOGLE:
        scope = ['email', "profile"]
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['GOOGLE']['client_id'],
            scope=scope,
            redirect_uri=redirect_uri
        )
        authorization_url, state = p.authorization_url(GOOGLE_AUTHORIZATION_BASE_URL)

        return authorization_url, state

    elif provider == Provider.FACEBOOK:
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['FACEBOOK']['client_id'],
            redirect_uri=redirect_uri
        )

        from requests_oauthlib.compliance_fixes import facebook_compliance_fix

        p = facebook_compliance_fix(p)
        authorization_url, state = p.authorization_url(FACEBOOK_AUTHORIZATION_BASE_URL)

        return authorization_url, state

    elif provider == Provider.GITHUB or provider.upper() == Provider.GITHUB:
        p = OAuth2Session(client_id=settings.STORMPATH_SOCIAL['GITHUB']['client_id'])
        authorization_url, state = p.authorization_url(GITHUB_AUTHORIZATION_BASE_URL)

        return authorization_url, state

    elif provider == Provider.LINKEDIN:
        p = OAuth2Session(
            client_id=settings.STORMPATH_SOCIAL['LINKEDIN']['client_id'],
            redirect_uri=redirect_uri
        )

        from requests_oauthlib.compliance_fixes import linkedin_compliance_fix

        p = linkedin_compliance_fix(p)
        authorization_url, state = p.authorization_url(LINKEDIN_AUTHORIZATION_BASE_URL)

        return authorization_url, state
    else:
        raise RuntimeError('Invalid Provider {}'.format(provider))
Пример #49
0
	def fetch_token(self, key, authorization_response):

		try:

			client_id = self.config['client_id']
			token_url = self.config['token_url']
			client_secret = self.config['client_secret']

			redirect_uri = ''.join(('http://', IN.APP.config.app_domain, '/', 'social/callback/!', self.__type__))

			self.session = OAuth2Session(client_id, state = key, redirect_uri = redirect_uri)
			self.session = facebook_compliance_fix(self.session)

			token = self.session.fetch_token(token_url, client_secret = client_secret, authorization_response = authorization_response)

			return token

		except Exception as e:
			IN.logger.debug()
Пример #50
0
    def get(self, request, *args, **kwargs):
        facebook = OAuth2Session(settings.FACEBOOK_CLIENT_ID, redirect_uri=settings.FACEBOOK_REDIRECT_URI)
        facebook = facebook_compliance_fix(facebook)

        if 'code' not in self.request.GET:
            authorization_url, state = facebook.authorization_url(self.authorization_base_url)
            return HttpResponseRedirect(authorization_url)
        else:
            auth_code = self.request.GET['code']
            facebook.fetch_token(self.token_url, client_secret=settings.FACEBOOK_CLIENT_SECRET, code=auth_code)
            user_info = json.loads(
                facebook.get("https://graph.facebook.com/v2.5/me?fields={0}".format(self.fields)).text)
            username = "******".format(user_info['id'])
            email = user_info['email'] or ''

            ott = self.save_user(username, email, user_info)
            context = {
                'ott': ott,
                'redirect_url': '/stations/list'
            }
            return self.render_to_response(context)
Пример #51
0
def fblogin():
    """
    :URL: /fbauth
    :Methods: GET

    Facebook auth callback URI
    """

    logger.info('Started Facebook auth for {}, referrer was {}'.format(request.remote_addr, request.referrer))

    try:
        facebook = OAuth2Session(FB_CLIENT_ID, redirect_uri=redirect_uri(), state=session['facebook_state'])
        facebook = facebook_compliance_fix(facebook)
    except KeyError:
        flash('Unable to log in via Facebook, do you have cookies enabled for this site?')
        logger.info('Failed to find Facebook state information for {}'.format(request.remote_addr))
        return redirect_back(url_for('index'))

    try:
        token = facebook.fetch_token(token_url, client_secret=FB_SECRET_ID, authorization_response=request.url)
        response = facebook.get('https://graph.facebook.com/v2.5/me?fields=id,name,email').content
    except (MismatchingStateError, MissingTokenError) as e:
        flash('Facebook was not able to provide us with the information we need to authenticate your account.')
        logger.info('Facebook auth exception for {}: {}'.format(request.remote_addr, e))
        return redirect_back(url_for('index'))

    decoded = json.loads(response)

    user_key = 'oauth-facebook-{}'.format(decoded['id'])

    try:
        username = SiteKey(user_key)
        user = SiteUser(username.value)

        if user.accesslevel is 0:
            flash('Your account has been banned')
            logger.info('Successful Facebook auth for {} but user is banned'.format(user.username))
            session.pop('username', None)
            session.pop('facebook_id', None)
            username.delete()
            return redirect_back(url_for('index'))

        user.seen()
        session['username'] = user.username
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']
        session.permanent = True

        # This profile update block won't be needed out of testing
        profile = user.profile()
        profile.profile['facebook_id'] = session['facebook_id']
        profile.update()
        # end block

        flash('You were successfully logged in')
        logger.info('Successful Facebook auth for {} (ID {})'.format(user.username, decoded['id']))
        return redirect_back(url_for('index'))
    except NoKey:
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']

        pd = PageData();
        pd.title = "Log in with Facebook"
        logger.info('Successful Facebook auth for ID {} but this person has no linked account'.format(decoded['id']))
        return render_template('new_facebook_user.html', pd=pd)

    flash('Facebook authentication failed :(')
    logger.info('Facebook auth error for {}'.format(request.remote_addr))
    return redirect_back(url_for('index'))
Пример #52
0
 # Credentials of APP

import ssl
client_id = '1184399584913921'
client_secret = 'e5634ae345fdda136e251cae7e31091e'

# OAuth endpoints given in the Facebook API documentation
authorization_base_url = 'https://www.facebook.com/dialog/oauth'
token_url = 'https://graph.facebook.com/oauth/access_token'
redirect_uri = 'https://tdas4-ece9065-lab3-cloned-tdas4.c9users.io/'     

from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import facebook_compliance_fix
facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
facebook = facebook_compliance_fix(facebook)

# Redirect user to Facebook for authorization
authorization_url, state = facebook.authorization_url(authorization_base_url)
print 'Please go here and authorize,', authorization_url

# Get the authorization verifier code from the callback url
redirect_response = raw_input('Paste the full redirect URL here:')

# Fetch the access token
facebook.fetch_token(token_url, client_secret=client_secret,authorization_response=redirect_response)

# Fetch a protected resource, i.e. user profile
r = facebook.get('https://graph.facebook.com/me?')
print r.content
Пример #53
0
 def _compliance_fix(self, oauth_sex):
     """
     Add a compliance fix to the `OAuth2Session` in order to make it work with Facebook.
     """
     return facebook_compliance_fix(oauth_sex)
 def __init__(self):	
     self._facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
     self._facebook = facebook_compliance_fix(self._facebook)
Пример #55
0
def fb_connect(request):
    context = {
        "user": request.user,
        "site_settings": get_settings(),
        "sections": Section.objects.all(),
    }
    # Process after selecting section/page
    if request.method == "POST" and request.POST.get("action", None) == "connect":
        try:
            pages_info = request.session.pop("fb_pages_info")
            page_id = request.POST.get("page_id")
            for page_info in pages_info:
                if page_info["id"] == page_id:
                    page_token = page_info["access_token"]
                    page_name = page_info["name"]
            section = Section.objects.get(
                pk=request.POST.get("section_id", None))
            section.facebook_page_id = page_id
            section.facebook_account_handle = page_name
            section.facebook_key = page_token
            section.save()
        except:
            # TODO: make this have a red color
            request.session["message"] = "ERROR: Could not connect. Try again"

        request.session["message"] = "Successfully linked Facebook page " + \
            page_name + " to section " + section.name
        request.session.save()
        return redirect("/")

    # Print an error or print the form
    else:
        # code = request.GET.get("code", None)
        # fb_app_id = MeowSetting.objects.get(
        #     setting_key="fb_app_id").setting_value
        # site_url = MeowSetting.objects.get(
        #     setting_key="site_url").setting_value
        # fb_app_secret = MeowSetting.objects.get(
        #     setting_key="fb_app_secret").setting_value
        # request_endpoint = "https://graph.facebook.com/oauth/access_token?client_id=" + fb_app_id + \
        #     "&redirect_uri=" + site_url + "/manage/fb-connect/&client_secret=" + \
        #     fb_app_secret + "&code=" + code
        # response = requests.get(request_endpoint).text
        # regex = re.search("access_token=([^&]*)($|&$|&.+)$", response)
        # token = regex.group(1)
        token = ""
        pages_info = {}

        fb_app_id = MeowSetting.objects.get(
            setting_key="fb_app_id").setting_value
        fb_app_secret = MeowSetting.objects.get(
            setting_key="fb_app_secret").setting_value

        fb_token_url = 'https://graph.facebook.com/oauth/access_token'
        redirect_uri = MeowSetting.objects.get(
            setting_key="site_url").setting_value + '/manage/fb-connect'

        fb_code = request.GET.get('code', None)
        fb_permissions = ["manage_pages", "publish_pages"]

        facebook = OAuth2Session(fb_app_id,
                                 redirect_uri=redirect_uri,
                                 scope=fb_permissions)
        facebook = facebook_compliance_fix(facebook)
        fb_token = facebook.fetch_token(
            fb_token_url,
            client_secret=fb_app_secret,
            code=fb_code)

        token = fb_token['access_token']

        extended_token = facepy.utils.get_extended_access_token(
            token, fb_app_id, fb_app_secret)
        api = facepy.GraphAPI(oauth_token=extended_token[0])
        raw_pages_info = api.get("/me/accounts/")
        pages_info = []
        for page in raw_pages_info[u'data']:
            page_info = {
                'access_token': page[u'access_token'],
                'name': page[u'name'],
                'id': page[u'id'],
            }
            pages_info.append(page_info)
        request.session["fb_pages_info"] = pages_info
        request.session.save()

        message = {}
        if not (pages_info):
            message["mtype"] = "alert"
            message["mtext"] = "Connection to Facebook failed; try again and be sure to authorize the application and all its permissions and be sure your account is an administrator on the page."
        context["message"] = message
        context["pages"] = pages_info
        return render(request, 'scheduler/fb_connect.html', context)
Пример #56
0
 def get_auth_link(self, auth_storage, share=False):
     facebook = OAuth2Session(self._client_id, scope=scope + (["publish_actions"] if share else []), redirect_uri=web.ctx.home + self._callback_page)
     facebook = facebook_compliance_fix(facebook)
     authorization_url, state = facebook.authorization_url(authorization_base_url)
     auth_storage["oauth_state"] = state
     return authorization_url
def oauth(provider, start_oauth_login=False):
    oauth_verify = True
    oauth_provider = oauth_conf.get(provider)
    oauth_access_type = ''
    oauth_approval_prompt = ''
    if oauth_live is False:
        print('offline testing')
        oauth_verify = False
        oauth_access_type = 'offline'
        oauth_approval_prompt = "force"
        os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

    if start_oauth_login:
        oauth_session = OAuth2Session(
            oauth_provider.get('client_id'), 
            scope=oauth_provider.get('scope'), 
            redirect_uri=request.url_root + oauth_provider.get('redirect_uri'))

        if provider == 'facebook':
            oauth_session = facebook_compliance_fix(oauth_session)

        authorization_url, state = oauth_session.authorization_url(
            oauth_provider.get('auth_uri'),
            access_type=oauth_access_type,
            approval_prompt=oauth_approval_prompt)

        # State is used to prevent CSRF, keep this for later, make sure oauth returns to the same url.
        # if testing and oauth_state errors make sure you logged in with localhost and not 127.0.0.1
        session['oauth_state'] = state
        session.modified = True
        return redirect(authorization_url)

    if session.get('oauth_state', None) is None:
        flash('Something went wrong, oauth session not started')
        return redirect('/login')
    
    # allready authorised so lets handle the callback
    oauth_session = OAuth2Session(
        oauth_provider.get('client_id'), 
        state=session['oauth_state'], 
        redirect_uri=request.url_root + oauth_provider.get('redirect_uri'))

    if provider == 'facebook':
        oauth_session = facebook_compliance_fix(oauth_session)
    

    # code error is todo with authorisation response
    oauth_session.fetch_token(
        oauth_provider.get('token_uri'),
        client_secret=oauth_provider.get('client_secret'),
        authorization_response=request.url,
        verify=oauth_verify)

    # Fetch a protected resource, i.e. user profile
    response = oauth_session.get(oauth_provider.get('user_uri'))
    oauth_response = response.json()
    
    oauth_id = oauth_response.get('login') or oauth_response.get('id')
    provider_id = oauth_lookup_id.get(provider)
    oauth_user = site_user.fetch_oauth_login({
        'username': oauth_id or '',
        'provider': provider_id
    }).get()

    if oauth_user: 
        user_details = site_user.get_user_details({
            'id': oauth_user.get('user_id')
        }).get()

        # we have matched a user so login and redirect
        if user_details:
            login_user(User(user_details.get('user_id')))
            # no E-Mail so lets ask the user to set there email before allowing login
            if not user_details.get('email'):
                return redirect('/profile/change_email')
            return redirect('/profile')

    flash('Your new profile has been created, and your now logged in')

    if current_user.get_id():
        # link oauth to users account
        site_user.create_oauth_login().execute({
            'user_id': current_user.get_id(), 
            'username': oauth_id or '', 
            'provider': provider_id})
        return redirect('/profile')

    # create new user from oauth information

    new_user_details = {
        'password': '******', 
        'profile_image': oauth_response.get('picture'),
        'username': oauth_id,
        'first_name': oauth_response.get('given_name') or '',
        'last_name': oauth_response.get('family_name') or ''}

    if  oauth_response.get('email'):
        new_user_details['email']= oauth_response.get('email')

    user_id = site_user.create().execute(new_user_details)

    # register oauth login creation
    site_user.create_oauth_login().execute({
        'user_id': user_id, 
        'username': oauth_id or '', 
        'provider': provider_id})

    login_user(User(user_id))
    site_user.update_last_login().execute({'id': user_id})
    if not user_id:
        flash('Failed to create user')
        return redirect('/login')
    return redirect('/profile')
Пример #58
0
def manage(request):
    message = {}
    old_fields = {}
    error = False
    action = None
    if request.method == "POST":
        action = request.POST.get('action', None)

    if request.method == "POST" and action == "meow-switch":
        send_posts = request.POST.get('switch-x', None)
        if send_posts:
            s = MeowSetting.objects.get(setting_key="send_posts")
            old = s.setting_value
            s.setting_value = send_posts
            s.save()
            if send_posts != old:
                message = {
                    "mtype": "success",
                    "mtext": "Meow status successfully changed. Be careful out there.",
                }

    if request.method == "POST" and action == "post-site-message":
        site_message = request.POST.get('site-message', None)
        s = MeowSetting.objects.get(setting_key="site_message")
        old = s.setting_value
        s.setting_value = site_message
        s.save()
        if site_message != old:
            message = {
                "mtype": "success",
                "mtext": "Site message successfully changed",
            }

    if request.method == "POST" and action == "add-user":
        try:
            old_fields['first_name'] = request.POST['first_name']
            old_fields['last_name'] = request.POST['last_name']
            old_fields['email'] = request.POST['email']
            old_fields['username'] = request.POST['username']
            old_fields['permission'] = request.POST['permission']
            password = User.objects.make_random_password()

            u = User(username=old_fields['username'], first_name=old_fields['first_name'],
                     last_name=old_fields['last_name'], email=old_fields['email'], password="******")
            u.save()
            u.set_password(password)
            u.groups.add(Group.objects.get(name=old_fields['permission']))
            u.save()

            message = {
                "mtype": "success",
                "mtext": "User added successfully!",
            }
        except KeyError as e:
            message = {
                "mtype": "alert",
                "mtext": "User not added; please fill out all fields!",
            }
            error = True
        except IntegrityError as e:
            message = {
                "mtype": "alert",
                "mtext": "Username " + old_fields['username'] + " already exists",
            }
            error = True

        # Now send them an email with the username/pass
        if not error:
            try:
                email_message = """
Hey {first_name},

Your new Meow account is ready. Log in with:

Username: {username}
Password: {password}

at {site_url} and change your password.

Thanks,
{organization_name}
                """
                site_url = MeowSetting.objects.get(
                    setting_key='site_url').setting_value
                organization_name = MeowSetting.objects.get(
                    setting_key='organization_name').setting_value
                from_email = MeowSetting.objects.get(
                    setting_key='from_email').setting_value

                email_message = email_message.format(
                    first_name=old_fields['first_name'], username=old_fields['username'], password=password, site_url=site_url, organization_name=organization_name)
                send_mail('[' + organization_name + '] Your new meow account',
                          email_message, from_email, [old_fields['email']], fail_silently=False)
                old_fields = {}
            except:
                print(sys.exc_info()[0])
                message = {
                    "mtype": "alert",
                    "mtext": "Account created but couldn't send password to " + old_fields['email'] + ".",
                }
                old_fields = {}
                error = True

    send_posts = MeowSetting.objects.get(
        setting_key='send_posts').setting_value
    site_message = MeowSetting.objects.get(
        setting_key='site_message').setting_value

    TWITTER_CONSUMER_KEY = MeowSetting.objects.get(
        setting_key='twitter_consumer_key').setting_value
    TWITTER_CONSUMER_SECRET = MeowSetting.objects.get(
        setting_key='twitter_consumer_secret').setting_value

    twitter_auth = tweepy.OAuthHandler(
        TWITTER_CONSUMER_KEY,
        TWITTER_CONSUMER_SECRET,
        MeowSetting.objects.get(
            setting_key="site_url").setting_value + "/manage/twitter-connect/"
    )
    twitter_auth.secure = True
    twitter_auth_url = twitter_auth.get_authorization_url()
    request.session["twitter_auth_token"] = twitter_auth.request_token
    request.session.save()

    fb_app_id = MeowSetting.objects.get(setting_key="fb_app_id").setting_value
    fb_app_secret = MeowSetting.objects.get(
        setting_key="fb_app_secret").setting_value

    # TODO: find a better place for these constants
    fb_authorization_base_url = 'https://www.facebook.com/v2.10/dialog/oauth'
    fb_token_url = 'https://graph.facebook.com/oauth/access_token'
    redirect_uri = MeowSetting.objects.get(
        setting_key="site_url").setting_value + '/manage/fb-connect'
    fb_permissions = ["manage_pages", "publish_pages"]

    facebook = OAuth2Session(fb_app_id,
                             redirect_uri=redirect_uri,
                             scope=fb_permissions)
    facebook = facebook_compliance_fix(facebook)
    facebook_auth_url, state = facebook.authorization_url(
        fb_authorization_base_url)

    context = {
        "user": request.user,
        "message": message,
        "old_fields": old_fields,
        "send_posts": send_posts,
        "site_settings": get_settings(),
        "twitter_auth_url": twitter_auth_url,
        "facebook_auth_url": facebook_auth_url,
        "fb_app_id": fb_app_id
    }
    return render(request, 'scheduler/manage.html', context)
Пример #59
0
def compliance_wrapper(oauth):
  from requests_oauthlib.compliance_fixes import facebook_compliance_fix
  return facebook_compliance_fix(oauth)