Esempio n. 1
0
def spotify_callback(request, format=None):
    code = request.GET.get("code")
    error = request.GET.get("error")

    response = post("https://accounts.spotify.com/api/token",
                    data={
                        'grant_type': 'authorization_code',
                        'code': code,
                        'redirect_uri': REDIRECT_URI,
                        'client_id': CLIENT_ID,
                        'client_secret': CLIENT_SECRET
                    }).json()

    access_token = response.get('access_token')
    token_type = response.get('token_type')
    refresh_token = response.get('refresh_token')
    expires_in = response.get('expires_in')
    error = response.get('error')

    if not request.session.exists(request.session.session_key):
        request.session.create()

    update_or_create_user_tokens(request.session.session_key, access_token,
                                 token_type, expires_in, refresh_token)

    return redirect('frontend:')
Esempio n. 2
0
def update_user_social_data(strategy, response, *args, **kwargs):
    """Set the name and avatar for a user only if is new.
    """
    # print 'update_user_social_data ::', strategy
    if not kwargs['is_new']:
        return

    full_name = ''
    backend = kwargs['backend']

    user = kwargs['user']

    if (
        isinstance(backend, GoogleOAuth2)
        or isinstance(backend, FacebookOAuth2)
    ):
        full_name = response.get('name')
    elif (
        isinstance(backend, InstagramOAuth2)
    ):

        if kwargs.get('details'):
            full_name = kwargs['details'].get('fullname')

    user.full_name = full_name

    if isinstance(backend, GoogleOAuth2):
        if response.get('image') and response['image'].get('url'):
            url = response['image'].get('url')
            url = url.split('?')[0]
            ext = url.split('.')[-1]
            image_name = 'google_avatar_%s' % user.username
            user.userprofile.avatar.save(
               '{0}.{1}'.format(image_name, ext),
               ContentFile(urllib2.urlopen(url).read())
            )
    elif isinstance(backend, FacebookOAuth2):
        fbuid = kwargs['response']['id']
        image_name = 'fb_avatar_%s.jpg' % fbuid
        image_url = 'http://graph.facebook.com/%s/picture?type=large' % fbuid
        image_stream = urlopen(image_url)

        user.avatar.save(
            image_name,
            ContentFile(image_stream.read()),
        )
    elif isinstance(backend, InstagramOAuth2):

        if response['data'].get('profile_picture'):
            image_name = 'instagram_avatar_%s.jpg' % user.username
            image_url = response['data'].get('profile_picture')
            image_stream = urlopen(image_url)

            user.userprofile.avatar.save(
                image_name,
                ContentFile(image_stream.read()),
            )

    user.save()
Esempio n. 3
0
def refresh_spotify_token(session_id):
    refresh_token = get_user_tokens(session_id).refresh_token

    response = post('https://accounts.spotify.com/api/token',
                    data={
                        'grant_type': 'refresh_token',
                        'client_id': CLIENT_ID,
                        'client_secret': CLIENT_SECRET,
                    }).json()

    access_token = response.get('access_token')
    token_type = response.get('token_type')
    expires_in = response.get('expires_in')
    refresh_token = response.get('refresh_token')

    update_or_create_user_tokens(session_id, access_token, refresh_token,
                                 token_type, expires_in)
    def test_kakaologin_get_fail_access_token_not_exist(self):
        client = Client()
        params = {'access_token': ''}
        response = client.get('/user/login/kakao',
                              data=params,
                              content_type='application/json').json()

        self.assertEqual(response.get('message'),
                         'ACCESS_TOKEN_DOES_NOT_EXIST')
Esempio n. 5
0
    def get(self, request, format=None):
        room_code = self.request.session.get('room_code')
        room = Room.objects.filter(code=room_code)
        if room.exists():
            room = room[0]
        else:
            return Response({}, status=status.HTTP_404_NOT_FOUND)
        host = room.host
        endpoint = "player/currently-playing"
        response = execute_spotify_api_request(host, endpoint)

        if 'error' in response or 'item' not in response:
            return Response({}, status=status.HTTP_204_NO_CONTENT)

        item = response.get("item")
        duration = item.get("duration_ms")
        progress = response.get("progress_ms")
        album_cover = item.get("album").get("images")[0].get("url")
        is_playing = response.get("is_playing")
        song_id = item.get("id")

        artist_string = ""
        for i, artist in enumerate(item.get("artists")):
            if i > 0:
                artist_string += ", "
            name = artist.get("name")
            artist_string += name

        nr_votes = len(Vote.objects.filter(room=room, song_id=song_id))
        song = {
            "title": item.get("name"),
            "artist": artist_string,
            "duration": duration,
            "time": progress,
            "image_url": album_cover,
            "is_playing": is_playing,
            "votes": nr_votes,
            "votes_required": room.votes_to_skip,
            "id": song_id,
        }
        self.update_room_song(room, song_id)
        return Response(song, status=status.HTTP_200_OK)
    def test_kakaologin_get_success(self):
        mock_content = {
            'id': '12345678',
            'properties': {
                'nickname': 'test_nickname'
            }
        }

        mock_response = requests.Response()
        mock_response._content = bytes(json.dumps(mock_content), 'utf-8')

        with patch('requests.get', return_value=mock_response):
            client = Client()
            params = {'access_token': 'test_access_token'}
            response = client.get('/user/login/kakao',
                                  data=params,
                                  content_type='application/json').json()

        self.assertEqual(response.get('nickname'), 'test_nickname')
        self.assertTrue(response.get('token'), True)
Esempio n. 7
0
    def get(self, request, format=None):
        room_code = self.request.session.get('room_code')
        room = Room.objects.filter(code=room_code)
        if room.exists():
            room = room[0]
        else:
            return Response({}, status=status.HTTP_404_NOT_FOUND)
        host = room.host
        endpoint = "player/currently-playing"
        response = execute_spotify_api_request(host, endpoint)

        if 'error' in response or 'item' not in response:
            return Response({}, status=status.HTTP_204_NO_CONTENT)

        item = response.get('item')
        duration = item.get('duration_ms')
        progress = response.get('progress_ms')
        album_cover = item.get('album').get('images')[0].get('url')
        is_playing = response.get('is_playing')
        song_id = item.get('id')

        artist_string = ""

        for i, artist in enumerate(item.get('artists')):
            if i > 0:
                artist_string += ", "
            name = artist.get('name')
            artist_string += name

        song = {
            'title': item.get('name'),
            'artist': artist_string,
            'duration': duration,
            'time': progress,
            'image_url': album_cover,
            'is_playing': is_playing,
            'votes': 0,
            'id': song_id
        }

        return Response(song, status=status.HTTP_200_OK)
Esempio n. 8
0
def refresh_spotify_tokens(session_id):
    refresh_token = get_token_from_db(session_id).refresh_token
    print("\n\n\n utils-->refresh_spotify_tokens session key=" +
          session_id)  ##########################
    response = post(
        URL.get("api-token"),
        data={
            "grant_type": "refresh_token",
            "refresh_token": refresh_token,
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
        },
    ).json()

    access_token = response.get("access_token")
    expires_in = response.get("expires_in")
    token_type = response.get("token_type")
    #    refresh_token = response.get("refresh_token")

    update_or_create_tokens(session_id, access_token, refresh_token,
                            token_type, expires_in)
Esempio n. 9
0
def spotify_callback(request, format=None):
    code = request.GET.get("code")
    error = request.GET.get("error")
    state = request.GET.get("state")
    print(
        "\n\n\n spotify_callback before redirect spotify session key=" +
        (request.session.session_key
         if request.session.session_key else "none")
    )  ################################################################################################
    response = post(
        URL.get("api-token"),
        data={
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "redirect_uri": REDIRECT_URI,
            "grant_type": "authorization_code",
            "code": code,
        },
    ).json()

    access_token = response.get("access_token")
    token_type = response.get("token_type")
    expires_in = response.get("expires_in")
    refresh_token = response.get("refresh_token")
    error = response.get("error")
    if not request.session.exists(request.session.session_key):
        request.session.create()
    print(
        "\n\n\n spotify_callback after redirect spotify session key=" +
        request.session.session_key
    )  ##################################################################################################
    update_or_create_tokens(
        session_id=request.session.session_key,
        access_token=access_token,
        refresh_token=refresh_token,
        token_type=token_type,
        expires_in=expires_in,
    )
    return redirect("frontend:")
    def test_kakaologin_get_fail_with_key_error(self):
        mock_content = {'id': '12345678'}

        mock_response = requests.Response()
        mock_response._content = bytes(json.dumps(mock_content), 'utf-8')

        with patch('requests.get', return_value=mock_response):
            client = Client()
            params = {'access_token': 'test_access_token'}
            response = client.get('/user/login/kakao',
                                  data=params,
                                  content_type='application/json').json()

        self.assertEqual(response.get('message'), 'KEY_ERROR')
    def test_kakaologin_get_fail_with_error_code(self):
        mock_content = {'code': -401}

        mock_response = requests.Response()
        mock_response._content = bytes(json.dumps(mock_content), 'utf-8')

        with patch('requests.get', return_value=mock_response):
            client = Client()
            params = {'access_token': 'test_access_token'}
            response = client.get('/user/login/kakao',
                                  data=params,
                                  content_type='application/json').json()

        self.assertIn('code -401', response.get('message'))
Esempio n. 12
0
def _normalize_django_response(response, request=None):
    if not _django_available:
        raise TypeError("django is not installed")

    if not isinstance(response, (django.http.response.HttpResponse)):
        raise TypeError("Cannot normalize this request object")

    url = None

    if isinstance(response, django.http.response.HttpResponseRedirect):
        url = response.url
    elif request:
        url = request.url
    else:
        raise TypeError("Normalized django object needs a path")

    return Response(request=request,
                    content=response.content,
                    url=url,
                    status_code=response.status_code,
                    content_type=response.get('Content-Type'),
                    response=response)
Esempio n. 13
0
def _normalize_django_response(response, request=None):
    if not _django_available:
        raise TypeError("django is not installed")

    if not isinstance(response, (django.http.response.HttpResponse)):
        raise TypeError("Cannot normalize this request object")

    url = None

    if isinstance(response, django.http.response.HttpResponseRedirect):
        url = response.url
    elif request:
        url = request.url
    else:
        raise TypeError("Normalized django object needs a path")

    return Response(
        request=request,
        content=response.content,
        url=url,
        status_code=response.status_code,
        content_type=response.get('Content-Type'),
        response=response)