处理Facebook取消Python中的回调授权

时间:2018-02-04 14:31:30

标签: python django facebook-login

我正在构建一个使用django-allauth使用Facebook登录的Django应用程序。我想知道用户何时删除我相应的Facebook应用程序,而Facebook以deauthorize callback的形式提供此类功能。还有一些关于如何使用PHP在documentation中解析请求的说明。

然而,将其翻译成Python似乎并不像我想象的那么容易,因为我得到了“填充错误”。解码发布的base64编码的字符串时,这对我来说似乎很奇怪。

1 个答案:

答案 0 :(得分:0)

问题似乎是必须手动将某个填充添加到发布的数据中。这是一个有效的例子:

class DeauthorizeView(View):

    def post(self, request, *args, **kwargs):
        try:
            signed_request = request.POST['signed_request']
            encoded_sig, payload = signed_request.split('.')
        except (ValueError, KeyError):
            return HttpResponse(status=400, content='Invalid request')

        try:
            # Reference for request decoding: https://developers.facebook.com/docs/games/gamesonfacebook/login#parsingsr
            # For some reason, the request needs to be padded in order to be decoded. See https://stackoverflow.com/a/6102526/2628463
            decoded_payload = base64.urlsafe_b64decode(payload + "==").decode('utf-8')
            decoded_payload = json.loads(decoded_payload)

            if type(decoded_payload) is not dict or 'user_id' not in decoded_payload.keys():
                return HttpResponse(status=400, content='Invalid payload data')

        except (ValueError, json.JSONDecodeError):
            return HttpResponse(status=400, content='Could not decode payload')

        try:
            secret = SocialApp.objects.get(id=1).secret

            sig = base64.urlsafe_b64decode(encoded_sig + "==")
            expected_sig = hmac.new(bytes(secret, 'utf-8'), bytes(payload, 'utf-8'), hashlib.sha256)
        except:
            return HttpResponse(status=400, content='Could not decode signature')

        if not hmac.compare_digest(expected_sig.digest(), sig):
            return HttpResponse(status=400, content='Invalid request')

        user_id = decoded_payload['user_id']

        try:
            social_account = SocialAccount.objects.get(uid=user_id)
        except SocialAccount.DoesNotExist:
            return HttpResponse(status=200)

        # Own custom logic here

        return HttpResponse(status=200)