コード例 #1
0
ファイル: tasks.py プロジェクト: asimihsan/djangokata
    def run(self, social_user_pk, **kwargs):
        """Inputs:

        social_user_pk: Integer for the primary key of the UserSocialAuth
        object.
        """

        logger = self.get_logger(**kwargs)
        task_id = kwargs.get("task_id", "")
        logger.info("Starting request %s. social_user_pk = %s" %
                (task_id, social_user_pk))
        try:
            # -----------------------------------------------------------------
            #   Validate inputs.
            # -----------------------------------------------------------------
            social_user = UserSocialAuth.objects.get(pk = social_user_pk)
            user = social_user.user
            account = user.get_profile()
            logger.info("social_user: %s, user: %s, account: %s" % (social_user, user, account))
            # -----------------------------------------------------------------

            # -----------------------------------------------------------------
            #   Set the Gravatar profile image URI, if we have an
            #   email address and if an associated Gravatar image exists.
            #
            #   Gravatar's SSL certificate doesn't match the hostname they
            #   ultimate serve images from, so we need to disable
            #   certificate checking.
            # -----------------------------------------------------------------
            email = user.email
            if email != '':
                logger.info("email address '%s' available so try to get gravatar profile image URI." % email)
                email_hash = hashlib.md5(email.strip().lower()).hexdigest()
                profile_image_uri = GRAVATAR_PROFILE_PICTURE_URL_TEMPLATE.substitute(email_hash = email_hash)
                logger.info("HTTP HEAD for URI: %s" % profile_image_uri)
                if requests.head(profile_image_uri, timeout=5, verify=False):
                    logger.info("gravatar profile image exists.")
                    r = requests.get(profile_image_uri, timeout=5, verify=False)
                    r.raise_for_status()
                    existing_gravatar_profile_image = account.get_profile_image_of_source("gravatar")
                    if existing_gravatar_profile_image is not None:
                        logger.info("deleting existing_gravatar_profile_image: %s" % existing_gravatar_profile_image)
                        existing_gravatar_profile_image.delete()
                    temporary_file_filepath = save_binary_data_as_image_to_temporary_file(logger,
                                                                                          r.raw.data)
                    with open(temporary_file_filepath, "rb") as f_in:
                        logger.info("opened %s, will save to image." % temporary_file_filepath)
                        imagefile_object = ImageFile(f_in)
                        profile_image_uuid = uuid.uuid4().hex
                        profile_image = ProfileImage(user = user,
                                                     uuid = profile_image_uuid,
                                                     source = "gravatar")
                        profile_image.image.save("%s.jpeg" % profile_image_uuid,
                                                 imagefile_object)
                        profile_image.save()
                    logger.info("deleting: %s" % temporary_file_filepath)
                    os.remove(temporary_file_filepath)
            # -----------------------------------------------------------------
        except:
            logger.exception("UpdateGravatarImageTask_%s: unhandled exception." % (kwargs.get("task_id", "")))
            raise
        return True
コード例 #2
0
ファイル: tasks.py プロジェクト: asimihsan/djangokata
    def run(self, social_user_pk, **kwargs):
        """Inputs:

        social_user_pk: Integer for the primary key of the UserSocialAuth
        object.
        """

        logger = self.get_logger(**kwargs)
        task_id = kwargs.get("task_id", "")
        logger.info("Starting request %s. social_user_pk = %s" %
                (task_id, social_user_pk))
        try:
            # -----------------------------------------------------------------
            #   Validate inputs.
            # -----------------------------------------------------------------
            social_user = UserSocialAuth.objects.get(pk = social_user_pk)
            user = social_user.user
            account = user.get_profile()
            logger.info("social_user: %s, user: %s, account: %s" % (social_user, user, account))
            if social_user.provider not in ["facebook", "twitter", "google-oauth2"]:
                logger.error("Don't know how to get profile picture for backend: %s" % social_user.provider)
                return False
            # -----------------------------------------------------------------

            # -----------------------------------------------------------------
            #   Determine what the profile image URI is.
            # -----------------------------------------------------------------
            if social_user.provider == "facebook":
                logger.info("facebook is the provider")
                profile_image_uri = FACEBOOK_PROFILE_PICTURE_URL_TEMPLATE.substitute(uid = social_user.uid)
            elif social_user.provider == "twitter":
                logger.info("twitter is the provider")
                json_request_uri = TWITTER_PROFILE_PICTURE_URL_TEMPLATE.substitute(uid = social_user.uid)
                logger.info("HTTP GET for JSON URI: %s" % json_request_uri)
                r = requests.get(json_request_uri, timeout=5)
                if r.status_code != 200:
                    logger.error("HTTP GET for JSON returns non-200 with response:\n%s" % r.text)
                r.raise_for_status()
                json_obj = json.loads(r.text)
                root_keys = json_obj[0]
                profile_image_uri = root_keys["profile_image_url_https"]
            else:
                assert(social_user.provider == "google-oauth2")
                logger.info("google is the provider")
                access_token = social_user.extra_data["access_token"]
                json_request_uri = GOOGLE_PROFILE_PICTURE_URL_TEMPLATE.substitute(access_token = access_token)
                logger.info("HTTP GET for JSON URI: %s" % json_request_uri)
                r = requests.get(json_request_uri, timeout=5)
                if r.status_code != 200:
                    logger.error("HTTP GET for JSON returns non-200 with response:\n%s" % r.text)
                r.raise_for_status()
                json_obj = json.loads(r.text)
                profile_image_uri = json_obj["picture"]
            # -----------------------------------------------------------------

            # -----------------------------------------------------------------
            #   Set the profile image URI and the respective image's
            #   dimensions on the social_auth 'extra_data' JSONField.
            # -----------------------------------------------------------------
            logger.info("HTTP HEAD for URI: %s" % profile_image_uri)
            if requests.head(profile_image_uri, timeout=5).ok:
                logger.info("HTTP GET for profile image at URI to: %s" % profile_image_uri)
                r = requests.get(profile_image_uri, timeout=5)
                r.raise_for_status()

                # Delete existing profile image.
                existing_profile_image = account.get_profile_image_of_source(social_user.provider)
                if existing_profile_image is not None:
                    logger.info("deleting existing_profile_image: %s" % existing_profile_image)
                    existing_profile_image.delete()

                temporary_file_filepath = save_binary_data_as_image_to_temporary_file(logger,
                                                                                      r.raw.data)
                with open(temporary_file_filepath, "rb") as f_in:
                    logger.info("opened %s, will save to image." % temporary_file_filepath)
                    imagefile_object = ImageFile(f_in)
                    profile_image_uuid = uuid.uuid4().hex
                    profile_image = ProfileImage(user = user,
                                                 uuid = profile_image_uuid,
                                                 source = social_user.provider)
                    profile_image.image.save("%s.jpeg" % profile_image_uuid,
                                             imagefile_object)
                    profile_image.save()
                    logger.info("saved profile_image: %s" % profile_image)
                logger.info("deleting: %s" % temporary_file_filepath)
                os.remove(temporary_file_filepath)
            # -----------------------------------------------------------------

        except:
            logger.exception("UpdateProfileImageTask_%s: unhandled exception." % (kwargs.get("task_id", "")))
            raise
        return True