Exemplo n.º 1
0
    def get(self, request):
        """
        password 변경 링크를 통해서만 접근 가능
        activation key 로 유효한 접근인지 확인 후
        get parameter 로 전달된 정보로 password 재설정

        :param request: 암호화된 activation key 와 password 정보
        :return: Response(1)
        """
        try:
            # get parameter 에서 값 추출
            # 암호화된 activation key 와 password 복호화
            activation_key = decrypt(
                key=ENCRYPTION_KEY,
                encrypted_text=request.GET['activation_key'],
            )
            password = decrypt(
                key=ENCRYPTION_KEY,
                encrypted_text=request.GET['password'],
            )
        except RequestDataDoesNotExist:
            raise RequestDataDoesNotExist('잘못된 요청입니다')

        # activation key 에 해당하는 유저가 존재하는지 검사
        activation_key_info = get_object_or_404(ActivationKeyInfo,
                                                key=activation_key)
        # activation key 가 만료된 경우
        if not activation_key_info.expires_at > timezone.now():
            raise RequestDataInvalid('activation_key 의 기한이 만료되었습니다.')

        # password 변경
        activation_key_info.user.set_password(password)
        activation_key_info.user.save()

        return Response(1, status=status.HTTP_200_OK)
Exemplo n.º 2
0
    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)))
Exemplo n.º 3
0
    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)))
Exemplo n.º 4
0
    def get(self, request):
        """
        1. 소셜로그인으로 생성된 유저가, Soundhub Signup 을 시도하는 경우 Signup.post() 함수에서 인증메일을 보내준다
        2. 인증 메일에는 Signup view 에 get 요청을 보내는 링크를 포함한다
        3. get parameter 로 전달된 정보를 사용해서
        4. 어떤 방식으로도 로그인할 수 있도록 Soundhub password 추가

        :param request:
            GET = {
                'activation_key': Encrypted Activation Key,
                'nickname': 사용자 입력 닉네임,
                'password': Encrypted Password,
                'instrument': 사용자 입력 악기정보,
            }
        :return: None
        """
        # get parameter 에서 값 추출
        # 암호화된 activation key 와 password 복호화
        activation_key = decrypt(
            key=ENCRYPTION_KEY,
            encrypted_text=request.GET['activation_key'],
        )
        password = decrypt(
            key=ENCRYPTION_KEY,
            encrypted_text=request.GET['password'],
        )
        nickname = request.GET['nickname']
        instrument = request.GET['instrument']

        # activation key 에 해당하는 유저가 존재하는지 검사
        activation_key_info = get_object_or_404(ActivationKeyInfo,
                                                key=activation_key)
        # activation key 가 만료된 경우
        if not activation_key_info.expires_at > timezone.now():
            raise RequestDataInvalid('activation_key 의 기한이 만료되었습니다.')

        # 해당 유저 정보를 변경하고 저장
        user = activation_key_info.user
        user.nickname = nickname
        user.set_password(password)
        user.instrument = instrument
        user.save()

        data = {
            'token': user.token,
            'user': UserSerializer(user).data,
        }
        return Response(data, status=status.HTTP_200_OK)
Exemplo n.º 5
0
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))
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
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))
Exemplo n.º 8
0
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))
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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))
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
def decrypt(context, data=None):
    request = context['request']
    key = request.session.get('key')
    try:
        dec = decrypt(data, key)
    except:
        dec = _('access denied')
    return dec
Exemplo n.º 13
0
 def dehydrate(self, bundle):
     u = bundle.request.user
     key = get_user_encryption_key(u.username)
     try:
         bundle.data['password'] = decrypt(bundle.data['password'], key)
     except:
         bundle.data['password'] = None
     return bundle
Exemplo n.º 14
0
 def dehydrate(self, bundle):
     u = bundle.request.user
     key = get_user_encryption_key(u.username)
     try:
         bundle.data["password"] = decrypt(bundle.data["password"], key)
     except:
         bundle.data["password"] = None
     return bundle
Exemplo n.º 15
0
def decrypt(context, data=None):
    request = context['request']
    key = request.session.get('key')
    try:
        dec = decrypt(data, key)
    except:
        dec = _('access denied')
    return dec
Exemplo n.º 16
0
    def test_normalize_and_encrypt(self):
        s = "Here's a test of thing!! "
        self.assertEquals(
            "Here's a test of thing!!",
            decrypt(normalize_and_encrypt(s))
        )

        s = "   Here's a test of thing!! "
        self.assertEquals(
            "Here's a test of thing!!",
            decrypt(normalize_and_encrypt(s))
        )

        s = """   Here's a TEST of thing!!        
"""  # noqa
        self.assertEquals(
            "Here's a TEST of thing!!",
            decrypt(normalize_and_encrypt(s))
        )
Exemplo n.º 17
0
 def clean(self):
     data = self.cleaned_data['encrypted_link']
     if not data:
         raise PermissionDenied
     user_id, now = decrypt(data).split("\t")
     user_id = int(user_id)
     if user_id != self.user_id:
         raise PermissionDenied
     link_generated_time = float(now)
     if abs(time.time() - link_generated_time) > 10:
         raise forms.ValidationError("Sorry, you waited too long, ... try again?")
Exemplo n.º 18
0
 def clean(self):
     data = self.cleaned_data['encrypted_link']
     if not data:
         raise PermissionDenied
     user_id, now = decrypt(data).split("\t")
     user_id = int(user_id)
     if user_id != self.user_id:
         raise PermissionDenied
     link_generated_time = float(now)
     if abs(time.time() - link_generated_time) > 10:
         raise forms.ValidationError("Sorry, you waited too long, ... try again?")
Exemplo n.º 19
0
def one_click_sign_in(request, link):
    # print(link)
    try:
        # print(decrypt(link))
        _, user_hashid, url = decrypt(link).split("|")
        me = Person.objects.get(hashid=user_hashid)
        update_session_auth_hash(request, me)
        login(request, me)
        return redirect(url)
    except:
        return redirect(reverse('login'))
Exemplo n.º 20
0
 def dispatch_recieved_messages(self, recieved):
     for connection, encrypted_message in recieved.items():
         fd = connection.fileno()
         if self.server.session_key_dict[fd] == '':
             session_key_encrypted = encrypted_message[0:128]
             auth_bmessage_encrypted = encrypted_message[128:]
             session_key = self.server.cipher_rsa_private.decrypt(
                 session_key_encrypted)
             self.server.session_key_dict[fd] = session_key
             auth_bmessage = encryption.decrypt(auth_bmessage_encrypted,
                                                session_key)
             auth_message = msg.Message()
             auth_message.make_from_binary_json(auth_bmessage, 'utf-8')
             self.server.authenticate_client(connection, auth_message)
         else:
             session_key = self.server.session_key_dict[fd]
             if fd in self.awaiting_file:
                 file_path = get_path(self.awaiting_file[fd].name)
                 f = encryption.decrypt_file(encrypted_message, session_key,
                                             file_path)
                 self.server.forward_file(self.awaiting_file[fd], file_path)
                 del self.awaiting_file[fd]
                 break
             bmessage = encryption.decrypt(encrypted_message, session_key)
             message = msg.Message()
             message.make_from_binary_json(bmessage, 'utf-8')
             if message.action == 'get_contacts':
                 username = message.user
                 self.server.send_contacts(connection, username)
             if message.action == 'add_contact':
                 self.server.add_contact(connection, message.user,
                                         message.contact)
             if message.action == 'delete_contact':
                 self.server.delete_contact(connection, message.user,
                                            message.contact)
             if message.action == 'personal_message':
                 self.server.forward_personal_message(connection, message)
             if message.action == 'send_file':
                 fdata = msg.File_data(message.name, message.filelength,
                                       message.src, message.dest)
                 self.awaiting_file[fd] = fdata
Exemplo n.º 21
0
 def clean_encrypted_link(self):
     data = self.cleaned_data['encrypted_link']
     if not data:
         raise PermissionDenied
     sound_id, now = decrypt(data).split("\t")
     sound_id = int(sound_id)
     if sound_id != self.sound_id:
         raise PermissionDenied
     link_generated_time = float(now)
     if abs(time.time() - link_generated_time) > 10:
         raise forms.ValidationError("Time expired")
     return data
Exemplo n.º 22
0
 def clean_encrypted_link(self):
     data = self.cleaned_data['encrypted_link']
     if not data:
         raise PermissionDenied
     user_id, now = decrypt(data).split("\t")
     user_id = int(user_id)
     if user_id != self.user_id:
         raise PermissionDenied
     link_generated_time = float(now)
     if abs(time.time() - link_generated_time) > 10:
         raise forms.ValidationError("Time expired")
     return data
Exemplo n.º 23
0
 def new_message(self):
     encrypted_data = self.reciever_thread.recieved_queue.get()
     if self.listener.waiting_file_flag:
         print(self.listener.file_data.name)
         file_path = get_path(self.listener.file_data.name)
         encryption.decrypt_file(encrypted_data, self.session_key,
                                 file_path)
         self.listener.new_file_recieved(file_path)
     else:
         bmessage = encryption.decrypt(encrypted_data, self.session_key)
         message = msg.GeneralMessage()
         message.make_from_binary_json(bmessage, 'utf-8')
         self.listener.new_message(message)
Exemplo n.º 24
0
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))
Exemplo n.º 25
0
def activate_user(request, activation_key, username):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse("accounts-home"))

    try:
        user_id = decrypt(activation_key)
        user = User.objects.get(id=int(user_id))
        user.is_active = True
        user.save()
        return render_to_response('accounts/activate.html', { 'all_ok': True }, context_instance=RequestContext(request))
    except User.DoesNotExist: #@UndefinedVariable
        return render_to_response('accounts/activate.html', { 'user_does_not_exist': True }, context_instance=RequestContext(request))
    except TypeError, ValueError:
        return render_to_response('accounts/activate.html', { 'decode_error': True }, context_instance=RequestContext(request))
Exemplo n.º 26
0
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))
Exemplo n.º 27
0
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))
Exemplo n.º 28
0
def decrypt_message(message):
    return encryption.decrypt(message, ukey)
Exemplo n.º 29
0
 def last_name(self):
     if not hasattr(self, "_decrypted_last_name"):
         self._decrypted_last_name = decrypt(self.encrypted_last_name)
     return self._decrypted_last_name
Exemplo n.º 30
0
 def email(self):
     if not hasattr(self, "_decrypted_email"):
         self._decrypted_email = decrypt(self.encrypted_email)
     return self._decrypted_email
Exemplo n.º 31
0
 def data(self):
     if not hasattr(self, "_decrypted_data"):
         self._decrypted_data = decrypt(self.encrypted_data)
     return self._decrypted_data