Esempio n. 1
0
    def __init__(self, **kwargs):
        request_cache_dict = DEFAULT_REQUEST_CACHE.data
        store = modulestore()

        services = kwargs.setdefault('services', {})
        user = kwargs.get('user')
        if user and user.is_authenticated:
            services['completion'] = CompletionService(
                user=user, context_key=kwargs.get('course_id'))
        services['fs'] = xblock.reference.plugins.FSService()
        services['i18n'] = ModuleI18nService
        services['library_tools'] = LibraryToolsService(
            store, user_id=user.id if user else None)
        services['partitions'] = PartitionService(
            course_id=kwargs.get('course_id'), cache=request_cache_dict)
        services['settings'] = SettingsService()
        services['user_tags'] = UserTagsService(self)
        if badges_enabled():
            services['badging'] = BadgingService(
                course_id=kwargs.get('course_id'), modulestore=store)
        self.request_token = kwargs.pop('request_token', None)
        services['teams'] = TeamsService()
        services['teams_configuration'] = TeamsConfigurationService()
        services['call_to_action'] = CallToActionService()
        super(LmsModuleSystem, self).__init__(**kwargs)
Esempio n. 2
0
    def handle(self, *args, **options):

        # Scrub the username from the log message
        cleaned_options = copy.copy(options)
        if 'username' in cleaned_options:
            cleaned_options['username'] = '******'
        LOGGER.info((u"Starting to create tasks to regenerate certificates "
                     u"with arguments %s and options %s"), text_type(args),
                    text_type(cleaned_options))

        # try to parse out the course from the serialized form
        course_id = CourseKey.from_string(options['course'])
        user = options['username']

        if '@' in user:
            student = User.objects.get(email=user,
                                       courseenrollment__course_id=course_id)
        else:
            student = User.objects.get(username=user,
                                       courseenrollment__course_id=course_id)

        course = modulestore().get_course(course_id, depth=2)

        if not options['noop']:
            LOGGER.info(
                (u"Adding task to the XQueue to generate a certificate "
                 u"for student %s in course '%s'."), student.id, course_id)

            if badges_enabled() and course.issue_badges:
                badge_class = get_completion_badge(course_id, student)
                badge = badge_class.get_for_user(student)

                if badge:
                    badge.delete()
                    LOGGER.info(u"Cleared badge for student %s.", student.id)

            # Add the certificate request to the queue
            ret = regenerate_user_certificates(
                student,
                course_id,
                course=course,
                forced_grade=options['grade_value'],
                template_file=options['template_file'],
                insecure=options['insecure'])

            LOGGER.info(
                (u"Added a certificate regeneration task to the XQueue "
                 u"for student %s in course '%s'. "
                 u"The new certificate status is '%s'."), student.id,
                text_type(course_id), ret)

        else:
            LOGGER.info((u"Skipping certificate generation for "
                         u"student %s in course '%s' "
                         u"because the noop flag is set."), student.id,
                        text_type(course_id))

        LOGGER.info((u"Finished regenerating certificates command for "
                     u"user %s and course '%s'."), student.id,
                    text_type(course_id))
Esempio n. 3
0
def _update_badge_context(context, course, user):
    """
    Updates context with badge info.
    """
    badge = None
    if badges_enabled() and course.issue_badges:
        badges = get_completion_badge(course.location.course_key, user).get_for_user(user)
        if badges:
            badge = badges[0]
    context['badge'] = badge
    def handle(self, *args, **options):

        # Scrub the username from the log message
        cleaned_options = copy.copy(options)
        if 'username' in cleaned_options:
            cleaned_options['username'] = '******'
        LOGGER.info(("Starting to create tasks to regenerate certificates "
                     "with arguments %s and options %s"), str(args),
                    str(cleaned_options))

        # try to parse out the course from the serialized form
        course_id = CourseKey.from_string(options['course'])
        user = options['username']

        kwargs = (Q(username=user)
                  | Q(email=user)) & Q(courseenrollment__course_id=course_id)
        student = User.objects.filter(kwargs).first()
        if not student:
            raise CommandError(f"User {user} does not exist.")

        course = modulestore().get_course(course_id, depth=2)

        if not options['noop']:
            LOGGER.info(("Adding task to the XQueue to generate a certificate "
                         "for student %s in course '%s'."), student.id,
                        course_id)

            if badges_enabled() and course.issue_badges:
                badge_class = get_completion_badge(course_id, student)
                badge = badge_class.get_for_user(student)

                if badge:
                    badge.delete()
                    LOGGER.info("Cleared badge for student %s.", student.id)

            # Add the certificate request to the queue
            regenerate_user_certificates(
                student,
                course_id,
                forced_grade=options['grade_value'],
                template_file=options['template_file'],
                insecure=options['insecure'])

            LOGGER.info(("Added a certificate regeneration task to the XQueue "
                         "for student %s in course '%s'."), student.id,
                        str(course_id))

        else:
            LOGGER.info(("Skipping certificate generation for "
                         "student %s in course '%s' "
                         "because the noop flag is set."), student.id,
                        str(course_id))

        LOGGER.info(("Finished regenerating certificates command for "
                     "user %s and course '%s'."), student.id, str(course_id))
Esempio n. 5
0
    def to_representation(self, user):
        """
        Overwrite to_native to handle custom logic since we are serializing two models as one here
        :param user: User object
        :return: Dict serialized account
        """
        profile = user.profile
        accomplishments_shared = badges_enabled()

        data = {
            "username": user.username,
            "url": self.context.get('request').build_absolute_uri(
                reverse('accounts_api', kwargs={'username': user.username})
            ),
            "email": user.email,
            # For backwards compatibility: Tables created after the upgrade to Django 1.8 will save microseconds.
            # However, mobile apps are not expecting microsecond in the serialized value. If we set it to zero the
            # DRF JSONEncoder will not include it in the serialized value.
            # https://docs.djangoproject.com/en/1.8/ref/databases/#fractional-seconds-support-for-time-and-datetime-fields
            "date_joined": user.date_joined.replace(microsecond=0),
            "is_active": user.is_active,
            "bio": AccountLegacyProfileSerializer.convert_empty_to_None(profile.bio),
            "country": AccountLegacyProfileSerializer.convert_empty_to_None(profile.country.code),
            "profile_image": AccountLegacyProfileSerializer.get_profile_image(
                profile,
                user,
                self.context.get('request')
            ),
            "time_zone": None,
            "language_proficiencies": LanguageProficiencySerializer(
                profile.language_proficiencies.all(),
                many=True
            ).data,
            "name": profile.name,
            "gender": AccountLegacyProfileSerializer.convert_empty_to_None(profile.gender),
            "goals": profile.goals,
            "year_of_birth": profile.year_of_birth,
            "level_of_education": AccountLegacyProfileSerializer.convert_empty_to_None(profile.level_of_education),
            "mailing_address": profile.mailing_address,
            "requires_parental_consent": profile.requires_parental_consent(),
            "accomplishments_shared": accomplishments_shared,
            "account_privacy": get_profile_visibility(profile, user, self.configuration),
        }

        if self.custom_fields:
            fields = self.custom_fields
        else:
            fields = _visible_fields(profile, user, self.configuration)

        return self._filter_fields(
            fields,
            data
        )
Esempio n. 6
0
    def to_representation(self, user):
        """
        Overwrite to_native to handle custom logic since we are serializing two models as one here
        :param user: User object
        :return: Dict serialized account
        """
        try:
            user_profile = user.profile
        except ObjectDoesNotExist:
            user_profile = None
            LOGGER.warning("user profile for the user [%s] does not exist",
                           user.username)

        accomplishments_shared = badges_enabled()

        data = {
            "id":
            user.id,
            "username":
            user.username,
            "url":
            self.context.get('request').build_absolute_uri(
                reverse('accounts_api', kwargs={'username': user.username})),
            "email":
            user.email,
            # For backwards compatibility: Tables created after the upgrade to Django 1.8 will save microseconds.
            # However, mobile apps are not expecting microsecond in the serialized value. If we set it to zero the
            # DRF JSONEncoder will not include it in the serialized value.
            # https://docs.djangoproject.com/en/1.8/ref/databases/#fractional-seconds-support-for-time-and-datetime-fields
            "date_joined":
            user.date_joined.replace(microsecond=0),
            "is_active":
            user.is_active,
            "bio":
            None,
            "country":
            None,
            "profile_image":
            None,
            "language_proficiencies":
            None,
            "name":
            None,
            "gender":
            None,
            "goals":
            None,
            "year_of_birth":
            None,
            "level_of_education":
            None,
            "mailing_address":
            None,
            "requires_parental_consent":
            None,
            "accomplishments_shared":
            accomplishments_shared,
            "account_privacy":
            self.configuration.get('default_visibility'),
            "social_links":
            None,
            "extended_profile_fields":
            None,
        }

        if user_profile:
            data.update({
                "bio":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.bio),
                "country":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.country.code),
                "profile_image":
                AccountLegacyProfileSerializer.get_profile_image(
                    user_profile, user, self.context.get('request')),
                "language_proficiencies":
                LanguageProficiencySerializer(
                    user_profile.language_proficiencies.all(), many=True).data,
                "name":
                user_profile.name,
                "gender":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.gender),
                "goals":
                user_profile.goals,
                "year_of_birth":
                user_profile.year_of_birth,
                "level_of_education":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.level_of_education),
                "mailing_address":
                user_profile.mailing_address,
                "requires_parental_consent":
                user_profile.requires_parental_consent(),
                "account_privacy":
                get_profile_visibility(user_profile, user, self.configuration),
                "social_links":
                SocialLinkSerializer(user_profile.social_links.all(),
                                     many=True).data,
                "extended_profile":
                get_extended_profile(user_profile),
            })

        if self.custom_fields:
            fields = self.custom_fields
        elif user_profile:
            fields = _visible_fields(user_profile, user, self.configuration)
        else:
            fields = self.configuration.get('public_fields')

        return self._filter_fields(fields, data)
Esempio n. 7
0
def learner_profile_context(request, profile_username, user_is_staff):
    """Context for the learner profile page.

    Args:
        logged_in_user (object): Logged In user.
        profile_username (str): username of user whose profile is requested.
        user_is_staff (bool): Logged In user has staff access.
        build_absolute_uri_func ():

    Returns:
        dict

    Raises:
        ObjectDoesNotExist: the specified profile_username does not exist.
    """
    profile_user = User.objects.get(username=profile_username)
    logged_in_user = request.user

    own_profile = (logged_in_user.username == profile_username)

    account_settings_data = get_account_settings(request,
                                                 [profile_username])[0]

    preferences_data = get_user_preferences(profile_user, profile_username)

    context = {
        'own_profile':
        own_profile,
        'platform_name':
        configuration_helpers.get_value('platform_name',
                                        settings.PLATFORM_NAME),
        'data': {
            'profile_user_id':
            profile_user.id,
            'default_public_account_fields':
            settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'],
            'default_visibility':
            settings.ACCOUNT_VISIBILITY_CONFIGURATION['default_visibility'],
            'accounts_api_url':
            reverse("accounts_api", kwargs={'username': profile_username}),
            'preferences_api_url':
            reverse('preferences_api', kwargs={'username': profile_username}),
            'preferences_data':
            preferences_data,
            'account_settings_data':
            account_settings_data,
            'profile_image_upload_url':
            reverse('profile_image_upload',
                    kwargs={'username': profile_username}),
            'profile_image_remove_url':
            reverse('profile_image_remove',
                    kwargs={'username': profile_username}),
            'profile_image_max_bytes':
            settings.PROFILE_IMAGE_MAX_BYTES,
            'profile_image_min_bytes':
            settings.PROFILE_IMAGE_MIN_BYTES,
            'account_settings_page_url':
            reverse('account_settings'),
            'has_preferences_access':
            (logged_in_user.username == profile_username or user_is_staff),
            'own_profile':
            own_profile,
            'country_options':
            list(countries),
            'find_courses_url':
            marketing_link('COURSES'),
            'language_options':
            settings.ALL_LANGUAGES,
            'badges_logo':
            staticfiles_storage.url('certificates/images/backpack-logo.png'),
            'badges_icon':
            staticfiles_storage.url(
                'certificates/images/ico-mozillaopenbadges.png'),
            'backpack_ui_img':
            staticfiles_storage.url('certificates/images/backpack-ui.png'),
            'platform_name':
            configuration_helpers.get_value('platform_name',
                                            settings.PLATFORM_NAME),
            'social_platforms':
            settings.SOCIAL_PLATFORMS,
        },
        'show_program_listing':
        ProgramsApiConfig.is_enabled(),
        'show_dashboard_tabs':
        True,
        'disable_courseware_js':
        True,
        'nav_hidden':
        True,
        'records_url':
        get_credentials_records_url(),
    }

    if own_profile or user_is_staff:
        achievements_fragment = LearnerAchievementsFragmentView(
        ).render_to_fragment(
            request,
            username=profile_user.username,
            own_profile=own_profile,
        )
        context['achievements_fragment'] = achievements_fragment

    if badges_enabled():
        context['data']['badges_api_url'] = reverse(
            "badges_api:user_assertions",
            kwargs={'username': profile_username})

    return context
Esempio n. 8
0
def learner_profile_context(request, profile_username, user_is_staff):
    """Context for the learner profile page.

    Args:
        logged_in_user (object): Logged In user.
        profile_username (str): username of user whose profile is requested.
        user_is_staff (bool): Logged In user has staff access.
        build_absolute_uri_func ():

    Returns:
        dict

    Raises:
        ObjectDoesNotExist: the specified profile_username does not exist.
    """
    profile_user = User.objects.get(username=profile_username)
    logged_in_user = request.user

    own_profile = (logged_in_user.username == profile_username)

    account_settings_data = get_account_settings(request,
                                                 [profile_username])[0]

    preferences_data = get_user_preferences(profile_user, profile_username)

    #Added by Mahendra
    user_enrolled_courses = CourseEnrollment.objects.filter(
        user_id=profile_user.id, is_active=1)
    cid = []
    for courseid in user_enrolled_courses:
        course_id = courseid.course_id
        cid.append(course_id)

    instructor_courses = CourseAccessRole.objects.filter(
        user_id=profile_user.id, role='instructor')
    instrsuctor_courseids = []
    for courseid in instructor_courses:
        course_id = courseid.course_id
        instrsuctor_courseids.append(course_id)

    try:
        userprofile_extrainfo = extrafields.objects.get(
            user_id=profile_user.id)
    except Exception as e:
        userprofile_extrainfo, created = extrafields.objects.get_or_create(
            user_id=profile_user.id)

    course_data = CourseOverview.objects.all().filter(
        pk__in=cid).order_by('start')[::-1]
    instructor_course_delivered = CourseOverview.objects.all().filter(
        pk__in=instrsuctor_courseids).order_by('start')[::-1]
    experience_data = experience.objects.all().filter(
        user=profile_user.id).order_by('-year')
    education_data = education.objects.all().filter(
        user=profile_user.id).order_by('-id')
    award_data = awards.objects.all().filter(
        user=profile_user.id).order_by('-year')
    research_data = research_papers.objects.all().filter(
        user=profile_user.id).order_by('-id')
    featured_data = media_featured.objects.all().filter(
        user=profile_user.id).order_by('-id')
    clinic_hospital_data = clinic_hospital_address.objects.all().filter(
        user=profile_user.id).order_by('-id')
    userprofile = UserProfile.objects.get(user_id=profile_user.id)
    course_certificates = certificate_api.get_certificates_for_user(
        profile_user.username)
    awareness_videos = healthcare_awareness_videos.objects.all().filter(
        user=profile_user.id)

    context = {
        'own_profile':
        own_profile,
        'platform_name':
        configuration_helpers.get_value('platform_name',
                                        settings.PLATFORM_NAME),
        'data': {
            'profile_user_id':
            profile_user.id,
            'default_public_account_fields':
            settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'],
            'default_visibility':
            settings.ACCOUNT_VISIBILITY_CONFIGURATION['default_visibility'],
            'accounts_api_url':
            reverse("accounts_api", kwargs={'username': profile_username}),
            'preferences_api_url':
            reverse('preferences_api', kwargs={'username': profile_username}),
            'preferences_data':
            preferences_data,
            'account_settings_data':
            account_settings_data,
            'profile_image_upload_url':
            reverse('profile_image_upload',
                    kwargs={'username': profile_username}),
            'profile_image_remove_url':
            reverse('profile_image_remove',
                    kwargs={'username': profile_username}),
            'profile_image_max_bytes':
            settings.PROFILE_IMAGE_MAX_BYTES,
            'profile_image_min_bytes':
            settings.PROFILE_IMAGE_MIN_BYTES,
            'account_settings_page_url':
            reverse('account_settings'),
            'has_preferences_access':
            (logged_in_user.username == profile_username or user_is_staff),
            'own_profile':
            own_profile,
            'country_options':
            list(countries),
            'find_courses_url':
            marketing_link('COURSES'),
            'language_options':
            settings.ALL_LANGUAGES,
            'badges_logo':
            staticfiles_storage.url('certificates/images/backpack-logo.png'),
            'badges_icon':
            staticfiles_storage.url(
                'certificates/images/ico-mozillaopenbadges.png'),
            'backpack_ui_img':
            staticfiles_storage.url('certificates/images/backpack-ui.png'),
            'platform_name':
            configuration_helpers.get_value('platform_name',
                                            settings.PLATFORM_NAME),
            'social_platforms':
            settings.SOCIAL_PLATFORMS,
        },
        'show_program_listing':
        ProgramsApiConfig.is_enabled(),
        'show_dashboard_tabs':
        True,
        'disable_courseware_js':
        True,
        'nav_hidden':
        True,
        'records_url':
        get_credentials_records_url(),
        #Added by Mahendra
        'instructor_courses':
        instructor_course_delivered,
        'courses':
        course_data,
        'experience_data':
        experience_data,
        'education_data':
        education_data,
        'award_data':
        award_data,
        'research_data':
        research_data,
        'featured_data':
        featured_data,
        'clinic_hospital_data':
        clinic_hospital_data,
        'userprofile':
        userprofile,
        'userprofile_extrainfo':
        userprofile_extrainfo,
        'course_certificates':
        course_certificates,
        'awareness_videos':
        awareness_videos,
    }

    if own_profile or user_is_staff:
        achievements_fragment = LearnerAchievementsFragmentView(
        ).render_to_fragment(
            request,
            username=profile_user.username,
            own_profile=own_profile,
        )
        context['achievements_fragment'] = achievements_fragment

    if badges_enabled():
        context['data']['badges_api_url'] = reverse(
            "badges_api:user_assertions",
            kwargs={'username': profile_username})

    return context
Esempio n. 9
0
    def to_representation(self, user):
        """
        Overwrite to_native to handle custom logic since we are serializing two models as one here
        :param user: User object
        :return: Dict serialized account
        """
        profile = user.profile
        accomplishments_shared = badges_enabled()

        data = {
            "username":
            user.username,
            "url":
            self.context.get('request').build_absolute_uri(
                reverse('accounts_api', kwargs={'username': user.username})),
            "email":
            user.email,
            # For backwards compatibility: Tables created after the upgrade to Django 1.8 will save microseconds.
            # However, mobile apps are not expecting microsecond in the serialized value. If we set it to zero the
            # DRF JSONEncoder will not include it in the serialized value.
            # https://docs.djangoproject.com/en/1.8/ref/databases/#fractional-seconds-support-for-time-and-datetime-fields
            "date_joined":
            user.date_joined.replace(microsecond=0),
            "is_active":
            user.is_active,
            "bio":
            AccountLegacyProfileSerializer.convert_empty_to_None(profile.bio),
            "country":
            AccountLegacyProfileSerializer.convert_empty_to_None(
                profile.country.code),
            "profile_image":
            AccountLegacyProfileSerializer.get_profile_image(
                profile, user, self.context.get('request')),
            "language_proficiencies":
            LanguageProficiencySerializer(profile.language_proficiencies.all(),
                                          many=True).data,
            "name":
            profile.name,
            "first_name":
            user.first_name,
            "last_name":
            user.last_name,
            "gender":
            AccountLegacyProfileSerializer.convert_empty_to_None(
                profile.gender),
            "goals":
            profile.goals,
            "state":
            profile.state,
            "zipcode":
            profile.zipcode,
            "company":
            profile.company,
            "phone_number":
            profile.phone_number,
            "newsletter":
            profile.newsletter,
            "city":
            profile.city,
            "title":
            profile.title,
            "year_of_birth":
            profile.year_of_birth,
            "level_of_education":
            AccountLegacyProfileSerializer.convert_empty_to_None(
                profile.level_of_education),
            "mailing_address":
            profile.mailing_address,
            "secondary_address":
            profile.secondary_address,
            "ethnicity":
            profile.ethnicity,
            "veteran_status":
            profile.veteran_status,
            "age_category":
            profile.age_category,
            "immigrant_status":
            profile.immigrant_status,
            "education":
            profile.education,
            "facebook_link":
            profile.facebook_link,
            "twitter_link":
            profile.twitter_link,
            "linkedin_link":
            profile.linkedin_link,
            "requires_parental_consent":
            profile.requires_parental_consent(),
            "accomplishments_shared":
            accomplishments_shared,
            "account_privacy":
            get_profile_visibility(profile, user, self.configuration),
            "is_affiliate_staff":
            profile.is_affiliate_staff
        }

        if self.custom_fields:
            fields = self.custom_fields
        else:
            fields = _visible_fields(profile, user, self.configuration)

        visible_serialized_account = self._filter_fields(fields, data)

        if profile.affiliate:
            is_program_director_or_course_manager = AffiliateMembership.objects.filter(
                member=user,
                affiliate=profile.affiliate,
                role__in=['staff', 'instructor']).exists()

            visible_serialized_account[
                'is_program_director_or_course_manager'] = is_program_director_or_course_manager
            visible_serialized_account[
                "affiliate_slug"] = profile.affiliate.slug

        visible_serialized_account["is_staff"] = user.is_staff

        return visible_serialized_account
Esempio n. 10
0
    def to_representation(self, user):
        """
        Overwrite to_native to handle custom logic since we are serializing three models as one here
        :param user: User object
        :return: Dict serialized account
        """
        try:
            user_profile = user.profile
        except ObjectDoesNotExist:
            user_profile = None
            LOGGER.warning(u"user profile for the user [%s] does not exist", user.username)

        try:
            account_recovery = user.account_recovery
        except ObjectDoesNotExist:
            account_recovery = None

        accomplishments_shared = badges_enabled()

        data = {
            "username": user.username,
            "url": self.context.get('request').build_absolute_uri(
                reverse('accounts_api', kwargs={'username': user.username})
            ),
            "email": user.email,
            # For backwards compatibility: Tables created after the upgrade to Django 1.8 will save microseconds.
            # However, mobile apps are not expecting microsecond in the serialized value. If we set it to zero the
            # DRF JSONEncoder will not include it in the serialized value.
            # https://docs.djangoproject.com/en/1.8/ref/databases/#fractional-seconds-support-for-time-and-datetime-fields
            "date_joined": user.date_joined.replace(microsecond=0),
            "is_active": user.is_active,
            "bio": None,
            "country": None,
            "profile_image": None,
            "language_proficiencies": None,
            "name": None,
            "gender": None,
            "goals": None,
            "year_of_birth": None,
            "level_of_education": None,
            "mailing_address": None,
            "requires_parental_consent": None,
            "accomplishments_shared": accomplishments_shared,
            "account_privacy": self.configuration.get('default_visibility'),
            "social_links": None,
            "extended_profile_fields": None,
        }

        if user_profile:
            data.update(
                {
                    "bio": AccountLegacyProfileSerializer.convert_empty_to_None(user_profile.bio),
                    "country": AccountLegacyProfileSerializer.convert_empty_to_None(user_profile.country.code),
                    "profile_image": AccountLegacyProfileSerializer.get_profile_image(
                        user_profile, user, self.context.get('request')
                    ),
                    "language_proficiencies": LanguageProficiencySerializer(
                        user_profile.language_proficiencies.all().order_by('code'), many=True
                    ).data,
                    "name": user_profile.name,
                    "gender": AccountLegacyProfileSerializer.convert_empty_to_None(user_profile.gender),
                    "goals": user_profile.goals,
                    "year_of_birth": user_profile.year_of_birth,
                    "level_of_education": AccountLegacyProfileSerializer.convert_empty_to_None(
                        user_profile.level_of_education
                    ),
                    "mailing_address": user_profile.mailing_address,
                    "requires_parental_consent": user_profile.requires_parental_consent(),
                    "account_privacy": get_profile_visibility(user_profile, user, self.configuration),
                    "social_links": SocialLinkSerializer(
                        user_profile.social_links.all().order_by('platform'), many=True
                    ).data,
                    "extended_profile": get_extended_profile(user_profile),
                }
            )

        if account_recovery:
            if is_secondary_email_feature_enabled_for_user(user):
                data.update(
                    {
                        "secondary_email": account_recovery.secondary_email,
                    }
                )

        if self.custom_fields:
            fields = self.custom_fields
        elif user_profile:
            fields = _visible_fields(user_profile, user, self.configuration)
        else:
            fields = self.configuration.get('public_fields')

        return self._filter_fields(
            fields,
            data
        )
Esempio n. 11
0
    def to_representation(self, user):  # lint-amnesty, pylint: disable=arguments-differ
        """
        Overwrite to_native to handle custom logic since we are serializing three models as one here
        :param user: User object
        :return: Dict serialized account
        """
        try:
            user_profile = user.profile
        except ObjectDoesNotExist:
            user_profile = None
            LOGGER.warning("user profile for the user [%s] does not exist",
                           user.username)

        try:
            account_recovery = user.account_recovery
        except ObjectDoesNotExist:
            account_recovery = None

        try:
            activation_key = user.registration.activation_key
        except ObjectDoesNotExist:
            activation_key = None

        accomplishments_shared = badges_enabled()
        data = {
            "username":
            user.username,
            "url":
            self.context.get('request').build_absolute_uri(
                reverse('accounts_api', kwargs={'username': user.username})),
            "email":
            user.email,
            "id":
            user.id,
            # For backwards compatibility: Tables created after the upgrade to Django 1.8 will save microseconds.
            # However, mobile apps are not expecting microsecond in the serialized value. If we set it to zero the
            # DRF JSONEncoder will not include it in the serialized value.
            # https://docs.djangoproject.com/en/1.8/ref/databases/#fractional-seconds-support-for-time-and-datetime-fields
            "date_joined":
            user.date_joined.replace(microsecond=0),
            "last_login":
            user.last_login,
            "is_active":
            user.is_active,
            "activation_key":
            activation_key,
            "bio":
            None,
            "country":
            None,
            "state":
            None,
            "profile_image":
            None,
            "language_proficiencies":
            None,
            "name":
            None,
            "gender":
            None,
            "goals":
            None,
            "year_of_birth":
            None,
            "level_of_education":
            None,
            "mailing_address":
            None,
            "requires_parental_consent":
            None,
            "accomplishments_shared":
            accomplishments_shared,
            "account_privacy":
            self.configuration.get('default_visibility'),
            "social_links":
            None,
            "extended_profile_fields":
            None,
            "phone_number":
            None,
            "pending_name_change":
            None,
        }

        if user_profile:
            verified_name_obj = get_verified_name(user, is_verified=True)
            verified_name = verified_name_obj.verified_name if verified_name_obj else None
            data.update({
                "bio":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.bio),
                "country":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.country.code),
                "state":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.state),
                "profile_image":
                AccountLegacyProfileSerializer.get_profile_image(
                    user_profile, user, self.context.get('request')),
                "language_proficiencies":
                LanguageProficiencySerializer(
                    user_profile.language_proficiencies.all().order_by('code'),
                    many=True).data,
                "name":
                user_profile.name,
                "verified_name":
                verified_name,
                "gender":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.gender),
                "goals":
                user_profile.goals,
                "year_of_birth":
                user_profile.year_of_birth,
                "level_of_education":
                AccountLegacyProfileSerializer.convert_empty_to_None(
                    user_profile.level_of_education),
                "mailing_address":
                user_profile.mailing_address,
                "requires_parental_consent":
                user_profile.requires_parental_consent(),
                "account_privacy":
                get_profile_visibility(user_profile, user, self.configuration),
                "social_links":
                SocialLinkSerializer(
                    user_profile.social_links.all().order_by('platform'),
                    many=True).data,
                "extended_profile":
                get_extended_profile(user_profile),
                "phone_number":
                user_profile.phone_number,
            })

        try:
            pending_name_change = PendingNameChange.objects.get(user=user)
            data.update({"pending_name_change": pending_name_change.new_name})
        except PendingNameChange.DoesNotExist:
            pass

        if is_secondary_email_feature_enabled():
            data.update({
                "secondary_email":
                account_recovery.secondary_email if account_recovery else None,
                "secondary_email_enabled":
                True,
            })

        if self.custom_fields:
            fields = self.custom_fields
        elif user_profile:
            fields = _visible_fields(user_profile, user, self.configuration)
        else:
            fields = self.configuration.get('public_fields')

        return self._filter_fields(fields, data)