def delete(self, request, id, **kwargs): email_address = self.get_email(pk=id) if email_address is None: return Response(status=status.HTTP_404_NOT_FOUND) if email_address.user_id != request.user.id: return Response(status=status.HTTP_403_FORBIDDEN) if email_address.primary: raise BadgrApiException400("Can not remove primary email address", 103) if self.request.user.emailaddress_set.count() == 1: raise BadgrApiException400("Can not remove only email address", 104) email_address.delete() return Response(status.HTTP_200_OK)
def delete(self, request, **kwargs): # verify the user has permission to the assertion try: assertion = self.get_object(request, **kwargs) except Http404 as e: raise BadgrApiException400('You do not have permission. Check your assigned role in the Issuer', 601) if not self.has_object_permissions(request, assertion): raise BadgrApiException400('You do not have permission. Check your assigned role in the Issuer', 601) revocation_reason = request.data.get('revocation_reason', None) if not revocation_reason: raise ValidationError({'revocation_reason': "This field is required"}) assertion.revoke(revocation_reason) # logger.event(badgrlog.BadgeAssertionRevokedEvent(current_assertion, request.user)) return Response(status=HTTP_200_OK)
def post(self, request, **kwargs): serializer = EmailSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) try: # check if email already exists CachedEmailAddress.objects.get(email=request.data.get('email'), verified=1) raise BadgrApiException400("Could not register email address. Address already in use", 101) except CachedEmailAddress.DoesNotExist: try: CachedEmailAddress.objects.get(email=request.data.get('email'), verified=0, user_id=request.user.pk) raise BadgrApiException400("You have already added this address. Verify it", 102) except CachedEmailAddress.DoesNotExist: pass email_address = serializer.save(user=request.user) email = serializer.data email_address.send_confirmation(request) return Response(email, status=status.HTTP_201_CREATED)
def post(self, request, **kwargs): context = self.get_context_data(**kwargs) response = [] if not request.data: raise BadgrApiException400('No provisionments sent', 0) for provisionment in request.data: serializer = self.v1_serializer_class(data=provisionment, context=context) try: serializer.is_valid(raise_exception=True) serializer.save(created_by=request.user) message = {'status': 'success', 'message': serializer.data} except ValidationError as e: if not isinstance( e, BadgrValidationError) and 'email' in e.detail: # Consistency with other BadgrValidationErrors e = BadgrValidationError("Enter a valid email address", 509) # check if email address was a duplicate duplicate_with_success = [ x for x in response if x['status'] == 'success' and x['email'] == provisionment['email'] ] if duplicate_with_success: e = BadgrValidationError( 'You entered this email address multiple times.', 510) message = {'status': 'failure', 'message': e.detail} message['email'] = provisionment['email'] response.append(message) return Response(response, status=status.HTTP_201_CREATED)
def delete(self, request, **kwargs): obj = self.get_object(request, **kwargs) try: obj.delete() except ProtectedError as e: raise BadgrApiException400(error_message=e.args[0], error_code=999) return Response(status=HTTP_204_NO_CONTENT)
def post(self, request, **kwargs): """ Revoke direct awards """ revocation_reason = request.data.get('revocation_reason', None) direct_awards = request.data.get('direct_awards', None) if not revocation_reason: raise BadgrValidationFieldError('revocation_reason', "This field is required", 999) if not direct_awards: raise BadgrValidationFieldError('direct_awards', "This field is required", 999) cache_cleared = False for direct_award in direct_awards: direct_award = DirectAward.objects.get( entity_id=direct_award['entity_id']) if direct_award.get_permissions(request.user)['may_award']: direct_award.revoke(revocation_reason) if not cache_cleared: direct_award.badgeclass.remove_cached_data( ['cached_direct_awards']) cache_cleared = True else: raise BadgrApiException400("You do not have permission", 100) return Response({"result": "ok"}, status=status.HTTP_200_OK)
def delete(self, request, **kwargs): if request.data: term_agreement = TermsAgreement.objects.get(entity_id=request.data['terms_agreement_entity_id']) term_agreement.agreed = False term_agreement.save() request.user.remove_cached_data(['cached_terms_agreements']) return Response(status=HTTP_200_OK) raise BadgrApiException400('Cannot revoke consent, no data sent', 999)
def post(self, request, **kwargs): if request.data: serializer = TermsAgreementSerializer(data=request.data, many=True, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) raise BadgrApiException400('Cannot accept terms, no data sent')
def put(self, request, **kwargs): enrollment = self.get_object(request, **kwargs) if not self.has_object_permissions(request, enrollment): raise BadgrApiException400("You do not have permission", 210) if enrollment.denied: raise BadgrApiException400("Enrollment already denied", 211) if enrollment.badge_instance: raise BadgrApiException400("Awarded enrollments cannot be denied", 212) enrollment.denied = True enrollment.save() html_message = EmailMessageMaker.create_enrollment_denied_email( enrollment) subject = 'Your request for the badgeclass {} has been denied by the issuer.'.format( enrollment.badge_class.name) enrollment.user.email_user(subject=subject, html_message=html_message) return Response(data='Succesfully denied enrollment', status=HTTP_200_OK)
def delete(self, request, **kwargs): try: enrollment = StudentsEnrolled.objects.get( entity_id=request.data['enrollmentID']) except ValueError: raise BadgrApiException400("Invalid enrollment id", 204) except StudentsEnrolled.DoesNotExist: raise BadgrApiException400("Enrollment not found", 205) else: if enrollment.date_awarded: raise BadgrApiException400( "Awarded enrollments cannot be withdrawn", 206) if request.user == enrollment.user: enrollment.delete() return Response(data='Enrollment withdrawn', status=200) else: raise BadgrApiException400( "Users can only withdraw their own enrollments", 207)
def get(self, request, *args, **kwargs): identity = kwargs.get('identity', None) salt = kwargs.get('salt', None) if not identity or not salt: raise BadgrApiException400( 'Cannot query name: salt and identity needed', 0) instance = BadgeInstance.objects.get(salt=salt) if instance.public: if identity == instance.get_hashed_identity(): return Response({'name': instance.get_recipient_name()}) return Response(status=status.HTTP_404_NOT_FOUND)
def may_enroll(self, badge_class, raise_exception=False): """ Checks to see if user may enroll no enrollments: May enroll any not awarded assertions: May not enroll Any awarded and not revoked: May not enroll All revoked: May enroll """ social_account = self.get_social_account() if not social_account.user.validated_name: if raise_exception: raise BadgrApiException400('May not enroll: no validated name', 209) return False if social_account.provider == 'edu_id': enrollments = StudentsEnrolled.objects.filter( user=social_account.user, badge_class_id=badge_class.pk) if not enrollments: return True # no enrollments else: for enrollment in enrollments: if not bool(enrollment.badge_instance ): # has never been awarded if raise_exception: raise BadgrApiException400( 'May not enroll: already enrolled', 201) return False else: # has been awarded if not enrollment.assertion_is_revoked(): if raise_exception: raise BadgrApiException400( 'May not enroll: you already have been awarded this badge', 202) return False return True # all have been awarded and revoked else: # no eduID if raise_exception: raise BadgrApiException400( "May not enroll: you don't have a student account", 203) return False
def get(self, request, **kwargs): """ Share a single badge to a support share provider --- parameters: - name: provider description: The identifier of the provider to use. Supports 'facebook', 'linkedin' required: true type: string paramType: query """ # from recipient.api import _scrub_boolean redirect = request.query_params.get('redirect', "1") provider = request.query_params.get('provider') if not provider: raise BadgrApiException400("Unspecified share provider", 701) provider = provider.lower() source = request.query_params.get('source', 'unknown') badge = self.get_object(request, **kwargs) if not badge: return Response(status=HTTP_404_NOT_FOUND) share = BackpackBadgeShare(provider=provider, badgeinstance=badge, source=source) share_url = share.get_share_url(provider) if not share_url: raise BadgrApiException400("Invalid share provider", 702) share.save() if redirect: headers = {'Location': share_url} return Response(status=HTTP_302_FOUND, headers=headers) else: return Response({'url': share_url})
def put(self, request, id, **kwargs): email_address = self.get_email(pk=id) if email_address is None: return Response(status=status.HTTP_404_NOT_FOUND) if email_address.user_id != request.user.id: return Response(status=status.HTTP_403_FORBIDDEN) if email_address.verified: if request.data.get('primary'): email_address.set_as_primary() email_address.publish() elif request.data.get('resend'): send_confirmation = False current_time = datetime.datetime.now() last_request_time = email_address.get_last_verification_sent_time() if last_request_time is None: email_address.set_last_verification_sent_time( datetime.datetime.now()) send_confirmation = True else: time_delta = current_time - last_request_time if time_delta > RATE_LIMIT_DELTA: send_confirmation = True if send_confirmation: email_address.send_confirmation(request=request) email_address.set_last_verification_sent_time( datetime.datetime.now()) else: remaining_time_obj = RATE_LIMIT_DELTA - ( datetime.datetime.now() - last_request_time) remaining_min = (remaining_time_obj.seconds // 60) % 60 remaining_sec = remaining_time_obj.seconds % 60 remaining_time_rep = "{} minutes and {} seconds".format( remaining_min, remaining_sec) return Response( "Will be able to re-send verification email in %s." % (str(remaining_time_rep)), status=status.HTTP_429_TOO_MANY_REQUESTS) else: raise BadgrApiException400( "Can't make unverified email address the primary email address", 105) serializer = EmailSerializer(email_address, context={'request': request}) serialized = serializer.data return Response(serialized, status=status.HTTP_200_OK)
def post(self, request, **kwargs): if 'badgeclass_slug' not in request.data: raise BadgrApiException400("Missing badgeclass id", 208) badge_class = get_object_or_404( BadgeClass, entity_id=request.data['badgeclass_slug']) if not badge_class.terms_accepted(request.user): raise BadgrValidationError( "Cannot enroll, must accept terms first", 0) if request.user.may_enroll(badge_class, raise_exception=True): enrollment = StudentsEnrolled.objects.create( badge_class_id=badge_class.pk, user=request.user, date_consent_given=timezone.now()) message = EmailMessageMaker.create_student_badge_request_email( request.user, badge_class) request.user.email_user( subject='You have successfully requested an edubadge', html_message=message) return Response(data={ 'status': 'enrolled', 'entity_id': enrollment.entity_id }, status=201) raise BadgrApiException400('Cannot enroll', 209)
def post(self, request, **kwargs): revocation_reason = request.data.get('revocation_reason', None) if not revocation_reason: raise BadgrValidationFieldError('revocation_reason', "This field is required", 999) assertions = request.data.get('assertions', None) if not assertions: raise BadgrValidationFieldError('assertions', "This field is required", 999) for assertion in assertions: badgeinstance = BadgeInstance.objects.get( entity_id=assertion['entity_id']) if badgeinstance.get_permissions(request.user)['may_award']: badgeinstance.revoke(revocation_reason) else: raise BadgrApiException400("You do not have permission", 100) return Response({"result": "ok"}, status=status.HTTP_200_OK)
def get_object(self, request, **kwargs): if request.user.is_authenticated: self.object = request.user self.has_object_permissions(request, self.object) return self.object raise BadgrApiException400("You do not have permission", 100)