Exemplo n.º 1
0
def test_get_connection(helpers, pubg_api):
    api = GraphAPI(access_token="token")
    obj_id = "19292868552"

    # image
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=
            f"https://graph.facebook.com/{pubg_api.version}/{obj_id}/picture",
            body=helpers.load_file_binary(
                "testdata/base/19292868552-picture.png"),
            content_type="image/png",
        )
        res = api.get_connection(
            object_id=obj_id,
            connection="picture",
            redirect=0,
        )
        assert res["content-type"] == "image/png"

    # data
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=
            f"https://graph.facebook.com/{pubg_api.version}/{obj_id}/picture",
            json=helpers.load_json("testdata/base/connecion_data.json"),
        )

        res = api.get_connection(object_id=obj_id, connection="picture")
        assert res["data"]["height"] == 50
Exemplo n.º 2
0
    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            existent = self.db(
                self.db.auth_user.email == user["email"]).select().first()
            if existent:
                current.session["%s_setpassword" %
                                existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user['email'],
                            password=existent.password)
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                return dict(
                    first_name=user.get('first_name', ""),
                    last_name=user.get('last_name', ""),
                    facebookid=user['id'],
                    facebook=user.get('username', user['id']),
                    nickname=str(user.get('username', '')) + str(user['id']),
                    email=user['email'],
                    # birthdate=birthday,
                    about=user.get("bio", ""),
                    website=user.get("website", ""),
                    # gender=user.get("gender", "Not specified").title(),
                    photo_source=3,
                    tagline=user.get("link", ""),
                )


# def getGraph():
#     a_token = auth.settings.login_form.accessToken()
#     return GraphAPI(a_token)
Exemplo n.º 3
0
def test_get_app_token():
    api = GraphAPI(app_id="id", app_secret="secret", access_token="token")

    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/oauth/access_token",
            json={
                "access_token": "access_token",
                "token_type": "bearer"
            },
        )

        data = api.get_app_token()
        assert data["access_token"] == "access_token"

        # initial with application_only_auth
        GraphAPI(app_id="id", app_secret="secret", application_only_auth=True)
Exemplo n.º 4
0
def test_discovery_user_media(helpers):
    username = "******"

    api = GraphAPI(access_token="token", instagram_business_id="id")
    # test with count
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/id",
            json=helpers.load_json("testdata/base/discovery_medias_p1.json"),
        )

        media = api.discovery_user_media(
            username=username,
            fields=
            "comments_count,id,like_count,media_type,media_url,permalink,timestamp",
            count=3,
            limit=5,
        )
        assert len(media["data"]) == 3

    # test with no next
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/id",
            json=helpers.load_json("testdata/base/discovery_medias_p1.json"),
        )

        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/id",
            json=helpers.load_json("testdata/base/discovery_medias_p2.json"),
        )

        media = api.discovery_user_media(
            username=username,
            fields=
            "comments_count,id,like_count,media_type,media_url,permalink,timestamp",
            count=None,
            limit=5,
        )
        assert len(media["data"]) == 10
Exemplo n.º 5
0
def test_api_initial():
    # test invalid version
    with pytest.raises(LibraryError):
        GraphAPI(version="ace")
    # test not support version
    with pytest.raises(LibraryError):
        GraphAPI(version="1.0")

    # test without access token
    with pytest.raises(LibraryError):
        GraphAPI()

    # use oauth flow
    api = GraphAPI(
        app_id="app id",
        app_secret="app secret",
        oauth_flow=True,
        base_url="https://graph.facebook.com/",
    )
Exemplo n.º 6
0
def test_get_full_connections(helpers):
    obj_id = "19292868552"

    api = GraphAPI(access_token="token", version="v11.0")
    # test with count
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url="https://graph.facebook.com/v11.0/19292868552/feed",
            json=helpers.load_json("testdata/base/full_connecions_p1.json"),
        )

        feed = api.get_full_connections(
            object_id=obj_id,
            connection="feed",
            count=3,
            limit=5,
            fields="created_time,id,message",
        )
        assert len(feed["data"]) == 3

    # test with no next
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url="https://graph.facebook.com/v11.0/19292868552/feed",
            json=helpers.load_json("testdata/base/full_connecions_p1.json"),
        )
        m.add(
            method=responses.GET,
            url="https://graph.facebook.com/v11.0/19292868552/feed",
            json=helpers.load_json("testdata/base/full_connecions_p2.json"),
        )

        feed = api.get_full_connections(
            object_id=obj_id,
            connection="feed",
            count=None,
            limit=5,
            fields="created_time,id,message",
        )
        assert len(feed["data"]) == 8
Exemplo n.º 7
0
    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            current.session.facebooklogin = True
            existent = self.db(self.db.auth_user.email == user["email"]).select().first()
            if existent:
                current.session["%s_setpassword" % existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user['email'],
                            password=existent.password
                            )
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                current.session["is_new_from"] = "facebook"
                self.db.auth.send_welcome_email(user)
                # self.db.auth.initial_user_permission(user)  # Called on profile page
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            nickname=IS_SLUG()(user.get('username', "%(first_name)s-%(last_name)s" % user) + "-" + user['id'][:5])[0],
                            email=user['email'],
                            # birthdate=birthday,
                            about=user.get("bio", ""),
                            website=user.get("website", ""),
                            # gender=user.get("gender", "Not specified").title(),
                            photo_source=3,
                            tagline=user.get("link", ""),
                            registration_type=2,
                            )
Exemplo n.º 8
0
    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            existent = self.db(self.db.auth_user.email == user["email"]).select().first()
            if existent:
                current.session["%s_setpassword" % existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user['email'],
                            password=existent.password
                            )
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            nickname=str(user.get('username', '')) + str(user['id']),
                            email=user['email'],
                            # birthdate=birthday,
                            about=user.get("bio", ""),
                            website=user.get("website", ""),
                            # gender=user.get("gender", "Not specified").title(),
                            photo_source=3,
                            tagline=user.get("link", ""),
                            )


# def getGraph():
#     a_token = auth.settings.login_form.accessToken()
#     return GraphAPI(a_token)
Exemplo n.º 9
0
def test_exchange_token(helpers):
    api = GraphAPI(access_token="token")

    page_id = "19292868552"

    # test page access token
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/{page_id}",
            json={
                "id": "19292868552",
                "access_token": "token"
            },
        )
        token = api.exchange_page_access_token(page_id=page_id)
        assert token == "token"
    # test can not exchange page access token
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/{page_id}",
            json={"id": "19292868552"},
        )
        with pytest.raises(LibraryError):
            api.exchange_page_access_token(page_id=page_id)

    # test exchange long-lived user token
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/oauth/access_token",
            json={
                "access_token": "token",
                "token_type": "bearer",
                "expires_in": 5184000,
            },
        )

        res = api.exchange_long_lived_user_access_token()
        assert res["access_token"] == "token"

    user_id = "123456"
    # test exchange long-lived page token
    with responses.RequestsMock() as m:
        m.add(
            method=responses.GET,
            url=f"https://graph.facebook.com/{api.version}/{user_id}/accounts",
            json=helpers.load_json("testdata/base/user_accounts_token.json"),
        )

        res = api.exchange_long_lived_page_access_token(user_id=user_id)
        assert len(res["data"]) == 1
        assert res["data"][0]["access_token"] == "access_token"
Exemplo n.º 10
0
def test_oauth_flow(helpers):
    with pytest.raises(LibraryError):
        api = GraphAPI(access_token="token")
        api.get_authorization_url()

    api = GraphAPI(app_id="id", app_secret="secret", oauth_flow=True)

    # test get authorization url
    _, state = api.get_authorization_url()

    # if user give authorize.
    resp = "https://localhost/?code=code&state=PyFacebook#_=_"

    with responses.RequestsMock() as m:
        m.add(
            method=responses.POST,
            url=api.EXCHANGE_ACCESS_TOKEN_URL,
            json=helpers.load_json("testdata/base/long_term_token.json"),
        )

        r = api.exchange_user_access_token(response=resp)
        assert r["access_token"] == "token"
Exemplo n.º 11
0
class FaceBookAccount(OAuthAccount):
    """OAuth impl for FaceBook"""
    AUTH_URL = "https://graph.facebook.com/oauth/authorize"
    TOKEN_URL = "https://graph.facebook.com/oauth/access_token"

    def __init__(self, db):
        self.db = db
        g = dict(GraphAPI=GraphAPI,
                 GraphAPIError=GraphAPIError,
                 request=current.request,
                 response=current.response,
                 session=current.session,
                 HTTP=HTTP)
        client = dict(db.config.get_list('auth', 'facebook'))
        OAuthAccount.__init__(self, g, client['id'], client['secret'],
                              self.AUTH_URL, self.TOKEN_URL,
                              scope='email,user_about_me,user_location,user_photos,user_relationships,user_birthday,user_website,create_event,user_events,publish_stream')
        self.graph = None

    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            current.session.facebooklogin = True
            try:
                user_email = user.get("email", False)
                if user_email:
                    existent = self.db(self.db.auth_user.email == user_email).select().first()
                else:
                    existent = False
            except:
                existent = False

            if existent:
                current.session["%s_setpassword" % existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user.get('email', existent.email),
                            password=existent.password,
                            is_active=True
                            )
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                current.session["is_new_from"] = "facebook"
                self.db.auth.send_welcome_email(user)
                # self.db.auth.initial_user_permission(user)  # Called on profile page
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user.get('id', 0),
                            facebook=user.get('username', user.get('id', 0)),
                            nickname=IS_SLUG()(user.get('username', "%(first_name)s-%(last_name)s" % user) + "-" + user['id'][:5])[0],
                            email=user.get('email', "*****@*****.**"),
                            # birthdate=birthday,
                            about=user.get("bio", ""),
                            website=user.get("website", ""),
                            # gender=user.get("gender", "Not specified").title(),
                            photo_source=3,
                            tagline=user.get("link", ""),
                            registration_type=2,
                            is_active=True
                            )
Exemplo n.º 12
0
class FaceBookAccount(OAuthAccount):
    """OAuth impl for FaceBook"""
    AUTH_URL = "https://graph.facebook.com/oauth/authorize"
    TOKEN_URL = "https://graph.facebook.com/oauth/access_token"

    def __init__(self, db):
        self.db = db
        g = dict(GraphAPI=GraphAPI,
                 GraphAPIError=GraphAPIError,
                 request=current.request,
                 response=current.response,
                 session=current.session,
                 HTTP=HTTP)
        client = dict(db.config.get_list('auth', 'facebook'))
        OAuthAccount.__init__(self, g, client['id'], client['secret'],
                              self.AUTH_URL, self.TOKEN_URL,
                              scope='email,user_about_me,user_location,user_photos,user_relationships,user_birthday,user_website,create_event,user_events,publish_stream')
        self.graph = None

    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            existent = self.db(self.db.auth_user.email == user["email"]).select().first()
            if existent:
                current.session["%s_setpassword" % existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user['email'],
                            password=existent.password
                            )
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            nickname=str(user.get('username', '')) + str(user['id']),
                            email=user['email'],
                            # birthdate=birthday,
                            about=user.get("bio", ""),
                            website=user.get("website", ""),
                            # gender=user.get("gender", "Not specified").title(),
                            photo_source=3,
                            tagline=user.get("link", ""),
                            )


# def getGraph():
#     a_token = auth.settings.login_form.accessToken()
#     return GraphAPI(a_token)
Exemplo n.º 13
0
class FaceBookAccount(OAuthAccount):
    """OAuth impl for FaceBook"""
    AUTH_URL = "https://graph.facebook.com/oauth/authorize"
    TOKEN_URL = "https://graph.facebook.com/oauth/access_token"

    def __init__(self, db):
        self.db = db
        g = dict(GraphAPI=GraphAPI,
                 GraphAPIError=GraphAPIError,
                 request=current.request,
                 response=current.response,
                 session=current.session,
                 HTTP=HTTP)
        client = dict(db.config.get_list('auth', 'facebook'))
        OAuthAccount.__init__(
            self,
            g,
            client['id'],
            client['secret'],
            self.AUTH_URL,
            self.TOKEN_URL,
            scope=
            'email,user_about_me,user_location,user_photos,user_relationships,user_birthday,user_website,create_event,user_events,publish_stream'
        )
        self.graph = None

    def get_user(self):
        session = current.session
        '''Returns the user using the Graph API.
        '''

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            existent = self.db(
                self.db.auth_user.email == user["email"]).select().first()
            if existent:
                current.session["%s_setpassword" %
                                existent.id] = existent.password
                return dict(first_name=user.get('first_name', ""),
                            last_name=user.get('last_name', ""),
                            facebookid=user['id'],
                            facebook=user.get('username', user['id']),
                            email=user['email'],
                            password=existent.password)
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                return dict(
                    first_name=user.get('first_name', ""),
                    last_name=user.get('last_name', ""),
                    facebookid=user['id'],
                    facebook=user.get('username', user['id']),
                    nickname=str(user.get('username', '')) + str(user['id']),
                    email=user['email'],
                    # birthdate=birthday,
                    about=user.get("bio", ""),
                    website=user.get("website", ""),
                    # gender=user.get("gender", "Not specified").title(),
                    photo_source=3,
                    tagline=user.get("link", ""),
                )


# def getGraph():
#     a_token = auth.settings.login_form.accessToken()
#     return GraphAPI(a_token)
Exemplo n.º 14
0
def user_api():
    return GraphAPI(app_id="123456", app_secret="xxxxx", access_token="page token")
Exemplo n.º 15
0
def pubg_api():
    return GraphAPI(app_id="123456", app_secret="xxxxx", access_token="token")