Пример #1
0
class GitHubTests(create_oauth2_tests(registry.by_id(GitHubProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
            "type":"User",
            "organizations_url":"https://api.github.com/users/pennersr/orgs",
            "gists_url":"https://api.github.com/users/pennersr/gists{/gist_id}",
            "received_events_url":"https://api.github.com/users/pennersr/received_events",
            "gravatar_id":"8639768262b8484f6a3380f8db2efa5b",
            "followers":16,
            "blog":"http://www.intenct.info",
            "avatar_url":"https://secure.gravatar.com/avatar/8639768262b8484f6a3380f8db2efa5b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png",
            "login":"******",
            "created_at":"2010-02-10T12:50:51Z",
            "company":"IntenCT",
            "subscriptions_url":"https://api.github.com/users/pennersr/subscriptions",
            "public_repos":14,
            "hireable":false,
            "url":"https://api.github.com/users/pennersr",
            "public_gists":0,
            "starred_url":"https://api.github.com/users/pennersr/starred{/owner}{/repo}",
            "html_url":"https://github.com/pennersr",
            "location":"The Netherlands",
            "bio":null,
            "name":"Raymond Penners",
            "repos_url":"https://api.github.com/users/pennersr/repos",
            "followers_url":"https://api.github.com/users/pennersr/followers",
            "id":201022,
            "following":0,
            "email":"*****@*****.**",
            "events_url":"https://api.github.com/users/pennersr/events{/privacy}",
            "following_url":"https://api.github.com/users/pennersr/following"
        }""")
Пример #2
0
class TwitchTests(create_oauth2_tests(registry.by_id(TwitchProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200,
            """{"name":"test_user1","created_at":"2011-06-03T17:49:19Z","updated_at":"2012-06-18T17:19:57Z","_links":{"self":"https://api.twitch.tv/kraken/users/test_user1"},"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/test_user1-profile_image-62e8318af864d6d7-300x300.jpeg","_id":22761313,"display_name":"test_user1","email":"*****@*****.**","partnered":true}

""")
Пример #3
0
class SpotifyOAuth2Tests(
        create_oauth2_tests(registry.by_id(SpotifyOAuth2Provider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """{
          "birthdate": "1937-06-01",
          "country": "SE",
          "display_name": "JM Wizzler",
          "email": "*****@*****.**",
          "external_urls": {
            "spotify": "https://open.spotify.com/user/wizzler"
          },
          "followers" : {
            "href" : null,
            "total" : 3829
          },
          "href": "https://api.spotify.com/v1/users/wizzler",
          "id": "wizzler",
          "images": [
            {
              "height": null,
              "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc3/t1.0-1/1970403_10152215092574354_1798272330_n.jpg",
              "width": null
            }
          ],
          "product": "premium",
          "type": "user",
          "uri": "spotify:user:wizzler"
        }""")
Пример #4
0
class WeiboTests(create_oauth2_tests(registry.by_id(WeiboProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200,
            """{"bi_followers_count": 0, "domain": "", "avatar_large": "http://tp3.sinaimg.cn/3195025850/180/0/0", "block_word": 0, "star": 0, "id": 3195025850, "city": "1", "verified": false, "follow_me": false, "verified_reason": "", "followers_count": 6, "location": "\u5317\u4eac \u4e1c\u57ce\u533a", "mbtype": 0, "profile_url": "u/3195025850", "province": "11", "statuses_count": 0, "description": "", "friends_count": 0, "online_status": 0, "mbrank": 0, "idstr": "3195025850", "profile_image_url": "http://tp3.sinaimg.cn/3195025850/50/0/0", "allow_all_act_msg": false, "allow_all_comment": true, "geo_enabled": true, "name": "pennersr", "lang": "zh-cn", "weihao": "", "remark": "", "favourites_count": 0, "screen_name": "pennersr", "url": "", "gender": "f", "created_at": "Tue Feb 19 19:43:39 +0800 2013", "verified_type": -1, "following": false}

""")
Пример #5
0
class StackExchangeTests(
        create_oauth2_tests(registry.by_id(StackExchangeProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
          "has_more": false,
           "items": [
              {
                "is_employee": false,
                 "last_access_date": 1356200390,
                 "display_name": "pennersr",
                 "account_id": 291652,
                 "badge_counts": {
                     "bronze": 2,
                     "silver": 2,
                     "gold": 0
                 },
                 "last_modified_date": 1356199552,
                 "profile_image": "http://www.gravatar.com/avatar/053d648486d567d3143d6bad8df8cfeb?d=identicon&r=PG",
                 "user_type": "registered",
                 "creation_date": 1296223711,
                 "reputation_change_quarter": 148,
                 "reputation_change_year": 378,
                 "reputation": 504,
                 "link": "http://stackoverflow.com/users/593944/pennersr",
                 "reputation_change_week": 0,
                 "user_id": 593944,
                 "reputation_change_month": 10,
                 "reputation_change_day": 0
              }
           ],
           "quota_max": 10000,
           "quota_remaining": 9999
        }""")
Пример #6
0
class FirefoxAccountsTests(create_oauth2_tests(registry.by_id(FirefoxAccountsProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(200, """
        {
            "uid":"6d940dd41e636cc156074109b8092f96",
            "email":"*****@*****.**"
        }""")
Пример #7
0
class DropboxOAuth2Tests(create_oauth2_tests(registry.by_id(
        DropboxOAuth2Provider.id))):
    def get_mocked_response(self):
        return [MockedResponse(200, """{
            "display_name": "Björn Andersson",
            "name_details": {
                "surname": "Andersson",
                "familiar_name": "Björn",
                "given_name": "Björn"
                },
            "locale": "en",
            "email": "*****@*****.**",
            "uid": 1234567890,
            "email_verified": true,
            "quota_info": {
                "shared": 3195052017,
                "datastores": 0,
                "quota": 61337501696,
                "normal": 15455059441
                },
            "is_paired": true,
            "team": null,
            "referral_link": "https://db.tt/UzhBTVjU",
            "country": "SE"
        }""")]
Пример #8
0
class SoundCloudTests(
        create_oauth2_tests(registry.by_id(SoundCloudProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
           "website": null,
            "myspace_name": null,
            "public_favorites_count": 0,
            "followings_count": 1,
            "full_name": "",
            "id": 22341947,
            "city": null,
            "track_count": 0,
            "playlist_count": 0,
            "discogs_name": null,
            "private_tracks_count": 0,
            "followers_count": 0,
            "online": true,
            "username": "******",
            "description": null,
            "kind": "user",
            "website_title": null,
            "primary_email_confirmed": false,
            "permalink_url": "http://soundcloud.com/user187631676",
            "private_playlists_count": 0,
            "permalink": "user187631676",
            "country": null,
            "uri": "https://api.soundcloud.com/users/22341947",
            "avatar_url": "https://a1.sndcdn.com/images/default_avatar_large.png?4b4189b",
            "plan": "Free"
        }""")
Пример #9
0
class VKTests(create_oauth2_tests(registry.by_id(VKProvider.id))):
    def get_mocked_response(self, verified_email=True):
        return MockedResponse(
            200, """
{"response": [{"last_name": "Penners", "university_name": "", "photo": "http://vk.com/images/camera_c.gif", "sex": 2, "photo_medium": "http://vk.com/images/camera_b.gif", "relation": "0", "timezone": 1, "photo_big": "http://vk.com/images/camera_a.gif", "uid": 219004864, "universities": [], "city": "1430", "first_name": "Raymond", "faculty_name": "", "online": 1, "counters": {"videos": 0, "online_friends": 0, "notes": 0, "audios": 0, "photos": 0, "followers": 0, "groups": 0, "user_videos": 0, "albums": 0, "friends": 0}, "home_phone": "", "faculty": 0, "nickname": "", "screen_name": "id219004864", "has_mobile": 1, "country": "139", "university": 0, "graduation": 0, "activity": "", "last_seen": {"time": 1377805189}}]}
""")

    def get_login_response_json(self, with_refresh_token=True):
        return '{"user_id": 219004864, "access_token":"testac"}'
Пример #10
0
class AmazonTests(create_oauth2_tests(registry.by_id(AmazonProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(200, """
        {
          "Profile":{
                        "CustomerId":"amzn1.account.K2LI23KL2LK2",
                        "Name":"John Doe",
                        "PrimaryEmail":"*****@*****.**"
                    }
        }""")
Пример #11
0
class OdnoklassnikiTests(
        create_oauth2_tests(registry.by_id(OdnoklassnikiProvider.id))):
    def get_mocked_response(self, verified_email=True):
        return MockedResponse(
            200, """
{"uid":"561999209121","birthday":"1999-09-09","age":33,"first_name":"Ivan","last_name":"Petrov","name":"Ivan Petrov","locale":"en","gender":"male","has_email":true,"location":{"city":"Moscow","country":"RUSSIAN_FEDERATION","countryCode":"RU","countryName":"Russia"},"online":"web","pic_1":"http://i500.mycdn.me/res/stub_50x50.gif","pic_2":"http://usd1.mycdn.me/res/stub_128x96.gif"}
""")

    def get_login_response_json(self, with_refresh_token=True):
        return '{"access_token": "testac"}'  # noqa
Пример #12
0
class MailRuTests(create_oauth2_tests(registry.by_id(MailRuProvider.id))):
    def get_mocked_response(self, verified_email=True):
        return MockedResponse(200, """
[ { "uid": "15410773191172635989", "first_name": "Евгений", "last_name": "Маслов", "nick": "maslov", "email": "*****@*****.**", "sex": 0,  "birthday": "15.02.1980",  "has_pic": 1, "pic": "http://avt.appsmail.ru/mail/emaslov/_avatar",  "pic_small": "http://avt.appsmail.ru/mail/emaslov/_avatarsmall",  "pic_big": "http://avt.appsmail.ru/mail/emaslov/_avatarbig", "link": "http://my.mail.ru/mail/emaslov/", "referer_type": "", "referer_id": "", "is_online": 1, "friends_count": 145, "is_verified": 1, "vip" : 0, "app_installed": 1, "location": { "country": { "name": "Россия", "id": "24" }, "city": { "name": "Москва", "id": "25" }, "region": { "name": "Москва", "id": "999999" } } }]"""
                              )  # noqa

    def get_login_response_json(self, with_refresh_token=True):
        # FIXME: This is not an actual response. I added this in order
        # to get the test suite going but did not verify to check the
        # exact response being returned.
        return '{"access_token": "testac", "uid": "weibo", "refresh_token": "testrf", "x_mailru_vid": "1"}'  # noqa
Пример #13
0
class PaypalTests(create_oauth2_tests(registry.by_id(PaypalProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
            "user_id": "https://www.paypal.com/webapps/auth/server/64ghr894040044",
            "name": "Jane Doe",
            "given_name": "Jane",
            "family_name": "Doe",
            "email": "*****@*****.**"
        }
        """)
Пример #14
0
class LinkedInOAuth2Tests(
        create_oauth2_tests(registry.by_id(LinkedInOAuth2Provider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
{
  "emailAddress": "*****@*****.**",
  "firstName": "Raymond",
  "id": "ZLARGMFT1M",
  "lastName": "Penners",
  "pictureUrl": "http://m.c.lnkd.licdn.com/mpr/mprx/0_e0hbvSLc",
  "publicProfileUrl": "http://www.linkedin.com/in/intenct"
}
""")
Пример #15
0
class AngelListTests(create_oauth2_tests(registry.by_id(AngelListProvider.id))
                     ):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
{"name":"pennersr","id":424732,"bio":"","follower_count":0,
"angellist_url":"https://angel.co/dsxtst",
"image":"https://angel.co/images/shared/nopic.png",
"email":"*****@*****.**","blog_url":null,
"online_bio_url":null,"twitter_url":"https://twitter.com/dsxtst",
"facebook_url":null,"linkedin_url":null,"aboutme_url":null,
"github_url":null,"dribbble_url":null,"behance_url":null,
"what_ive_built":null,"locations":[],"roles":[],"skills":[],
"investor":false,"scopes":["message","talent","dealflow","comment",
"email"]}
""")
Пример #16
0
class DoubanTests(create_oauth2_tests(registry.by_id(DoubanProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
            {"name": "guoqiao",
             "created": "2009-02-18 01:07:52",
             "is_suicide": false,
             "alt": "http://www.douban.com/people/qguo/",
             "avatar": "http://img3.douban.com/icon/u3659811-3.jpg",
             "signature": "",
             "uid": "qguo",
             "is_banned": false,
             "desc": "\u4e0d\u662f\u5f88\u7231\u8bfb\u4e66",
             "type": "user",
             "id": "3659811",
             "large_avatar": "http://img3.douban.com/icon/up3659811-3.jpg"}
""")
Пример #17
0
class FeedlyTests(create_oauth2_tests(registry.by_id(FeedlyProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(200, """
        {
          "id": "c805fcbf-3acf-4302-a97e-d82f9d7c897f",
          "email": "*****@*****.**",
          "givenName": "Jim",
          "familyName": "Smith",
          "picture": "https://www.google.com/profile_images/1771656873/bigger.jpg",
          "gender": "male",
          "locale": "en",
          "reader": "9080770707070700",
          "google": "115562565652656565656",
          "twitter": "jimsmith",
          "facebook": "",
          "wave": "2013.7"
        }""")
Пример #18
0
class FoursquareTests(
        create_oauth2_tests(registry.by_id(FoursquareProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
                              {
                                "notifications": [{"item": {"unreadCount": 0}, "type": "notificationTray"}],
                                "meta": {"code": 200},
                                "response":
                                {
                                    "user":
                                    {
                                        "photo": {"prefix": "https://irs0.4sqi.net/img/user/", "suffix": "/blank_boy.png"},
                                        "pings": false,
                                        "homeCity": "Athens, ESYE31",
                                        "id": "76077726",
                                        "badges": {"count": 0, "items": []},
                                        "referralId": "u-76077726",
                                        "friends":
                                        {
                                            "count": 0,
                                            "groups": [{"count": 0, "items": [], "type": "friends", "name": "Mutual friends"}, {"count": 0, "items": [], "type": "others", "name": "Other friends"}]
                                        },
                                        "createdAt": 1389624445,
                                        "tips": {"count": 0},
                                        "type": "user",
                                        "bio": "",
                                        "relationship": "self",
                                        "lists":
                                        {
                                            "count": 1,
                                            "groups": [{"count": 1, "items": [{"description": "", "collaborative": false, "url": "/user/76077726/list/todos", "editable": false, "listItems": {"count": 0}, "id": "76077726/todos", "followers": {"count": 0}, "user": {"gender": "male", "firstName": "\u03a1\u03c9\u03bc\u03b1\u03bd\u03cc\u03c2", "relationship": "self", "photo": {"prefix": "https://irs0.4sqi.net/img/user/", "suffix": "/blank_boy.png"}, "lastName": "\u03a4\u03c3\u03bf\u03c5\u03c1\u03bf\u03c0\u03bb\u03ae\u03c2", "id": "76077726"}, "public": false, "canonicalUrl": "https://foursquare.com/user/76077726/list/todos", "name": "My to-do list"}], "type": "created"}, {"count": 0, "items": [], "type": "followed"}]
                                        },
                                        "photos": {"count": 0, "items": []},
                                        "checkinPings": "off",
                                        "scores": {"max": 0, "checkinsCount": 0, "goal": 50, "recent": 0},
                                        "checkins": {"count": 0, "items": []},
                                        "firstName": "\u03a1\u03c9\u03bc\u03b1\u03bd\u03cc\u03c2",
                                        "gender": "male",
                                        "contact": {"email": "*****@*****.**"},
                                        "lastName": "\u03a4\u03c3\u03bf\u03c5\u03c1\u03bf\u03c0\u03bb\u03ae\u03c2",
                                        "following": {"count": 0, "groups": [{"count": 0, "items": [], "type": "following", "name": "Mutual following"}, {"count": 0, "items": [], "type": "others", "name": "Other following"}]},
                                        "requests": {"count": 0}, "mayorships": {"count": 0, "items": []}}
                                    }
                                 }
""")
Пример #19
0
class HubicTests(create_oauth2_tests(registry.by_id(HubicProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
{
    "email": "*****@*****.**",
    "firstname": "Test",
    "activated": true,
    "creationDate": "2014-04-17T17:04:01+02:00",
    "language": "en",
    "status": "ok",
    "offer": "25g",
    "lastname": "User"
}
""")

    def get_login_response_json(self, with_refresh_token=True):
        return '{\
Пример #20
0
class BitlyTests(create_oauth2_tests(registry.by_id(BitlyProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """{
            "data": {
                "apiKey": "R_f6397a37e765574f2e198dba5bb59522",
                "custom_short_domain": null,
                "display_name": null,
                "full_name": "Bitly API Oauth Demo Account",
                "is_enterprise": false,
                "login": "******",
                "member_since": 1331567982,
                "profile_image": "http://bitly.com/u/bitlyapioauthdemo.png",
                "profile_url": "http://bitly.com/u/bitlyapioauthdemo",
                "share_accounts": [],
                "tracking_domains": []
            },
            "status_code": 200,
            "status_txt": "OK"
        }""")
Пример #21
0
class CoinbaseTests(create_oauth2_tests(registry.by_id(CoinbaseProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
{
  "users": [
    {
      "user": {
        "id": "512db383f8182bd24d000001",
        "name": "User One",
        "email": "*****@*****.**",
        "time_zone": "Pacific Time (US & Canada)",
        "native_currency": "USD",
        "balance": {
          "amount": "49.76000000",
          "currency": "BTC"
        },
        "merchant": {
          "company_name": "Company Name, Inc.",
          "logo": {
            "small": "http://smalllogo.example",
            "medium": "http://mediumlogo.example",
            "url": "http://logo.example"
          }
        },
        "buy_level": 1,
        "sell_level": 1,
        "buy_limit": {
          "amount": "10.00000000",
          "currency": "BTC"
        },
        "sell_limit": {
          "amount": "100.00000000",
          "currency": "BTC"
        }
      }
    }
  ]
}
        """)
Пример #22
0
class WindowsLiveTests(
        create_oauth2_tests(registry.by_id(WindowsLiveProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
          "first_name": "James",
          "last_name": "Smith",
          "name": "James Smith",
          "locale": "en_US",
          "gender": null,
          "emails": {
              "personal": null,
              "account": "*****@*****.**",
              "business": null,
              "preferred": "*****@*****.**"
              },
          "link": "https://profile.live.com/",
          "updated_time": "2014-02-07T00:35:27+0000",
          "id": "83605e110af6ff98"
        }
        """)
Пример #23
0
class InstagramTests(create_oauth2_tests(registry.by_id(InstagramProvider.id))
                     ):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
          "meta": {
            "code": 200
          },
          "data": {
            "username": "******",
            "bio": "",
            "website": "",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_11428116_75sq_1339547159.jpg",
            "full_name": "georgewhewell",
            "counts": {
              "media": 74,
              "followed_by": 91,
              "follows": 104
            },
            "id": "11428116"
          }
        }""")
Пример #24
0
class GoogleTests(create_oauth2_tests(registry.by_id(GoogleProvider.id))):
    def get_mocked_response(self,
                            family_name='Penners',
                            given_name='Raymond',
                            name='Raymond Penners',
                            email='*****@*****.**',
                            verified_email=True):
        return MockedResponse(
            200, """
              {"family_name": "%s", "name": "%s",
               "picture": "https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg",
               "locale": "nl", "gender": "male",
               "email": "%s",
               "link": "https://plus.google.com/108204268033311374519",
               "given_name": "%s", "id": "108204268033311374519",
               "verified_email": %s }
        """ % (family_name, name, email, given_name,
               (repr(verified_email).lower())))

    def test_google_compelete_login_401(self):
        from users.socialaccount.providers.google.views import GoogleOAuth2Adapter

        class LessMockedResponse(MockedResponse):
            def raise_for_status(self):
                if self.status_code != 200:
                    raise HTTPError(None)

        request = RequestFactory().get(reverse(self.provider.id + '_login'),
                                       dict(process='login'))

        adapter = GoogleOAuth2Adapter()
        app = adapter.get_provider().get_app(request)
        token = SocialToken(token='some_token')
        response_with_401 = LessMockedResponse(
            401, """
                                                {"error": {
                                                  "errors": [{
                                                    "domain": "global",
                                                    "reason": "authError",
                                                    "message": "Invalid Credentials",
                                                    "locationType": "header",
                                                    "location": "Authorization" } ],
                                                  "code": 401,
                                                  "message": "Invalid Credentials" }
                                                }""")
        with mock.patch('users.socialaccount.providers.google.views.requests'
                        ) as patched_requests:
            patched_requests.get.return_value = response_with_401
            with self.assertRaises(HTTPError):
                adapter.complete_login(request, app, token)

    def test_username_based_on_email(self):
        first_name = '明'
        last_name = '小'
        email = '*****@*****.**'
        self.login(
            self.get_mocked_response(name=first_name + ' ' + last_name,
                                     email=email,
                                     given_name=first_name,
                                     family_name=last_name,
                                     verified_email=True))
        user = User.objects.get(email=email)
        self.assertEqual(user.username, 'raymond.penners')

    def test_email_verified(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=True))
        email_address = EmailAddress.objects \
            .get(email=test_email,
                 verified=True)
        self.assertFalse(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())
        account = email_address.user.socialaccount_set.all()[0]
        self.assertEqual(account.extra_data['given_name'], 'Raymond')

    def test_user_signed_up_signal(self):
        sent_signals = []

        def on_signed_up(sender, request, user, **kwargs):
            sociallogin = kwargs['sociallogin']
            self.assertEqual(sociallogin.account.provider, GoogleProvider.id)
            self.assertEqual(sociallogin.account.user, user)
            sent_signals.append(sender)

        user_signed_up.connect(on_signed_up)
        self.login(self.get_mocked_response(verified_email=True))
        self.assertTrue(len(sent_signals) > 0)

    def test_email_unverified(self):
        test_email = '*****@*****.**'
        resp = self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertFalse(email_address.verified)
        self.assertTrue(
            EmailConfirmation.objects.filter(
                email_address__email=test_email).exists())
        self.assertTemplateUsed(
            resp, 'account/email/email_confirmation_signup_subject.txt')

    def test_email_verified_stashed(self):
        # http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
        request = RequestFactory().get('/')
        request.session = self.client.session
        adapter = get_adapter()
        test_email = '*****@*****.**'
        adapter.stash_verified_email(request, test_email)
        request.session.save()

        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertTrue(email_address.verified)
        self.assertFalse(EmailConfirmation.objects \
                             .filter(email_address__email=test_email) \
                             .exists())

    def test_account_connect(self):
        email = '*****@*****.**'
        user = User.objects.create(username='******',
                                   is_active=True,
                                   email=email)
        user.set_password('test')
        user.save()
        EmailAddress.objects.create(user=user,
                                    email=email,
                                    primary=True,
                                    verified=True)
        self.client.login(username=user.username, password='******')
        self.login(self.get_mocked_response(verified_email=True),
                   process='connect')
        # Check if we connected...
        self.assertTrue(
            SocialAccount.objects.filter(user=user,
                                         provider=GoogleProvider.id).exists())
        # For now, we do not pick up any new e-mail addresses on connect
        self.assertEqual(EmailAddress.objects.filter(user=user).count(), 1)
        self.assertEqual(
            EmailAddress.objects.filter(user=user, email=email).count(), 1)

    @override_settings(ACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.MANDATORY,
                       SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.NONE)
    def test_social_email_verification_skipped(self):
        test_email = '*****@*****.**'
        self.login(self.get_mocked_response(verified_email=False))
        email_address = EmailAddress.objects \
            .get(email=test_email)
        self.assertFalse(email_address.verified)
        self.assertFalse(EmailConfirmation.objects \
                            .filter(email_address__email=test_email) \
                            .exists())

    @override_settings(ACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.OPTIONAL,
                       SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.
                       EmailVerificationMethod.OPTIONAL)
    def test_social_email_verification_optional(self):
        self.login(self.get_mocked_response(verified_email=False))
        self.assertEqual(len(mail.outbox), 1)
        self.login(self.get_mocked_response(verified_email=False))
        self.assertEqual(len(mail.outbox), 1)
Пример #25
0
class FacebookTests(create_oauth2_tests(registry.by_id(FacebookProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
           "id": "630595557",
           "name": "Raymond Penners",
           "first_name": "Raymond",
           "last_name": "Penners",
           "email": "*****@*****.**",
           "link": "https://www.facebook.com/raymond.penners",
           "username": "******",
           "birthday": "07/17/1973",
           "work": [
              {
                 "employer": {
                    "id": "204953799537777",
                    "name": "IntenCT"
                 }
              }
           ],
           "timezone": 1,
           "locale": "nl_NL",
           "verified": true,
           "updated_time": "2012-11-30T20:40:33+0000"
        }""")

    def test_username_conflict(self):
        User = get_user_model()
        User.objects.create(username='******')
        self.login(self.get_mocked_response())
        socialaccount = SocialAccount.objects.get(uid='630595557')
        self.assertEqual(socialaccount.user.username, 'raymond')

    def test_username_based_on_provider(self):
        self.login(self.get_mocked_response())
        socialaccount = SocialAccount.objects.get(uid='630595557')
        self.assertEqual(socialaccount.user.username, 'raymond.penners')

    def test_media_js(self):
        provider = providers.registry.by_id(FacebookProvider.id)
        request = RequestFactory().get(reverse('account_login'))
        request.session = {}
        script = provider.media_js(request)
        self.assertTrue('"appId": "app123id"' in script)

    def test_login_by_token(self):
        resp = self.client.get(reverse('account_login'))
        with patch('users.socialaccount.providers.facebook.views'
                   '.requests') as requests_mock:
            mocks = [self.get_mocked_response().json()]
            requests_mock.get.return_value.json \
                = lambda: mocks.pop()
            resp = self.client.post(reverse('facebook_login_by_token'),
                                    data={'access_token': 'dummy'})
            self.assertEqual('http://testserver/accounts/profile/',
                             resp['location'])

    @override_settings(
        SOCIALACCOUNT_PROVIDERS={
            'facebook': {
                'AUTH_PARAMS': {
                    'auth_type': 'reauthenticate'
                },
                'VERIFIED_EMAIL': False
            }
        })
    def test_login_by_token_reauthenticate(self):
        resp = self.client.get(reverse('account_login'))
        nonce = json.loads(
            resp.context['fb_data'])['loginOptions']['auth_nonce']
        with patch('users.socialaccount.providers.facebook.views'
                   '.requests') as requests_mock:
            mocks = [self.get_mocked_response().json(), {'auth_nonce': nonce}]
            requests_mock.get.return_value.json \
                = lambda: mocks.pop()
            resp = self.client.post(reverse('facebook_login_by_token'),
                                    data={'access_token': 'dummy'})
            self.assertEqual('http://testserver/accounts/profile/',
                             resp['location'])

    @override_settings(
        SOCIALACCOUNT_PROVIDERS={'facebook': {
            'VERIFIED_EMAIL': True
        }})
    def test_login_verified(self):
        emailaddress = self._login_verified()
        self.assertTrue(emailaddress.verified)

    def test_login_unverified(self):
        emailaddress = self._login_verified()
        self.assertFalse(emailaddress.verified)

    def _login_verified(self):
        resp = self.login(self.get_mocked_response())
        return EmailAddress.objects.get(email='*****@*****.**')
Пример #26
0
class OrcidTests(create_oauth2_tests(registry.by_id(OrcidProvider.id))):
    def get_mocked_response(self):
        return MockedResponse(
            200, """
        {
            "message-version": "1.1",
            "orcid-profile": {
                "orcid-bio": {
                    "personal-details": {
                        "given-names": {
                            "value": "myname"
                        },
                        "other-names": {
                            "other-name": [
                                {
                                    "value": "myself"
                                }
                            ],
                            "visibility": "PUBLIC"
                        },
                        "family-name": {
                            "value": "mylastname"
                        }
                    },
                    "delegation": null,
                    "applications": null,
                    "contact-details": {
                        "email": [],
                        "address": {
                            "country": {
                                "value": "AR",
                                "visibility": "PUBLIC"
                            }
                        }
                    },
                    "keywords": {
                        "keyword": [
                            {
                                "value": "basil"
                            },
                            {
                                "value": "pizza"
                            }
                        ],
                        "visibility": "PUBLIC"
                    },
                    "scope": null,
                    "biography": {
                        "value": "mybio",
                        "visibility": "PUBLIC"
                    }
                },
                "group-type": null,
                "orcid-activities": {
                    "affiliations": null,
                    "orcid-works": {
                        "scope": null,
                        "orcid-work": [
                            {
                                "put-code": "394644",
                                "work-title": {
                                    "subtitle": null,
                                    "title": {
                                        "value": "titlepaper"
                                    }
                                },
                                "visibility": "PUBLIC",
                                "work-type": "CONFERENCE_PAPER",
                                "url": null,
                                "work-contributors": {
                                    "contributor": [
                                        {
                                            "contributor-attributes": {},
                                            "credit-name": {
                                                "value": "myname",
                                                "visibility": "PUBLIC"
                                            }
                                        }
                                    ]
                                },
                                "work-source": {
                                    "path": "0000-0001-6796-198X",
                                    "host": "sandbox.orcid.org",
                                    "uri": "http://sandbox.orcid.org/...98X",
                                    "value": null
                                }
                            }
                        ]
                    }
                },
                "orcid": null,
                "client-type": null,
                "orcid-history": {
                    "last-modified-date": {
                        "value": 1406058219693
                    },
                    "creation-method": "WEBSITE",
                    "submission-date": {
                        "value": 1405935036511
                    },
                    "visibility": null,
                    "source": null,
                    "claimed": {
                        "value": true
                    }
                },
                "type": "USER",
                "orcid-preferences": {
                    "locale": "EN"
                },
                "orcid-identifier": {
                    "path": "0000-0001-6796-198X",
                    "host": "sandbox.orcid.org",
                    "uri": "http://sandbox.orcid.org/0000-0001-6796-198X",
                    "value": null
                }
            }
        }""")

    def get_login_response_json(self, with_refresh_token=True):
        # FIXME: This is not an actual response. I added this in order
        # to get the test suite going but did not verify to check the
        # exact response being returned.
        return """