def test_delete_sound_view(self): user, packs, sounds = create_user_and_sounds(num_sounds=1, num_packs=1) sound = sounds[0] sound_id = sound.id sound.change_processing_state("OK") sound.change_moderation_state("OK") self.client.login(username=user.username, password='******') # Try delete with incorrect encrypted sound id link (should not delete sound) encrypted_link = encrypt(u"%d\t%f" % (1234, time.time())) resp = self.client.get('%s?sound=%s' % (reverse('sound-delete', args=[sound.user.username, sound.id]), encrypted_link)) self.assertEqual(resp.status_code, 200) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 1) # Try delete with expried encrypted link (should not delete sound) encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time() - 15)) resp = self.client.get('%s?sound=%s' % (reverse('sound-delete', args=[sound.user.username, sound.id]), encrypted_link)) self.assertEqual(resp.status_code, 200) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 1) # Try delete with valid link (should delete sound) encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) resp = self.client.get('%s?sound=%s' % (reverse('sound-delete', args=[sound.user.username, sound.id]), encrypted_link)) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 0) self.assertRedirects(resp, reverse('accounts-home'))
def test_delete_sound_view(self, delete_sound_solr): user, packs, sounds = create_user_and_sounds(num_sounds=1, num_packs=1) sound = sounds[0] sound_id = sound.id sound.change_processing_state("OK") sound.change_moderation_state("OK") self.client.login(username=user.username, password='******') # Try delete with incorrect encrypted sound id link (should not delete sound) encrypted_link = encrypt(u"%d\t%f" % (1234, time.time())) resp = self.client.post(reverse('sound-delete', args=[sound.user.username, sound.id]), {"encrypted_link": encrypted_link}) self.assertEqual(resp.status_code, 403) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 1) # Try delete with expired encrypted link (should not delete sound) encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time() - 15)) resp = self.client.post(reverse('sound-delete', args=[sound.user.username, sound.id]), {"encrypted_link": encrypted_link}) self.assertEqual(resp.status_code, 200) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 1) # Try delete with valid link (should delete sound) encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) resp = self.client.post(reverse('sound-delete', args=[sound.user.username, sound.id]), {"encrypted_link": encrypted_link}) self.assertEqual(Sound.objects.filter(id=sound_id).count(), 0) self.assertRedirects(resp, reverse('accounts-home')) delete_sound_solr.assert_called_once_with(sound.id)
def post(self): '''Insert an aws account''' data = request.json fancy_name = validate_param(data.get("fancy_name", None), [(TYPE_VALIDATOR, unicode)], required=True) access_key = encrypt( validate_param(data.get("access_key", None), [(TYPE_VALIDATOR, unicode)], required=True)) secret_key = encrypt( validate_param(data.get("secret_key", None), [(TYPE_VALIDATOR, unicode)], required=True)) idUser = validate_param(data.get("user", {}).get("id", None), [(TYPE_VALIDATOR, int)], required=True) validate_access(request.headers.get("Authorization"), [ADMIN_USER, MYSELF_USER], id_myself=idUser) account = AwsAccount(fancy_name=fancy_name, access_key=access_key, secret_key=secret_key, idUser=idUser) db.session.add(account) try: db.session.commit() except: db.session.rollback() raise return jsonify(self.awsAccountSchema.dump(account).data), 201
def test_basic_encryption(self): e = Factory.rand_str(include_emoji=False) self.assertEquals(e, decrypt(encrypt(e))) e = "😀💌❤️" self.assertEquals(e, decrypt(encrypt(e))) e = Factory.rand_text() self.assertEquals(e, decrypt(encrypt(e))) e = Factory.rand_email() self.assertEquals(e, decrypt(encrypt(e)))
def test_extended_types_encryption(self): e = Factory.rand_phone() self.assertEquals(e, decrypt(encrypt(e))) e = Factory.rand_name() self.assertEquals(e, decrypt(encrypt(e))) e = Factory.temp_password() self.assertEquals(e, decrypt(encrypt(e))) e = Factory.rand_url() self.assertEquals(e, decrypt(encrypt(e)))
def delete(request): encrypted_string = request.GET.get("user", None) waited_too_long = False num_sounds = request.user.sounds.all().count() if encrypted_string is not None: user_id, now = decrypt(encrypted_string).split("\t") user_id = int(user_id) if user_id != request.user.id: raise PermissionDenied link_generated_time = float(now) if abs(time.time() - link_generated_time) < 10: if num_sounds == 0: request.user.profile.change_ownership_of_user_content() request.user.delete() return HttpResponseRedirect(reverse("front-page")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (request.user.id, time.time())) tvars = { 'waited_too_long': waited_too_long, 'encrypted_link': encrypted_link, 'num_sounds': num_sounds, } return render(request, 'accounts/delete.html', tvars)
def pack_delete(request, username, pack_id): pack = get_object_or_404(Pack, id=pack_id) if pack.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm("pack.can_change") or pack.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("pack", None) waited_too_long = False if encrypted_string is not None: pack_id, now = decrypt(encrypted_string).split("\t") pack_id = int(pack_id) link_generated_time = float(now) if pack_id != pack.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete pack %s" % (request.user.username, pack_id)) pack.delete() return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (pack.id, time.time())) tvars = {"pack": pack, "encrypted_link": encrypted_link, "waited_too_long": waited_too_long} return render(request, "sounds/pack_delete.html", tvars)
def __init__(self, *args, **kwargs): self.sound_id = int(kwargs.pop('sound_id')) encrypted_link = encrypt(u"%d\t%f" % (self.sound_id, time.time())) kwargs['initial'] = { 'encrypted_link': encrypted_link } super(DeleteSoundForm, self).__init__(*args, **kwargs)
def delete(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm('sound.delete_sound') or sound.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("sound", None) waited_too_long = False if encrypted_string != None: sound_id, now = decrypt(encrypted_string).split("\t") sound_id = int(sound_id) link_generated_time = float(now) if sound_id != sound.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete sound %s" % (request.user.username, sound_id)) sound.delete() return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) return render_to_response('sounds/delete.html', locals(), context_instance=RequestContext(request))
def pack_delete(request, username, pack_id): pack = get_object_or_404(Pack, id=pack_id) if pack.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm('pack.can_change') or pack.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("pack", None) waited_too_long = False if encrypted_string != None: pack_id, now = decrypt(encrypted_string).split("\t") pack_id = int(pack_id) link_generated_time = float(now) if pack_id != pack.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete pack %s" % (request.user.username,pack_id)) print pack pack.delete() print "DELETED!" return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (pack.id, time.time())) return render_to_response('sounds/pack_delete.html', locals(), context_instance=RequestContext(request))
def delete(request, username, sound_id): sound = get_object_or_404(Sound, user__username__iexact=username, id=sound_id, moderation_state="OK", processing_state="OK") if not (request.user.has_perm('sound.delete_sound') or sound.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("sound", None) waited_too_long = False if encrypted_string != None: sound_id, now = decrypt(encrypted_string).split("\t") sound_id = int(sound_id) link_generated_time = float(now) if sound_id != sound.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete sound %s" % (request.user.username,sound_id)) sound.delete() return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) return render_to_response('sounds/delete.html', locals(), context_instance=RequestContext(request))
def pack_delete(request, username, pack_id): pack = get_object_or_404(Pack, id=pack_id) if pack.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm('pack.can_change') or pack.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("pack", None) waited_too_long = False if encrypted_string is not None: pack_id, now = decrypt(encrypted_string).split("\t") pack_id = int(pack_id) link_generated_time = float(now) if pack_id != pack.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete pack %s" % (request.user.username, pack_id)) pack.delete_pack(remove_sounds=False) return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (pack.id, time.time())) tvars = { 'pack': pack, 'encrypted_link': encrypted_link, 'waited_too_long': waited_too_long } return render(request, 'sounds/pack_delete.html', tvars)
def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id') encrypted_link = encrypt(u"%d\t%f" % (self.user_id, time.time())) kwargs['initial'] = { 'delete_sounds': 'only_user', 'encrypted_link': encrypted_link } super(DeleteUserForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs): user = threadlocal.get_current_user() key = get_user_encryption_key(user.username) or kwargs.get('key') # if no key throw error if not key: raise StandardError("If calling save from outside of a request, " \ "you must specify 'key' as a kwarg") self.password = encrypt(self.password, key) super(Credential, self).save(*args, **kwargs)
def send_encrypted_message(self, connection, message, binary): fd = connection.fileno() if not binary: bmessage = message.get_binary_json('utf-8') else: bmessage = message if fd in self.session_key_dict: enctypted_message = encryption.encrypt(bmessage, self.session_key_dict[fd]) self.sender.queue.put((connection, enctypted_message))
def put(self, request): """ 비밀번호 변경 메일 발송 :param request: data = { 'password1': 비밀번호 'password2': 확인용 비밀번호 } :return: Response(1) """ try: password1 = request.data['password1'] password2 = request.data['password2'] except RequestDataDoesNotExist: raise RequestDataDoesNotExist( 'password1 또는 password2 값이 전달되지 않았습니다') if password1 == password2: # password 암호화 encrypted_password = encrypt( key=ENCRYPTION_KEY, plain_text=request.data['password1'], ) # 유저의 activation key 새로 설정 request.user.activationkeyinfo.refresh() # activation key info 암호화 encrypted_activation_key = encrypt( key=ENCRYPTION_KEY, plain_text=request.user.activationkeyinfo.key, ) data = { 'activation_key': encrypted_activation_key, 'password': encrypted_password, # password 암호화 } # password 변경 메일 발송 send_password_reset_mail.delay(data, [request.user.email]) return Response(1, status=status.HTTP_200_OK) else: raise RequestDataInvalid('password1 과 password2 가 일치하지 않습니다')
def delete(request): import time encrypted_string = request.GET.get("user", None) waited_too_long = False num_sounds = request.user.sounds.all().count() if encrypted_string != None: try: user_id, now = decrypt(encrypted_string).split("\t") user_id = int(user_id) if user_id != request.user.id: raise PermissionDenied link_generated_time = float(now) if abs(time.time() - link_generated_time) < 10: from forum.models import Post, Thread from comments.models import Comment from sounds.models import DeletedSound deleted_user = User.objects.get(id=settings.DELETED_USER_ID) for post in Post.objects.filter(author=request.user): post.author = deleted_user post.save() for thread in Thread.objects.filter(author=request.user): thread.author = deleted_user thread.save() for comment in Comment.objects.filter(user=request.user): comment.user = deleted_user comment.save() for sound in DeletedSound.objects.filter(user=request.user): sound.user = deleted_user sound.save() request.user.delete() return HttpResponseRedirect(reverse("front-page")) else: waited_too_long = True except: pass encrypted_link = encrypt(u"%d\t%f" % (request.user.id, time.time())) return render_to_response('accounts/delete.html', locals(), context_instance=RequestContext(request))
def delete(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm('sound.delete_sound') or sound.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("sound", None) waited_too_long = False if encrypted_string is not None: sound_id, now = decrypt(encrypted_string).split("\t") sound_id = int(sound_id) link_generated_time = float(now) if sound_id != sound.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete sound %s" % (request.user.username, sound_id)) try: ticket = sound.ticket tc = TicketComment(sender=request.user, text="User %s deleted the sound" % request.user, ticket=ticket, moderator_only=False) tc.save() except Ticket.DoesNotExist: # No ticket assigned, not adding any message (should not happen) pass sound.delete() return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) return render_to_response('sounds/delete.html', locals(), context_instance=RequestContext(request))
def delete(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 if not (request.user.has_perm('sound.delete_sound') or sound.user == request.user): raise PermissionDenied encrypted_string = request.GET.get("sound", None) waited_too_long = False if encrypted_string is not None: sound_id, now = decrypt(encrypted_string).split("\t") sound_id = int(sound_id) link_generated_time = float(now) if sound_id != sound.id: raise PermissionDenied if abs(time.time() - link_generated_time) < 10: logger.debug("User %s requested to delete sound %s" % (request.user.username,sound_id)) try: ticket = sound.ticket tc = TicketComment(sender=request.user, text="User %s deleted the sound" % request.user, ticket=ticket, moderator_only=False) tc.save() except Ticket.DoesNotExist: # No ticket assigned, not adding any message (should not happen) pass sound.delete() return HttpResponseRedirect(reverse("accounts-home")) else: waited_too_long = True encrypted_link = encrypt(u"%d\t%f" % (sound.id, time.time())) return render_to_response('sounds/delete.html', locals(), context_instance=RequestContext(request))
def one_click_sign_in_link(self, url): from utils.factory import Factory return quote_plus( encrypt("%s|%s|%s" % (Factory.rand_str( include_emoji=False, length=5), self.hashid, url)))
def post(self, request): """ 1. 전달된 email 의 유저가 존재하는 경우 1) 소셜로그인 계정일 때 - 추가 회원가입 링크를 담은 인증 메일 발송 2) Soundhub 계정일 때 a. is_active 가 True - RequestDataInvalid: '이미 존재하는 유저입니다' b. is_active 가 False - 안내 메일 발송 - RequestDataInvalid: '이메일 인증 중인 유저입니다. 메일을 확인해주세요.' 2. 전달된 email 의 유저가 존재하지 않는 경우 - User, ActivationKeyInfo 생성 - 인증메일 발송 :param request: data = { 'email': '*****@*****.**', 'nickname': 'user_nickname', 'password1': 'password', 'password2': 'password', 'instrument': 'instrument_name' } :return: 유저 생성 성공: User serializer 데이터 (HTTP status 201) 유저 생성 실패: User serializer 의 error 정보 (HTTP status 400) """ # 유저 타입 상수 soundhub = User.USER_TYPE_SOUNDHUB email = request.data['email'] # 전달된 이메일의 유저가 존재하는 경우 if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) # 소셜로그인 계정인 경우 if not user.user_type == soundhub: # password 암호화 encrypted_password = encrypt( key=ENCRYPTION_KEY, plain_text=request.data['password'], ) # 유저의 activation key 새로 설정 user.activationkeyinfo.refresh() # activation key info 암호화 encrypted_activation_key = encrypt( key=ENCRYPTION_KEY, plain_text=user.activationkeyinfo.key, ) data = { 'activation_key': encrypted_activation_key, 'nickname': request.data['nickname'], 'password': encrypted_password, # password 암호화 'instrument': request.data['instrument'], } # 유저 정보를 담은 데이터와 함께 메일 발송 send_verification_mail_after_social_login.delay( data, [user.email]) # Soundhub 계정일 때 elif user.is_active is True: raise RequestDataInvalid('이미 존재하는 유저입니다') elif user.is_active is False: # Activation key 만료 기한 재설정 user.activationkeyinfo.refresh_expires_at() send_confirm_readmission_mail.delay([user.email]) raise RequestDataInvalid('이메일 인증 중인 유저입니다. 메일을 확인해주세요.') serializer = SignupSerializer(data=request.data) if serializer.is_valid(): # user 생성, 반환 user = serializer.save() # activation key 생성 activation_key_info = ActivationKeyInfo.objects.create(user=user) # 인증 메일 발송 send_verification_mail.delay( activation_key=activation_key_info.key, recipient_list=[user.email], ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def send_activation(user): encrypted_user_id = encrypt(str(user.id)) username = user.username send_mail_template(u'activation link.', 'accounts/email_activation.txt', locals(), None, user.email)
def reset_encrypted_link(self, user_id): self.data = self.data.copy() self.data["encrypted_link"] = encrypt(u"%d\t%f" % (user_id, time.time()))
def send(self): tombstone = False subject = False body = False # print("om.send") # print("not self.attempt_started: %s" % (not self.attempt_started)) # print("self.message.transactional is True: %s" % (self.message.transactional is True)) # print("self.subscription: %s" % (self.subscription)) # print("self.subscription.person is self.person.pk: %s" % ( # self.subscription and self.subscription.person.pk == self.person.pk) # ) # print("self.subscription.double_opted_in: %s" % (self.subscription and self.subscription.double_opted_in)) # print("not self.subscription.unsubscribed: %s" % (self.subscription and not self.subscription.unsubscribed)) # print("not self.person.banned: %s" % (not self.person.banned)) # print("not self.person.hard_bounced: %s" % (not self.person.hard_bounced)) if ( # Don't dogpile. not self.attempt_started # We're allowed to send this. and ( # Transactional always sends self.message.transactional is True # Or, you're subscribed. or (self.subscription and self.subscription.person.pk == self.person.pk and self.subscription.double_opted_in and not self.subscription.unsubscribed)) # Never send to someone who's banned or hard bounced. and not self.person.banned and not self.person.hard_bounced): try: # print("trying") # Save about to send metadata self.attempt_started = True self.attempt_complete = False self.retry_if_not_complete_by = timezone.now() + RETRY_IN_TIME self.save() subject, body, html_body = self.render_subject_and_body() # print("subject: %s" % subject) # print("body: %s" % body) # print(self.message.transactional_send_reason) # print(self.message.transactional_no_unsubscribe_reason) # print(self.delete_account_link) # Final checks to make sure unsubscribe and CAN_SPAM compliance if self.message.transactional: if (not self.message.purchase and (self.message.transactional_send_reason not in body or self.message.transactional_no_unsubscribe_reason not in body or self.delete_account_link not in body)): self.should_retry = False self.send_success = False self.attempt_complete = True self.attempt_completed_at = timezone.now() self.attempt_count = self.attempt_count + 1 self.valid_message = False self.save() if self.message.transactional_send_reason not in body: # print("Transactional message was attempted without transactional_send_reason. Refusing to send.") # noqa logging.warn( "Transactional message was attempted without transactional_send_reason. Refusing to send." ) # noqa if self.message.transactional_no_unsubscribe_reason not in body: # print("Transactional message was attempted without transactional_no_unsubscribe_reason. Refusing to send.") # noqa logging.warn( "Transactional message was attempted without transactional_no_unsubscribe_reason. Refusing to send." ) # noqa if self.delete_account_link not in body: # print("Transactional message was attempted without delete_account_link. Refusing to send.") logging.warn( "Transactional message was attempted without delete_account_link. Refusing to send." ) return False else: if self.unsubscribe_link not in body: self.should_retry = False self.send_success = False self.attempt_complete = True self.attempt_completed_at = timezone.now() self.attempt_count = self.attempt_count + 1 self.valid_message = False self.save() # print("Message was attempted without including the unsubscribe_link. Refusing to send.") logging.warn( "Message was attempted without including the unsubscribe_link. Refusing to send." ) return False # print("final checks passsed") tombstone, _ = OutgoingMessageAttemptTombstone.objects.get_or_create( send_time=timezone.now(), outgoing_message_pk=self.pk, encrypted_email=self.person.encrypted_email, ) # Send the message. from_email = settings.DEFAULT_FROM_EMAIL if (self.subscription and self.subscription.newsletter and self.subscription.newsletter.full_from_email): from_email = self.subscription.newsletter.full_from_email # print("django_send_mail") logging.warn("django_send_mail") django_send_mail(subject, body, from_email, [ self.person.email, ], html_message=html_body, fail_silently=False) self.attempt_complete = True self.attempt_count = self.attempt_count + 1 self.send_success = True self.hard_bounced = False self.save() # print("success") except Exception as e: print("exception throw") import traceback traceback.print_exc() logging.warn(e) # print(e) self.attempt_complete = True self.attempt_completed_at = timezone.now() self.attempt_count = self.attempt_count + 1 self.send_success = False self.save() self.hard_bounced = False self.send_success = False if not tombstone: tombstone, _ = OutgoingMessageAttemptTombstone.objects.get_or_create( send_time=timezone.now(), outgoing_message_pk=self.pk, encrypted_email=self.person.encrypted_email, ) tombstone.send_success = False tombstone.send_error = str(e) tombstone.reason = str(e) tombstone.attempt_made = True tombstone.retry_number = self.attempt_count self.save() # Log attempt if subject is not False: tombstone.encrypted_message_subject = encrypt(subject) if body is not False: tombstone.encrypted_message_body = encrypt(body) tombstone.save() else: if (not self.subscription or self.subscription.person.pk != self.person.pk or not self.subscription.double_opted_in or self.subscription.unsubscribed or self.person.banned or self.person.hard_bounced): self.attempt_started = True self.attempt_complete = True self.attempt_completed_at = timezone.now() self.send_success = False self.attempt_skipped = True self.save() # print("logging as skipped.") logging.warn("Skipping message.")
def last_name(self, value): self.encrypted_last_name = encrypt(value) self.hashed_last_name = lookup_hash(value)
def email(self, value): self.encrypted_email = encrypt(value) self.hashed_email = lookup_hash(value)
def send(self, message): bmessage = message.get_binary_json('utf-8') encrypted_message = encryption.encrypt(bmessage, self.session_key) self.sender_thread.send_queue.put(encrypted_message)
def data(self, value): self.encrypted_data = encrypt(value)
def send_auth_data(self, auth_message): auth_bmessage = auth_message.get_binary_json('utf-8') auth_message_encrypted = encryption.encrypt(auth_bmessage, self.session_key) self.sender_thread.send_queue.put(self.session_key_encrypted + auth_message_encrypted)