예제 #1
0
 def to_representation(self, data):
     representation = super(LimitOffsetPaginatedListSerializer, self).to_representation(data)
     envelope = BaseSerializerV2.response_envelope(result=representation,
                                                   success=True,
                                                   description='ok')
     envelope['pagination'] = self.paginator.get_page_info()
     return envelope
예제 #2
0
 def to_representation(self, data):
     representation = super(CursorPaginatedListSerializer, self).to_representation(data)
     envelope = BaseSerializerV2.response_envelope(result=representation,
                                                   success=True,
                                                   description='ok')
     envelope['pagination'] = self.paginator.get_page_info()
     return envelope
예제 #3
0
    def post(self, request, **kwargs):
        result = [
            self._process_revoke(request, revocation)
            for revocation in self.request.data
        ]

        response_data = BaseSerializerV2.response_envelope(result=result, success=True, description="revoked badges")

        return Response(status=HTTP_200_OK, data=response_data)
예제 #4
0
    def post(self, request, **kwargs):
        if not isinstance(request.auth, AccessToken):
            # need to use a oauth2 bearer token to authorize
            error_response = BaseSerializerV2.response_envelope(result=[], success=False, description="Invalid token")
            return Response(error_response, status=HTTP_403_FORBIDDEN)

        issuer_entityids = request.data.get('issuers', None)
        if not issuer_entityids:
            raise serializers.ValidationError({"issuers": "field is required"})

        issuers = []
        for issuer_entityid in issuer_entityids:
            try:
                issuer = Issuer.cached.get(entity_id=issuer_entityid)
                self.check_object_permissions(request, issuer)
            except Issuer.DoesNotExist as e:
                raise serializers.ValidationError({"issuers": "unknown issuer"})
            else:
                issuers.append(issuer)

        tokens = []
        expires = timezone.now() + datetime.timedelta(weeks=5200)
        for issuer in issuers:
            scope = "rw:issuer:{}".format(issuer.entity_id)

            # grant application user staff access to issuer if needed
            staff, staff_created = IssuerStaff.cached.get_or_create(
                issuer=issuer,
                user=request.auth.application.user,
                defaults=dict(
                    role=IssuerStaff.ROLE_STAFF
                )
            )

            accesstoken, created = AccessToken.objects.get_or_create(
                user=request.auth.application.user,
                application=request.auth.application,
                scope=scope,
                defaults=dict(
                    expires=expires,
                    token=random_token_generator(request)
                )
            )
            tokens.append({
                'issuer': issuer.entity_id,
                'token': accesstoken.token,
                'expires': accesstoken.expires,
            })

        serializer = IssuerAccessTokenSerializerV2(data=tokens, many=True, context=dict(
            request=request,
            kwargs=kwargs
        ))
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)
예제 #5
0
    def get(self, request, **kwargs):
        if not isinstance(request.auth, AccessToken):
            raise ValidationError("Invalid credentials")
        provider_name = self.request.GET.get('provider', None)
        if provider_name is None:
            raise ValidationError('No provider specified')

        authcode = authcode_for_accesstoken(request.auth)

        redirect_url = "{origin}{url}?provider={provider}&authCode={code}".format(
            origin=OriginSetting.HTTP,
            url=reverse('socialaccount_login'),
            provider=provider_name,
            code=authcode)

        response_data = dict(url=redirect_url)
        if kwargs['version'] == 'v1':
            return Response(response_data)

        return Response(BaseSerializerV2.response_envelope(response_data, True, 'OK'))
예제 #6
0
    def post(self, request, **kwargs):
        entity_id = request.data.get('entity_id')
        badge_instance = self.get_object(entity_id)

        #only do badgecheck verify if not a local badge
        if (badge_instance.source_url):
            recipient_profile = {
                badge_instance.recipient_type: badge_instance.recipient_identifier
            }

            badge_check_options = {
                'include_original_json': True,
                'use_cache': True,
            }

            try:
                response = openbadges.verify(badge_instance.jsonld_id, recipient_profile=recipient_profile, **badge_check_options)
            except ValueError as e:
                raise ValidationError([{'name': "INVALID_BADGE", 'description': str(e)}])

            graph = response.get('graph', [])

            revoked_obo = first_node_match(graph, dict(revoked=True))

            if bool(revoked_obo):
                instance = BadgeInstance.objects.get(source_url=revoked_obo['id'])
                instance.revoke(revoked_obo.get('revocationReason', 'Badge is revoked'))

            else:
                report = response.get('report', {})
                is_valid = report.get('valid')

                if not is_valid:
                    if report.get('errorCount', 0) > 0:
                        errors = [{'name': 'UNABLE_TO_VERIFY', 'description': 'Unable to verify the assertion'}]
                    raise ValidationError(errors)

                validation_subject = report.get('validationSubject')

                badge_instance_obo = first_node_match(graph, dict(id=validation_subject))
                if not badge_instance_obo:
                    raise ValidationError([{'name': 'ASSERTION_NOT_FOUND', 'description': 'Unable to find an badge instance'}])

                badgeclass_obo = first_node_match(graph, dict(id=badge_instance_obo.get('badge', None)))
                if not badgeclass_obo:
                    raise ValidationError([{'name': 'ASSERTION_NOT_FOUND', 'description': 'Unable to find a badgeclass'}])

                issuer_obo = first_node_match(graph, dict(id=badgeclass_obo.get('issuer', None)))
                if not issuer_obo:
                    raise ValidationError([{'name': 'ASSERTION_NOT_FOUND', 'description': 'Unable to find an issuer'}])

                original_json = response.get('input').get('original_json', {})

                BadgeInstance.objects.update_from_ob2(
                    badge_instance.badgeclass,
                    badge_instance_obo,
                    badge_instance.recipient_identifier,
                    badge_instance.recipient_type,
                    original_json.get(badge_instance_obo.get('id', ''), None)
                )

                badge_instance.rebake(save=True)

                BadgeClass.objects.update_from_ob2(
                    badge_instance.issuer,
                    badgeclass_obo,
                    original_json.get(badgeclass_obo.get('id', ''), None)
                )

                Issuer.objects.update_from_ob2(
                    issuer_obo,
                    original_json.get(issuer_obo.get('id', ''), None)
                )
        result = self.get_object(entity_id).get_json(expand_badgeclass=True, expand_issuer=True)

        return Response(BaseSerializerV2.response_envelope([result], True, 'OK'), status=status.HTTP_200_OK)