示例#1
0
 def test_check_token_with_nonexistent_token_and_user(self):
     user = User.objects.create_user('tokentestuser', '*****@*****.**',
                                     'testpw')
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertIs(p0.check_token(None, tk1), False)
     self.assertIs(p0.check_token(user, None), False)
示例#2
0
    def test_django12_hash(self):
        """
        Ensure we can use the hashes generated by Django 1.2
        """
        # Hard code in the Django 1.2 algorithm (not the result, as it is time
        # dependent)
        def _make_token(user):
            from django.utils.hashcompat import sha_constructor
            from django.utils.http import int_to_base36

            timestamp = (date.today() - date(2001, 1, 1)).days
            ts_b36 = int_to_base36(timestamp)
            hash = sha_constructor(
                settings.SECRET_KEY
                + unicode(user.id)
                + user.password
                + user.last_login.strftime("%Y-%m-%d %H:%M:%S")
                + unicode(timestamp)
            ).hexdigest()[::2]
            return "%s-%s" % (ts_b36, hash)

        user = User.objects.create_user("tokentestuser", "*****@*****.**", "testpw")
        p0 = PasswordResetTokenGenerator()
        tk1 = _make_token(user)
        self.assertTrue(p0.check_token(user, tk1))
示例#3
0
文件: tokens.py 项目: 0xmilk/appscale
 def test_make_token(self):
     """
     Ensure that we can make a token and that it is valid
     """
     user = User.objects.create_user('tokentestuser', '*****@*****.**', 'testpw')
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertTrue(p0.check_token(user, tk1))
示例#4
0
 def authenticate(self, user_token, key_token):
     try:
         token_generator=PasswordResetTokenGenerator()
         user = get_object_or_404(User, pk=base36_to_int(user_token))
         if token_generator.check_token( user, key_token) and user.is_active:
             logger.debug("User: %s authenticated via token" % user.username)
             return user
     except User.DoesNotExist:
         return None
示例#5
0
文件: tokens.py 项目: 0xmilk/appscale
    def test_date_length(self):
        """
        Make sure we don't allow overly long dates, causing a potential DoS.
        """
        user = User.objects.create_user('ima1337h4x0r', '*****@*****.**', 'p4ssw0rd')
        p0 = PasswordResetTokenGenerator()

        # This will put a 14-digit base36 timestamp into the token, which is too large.
        tk1 = p0._make_token_with_timestamp(user, 175455491841851871349)
        self.assertFalse(p0.check_token(user, tk1))
示例#6
0
 def test_token_with_different_secret(self):
     """
     A valid token can be created with a secret other than SECRET_KEY by
     using the PasswordResetTokenGenerator.secret attribute.
     """
     user = User.objects.create_user('tokentestuser', '*****@*****.**', 'testpw')
     new_secret = 'abcdefghijkl'
     # Create and check a token with a different secret.
     p0 = PasswordResetTokenGenerator()
     p0.secret = new_secret
     tk0 = p0.make_token(user)
     self.assertTrue(p0.check_token(user, tk0))
     # Create and check a token with the default secret.
     p1 = PasswordResetTokenGenerator()
     self.assertEqual(p1.secret, settings.SECRET_KEY)
     self.assertNotEqual(p1.secret, new_secret)
     tk1 = p1.make_token(user)
     # Tokens created with a different secret don't validate.
     self.assertFalse(p0.check_token(user, tk1))
     self.assertFalse(p1.check_token(user, tk0))
示例#7
0
def reset_password(request):
    token = request.POST.get('token')
    username_or_email = request.POST.get('username_or_email')
    password = request.POST.get('password')

    try:
        empous_user = User.objects.get(Q(username__iexact=username_or_email)|Q(email__iexact=username_or_email))
        token_gen = PasswordResetTokenGenerator()
        if token_gen.check_token(empous_user, token):
            empous_user.set_password(password)
            empous_user.save()
            return HttpResponse(json.dumps(StatusCodes.SUCCESS), mimetype='application/json')
        else:
            return HttpResponse(json.dumps(StatusCodes.TOKEN_INVALID), mimetype='application/json')

    except User.DoesNotExist:
        return HttpResponse(json.dumps(StatusCodes.USER_DOESNT_EXIST), mimetype='application/json')
示例#8
0
def edit(request, key=None):
    member = get_object_or_404(Member, key=key)
    if "token" in request.REQUEST:
        token = request.REQUEST["token"]
        token_gen = PasswordResetTokenGenerator()
        if token_gen.check_token(member, token):
            member.backend = (
                "django.contrib.auth.backends.ModelBackend"
            )  # from: http://stackoverflow.com/questions/2787650/manually-logging-in-a-user-without-password
            login(request, member)
            return HttpResponseRedirect(reverse(edit, kwargs={"key": member.key}))
    if request.method == "POST":
        form = MemberForm(request.POST, instance=member)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(edit, kwargs={"key": member.key}))
    form = MemberForm(instance=member)
    return render(request, "members/form.html", {"member": member, "form": form})
示例#9
0
 def test_make_token(self):
     user = User.objects.create_user('tokentestuser', '*****@*****.**', 'testpw')
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertTrue(p0.check_token(user, tk1))
示例#10
0
    def post(self, request, *args, **kwargs):
        method = request.POST.get('_method')
        _query = request.GET.copy()
        print request.REQUEST.__str__();
        print _query;
        _query.pop("error", None)
        _query.pop("message", None)
        _query.pop("success", None)
        if method == 'PUT':
            password = request.POST.get('password')
            password_confirm = request.POST.get('password_confirm')
            email = request.GET.get('email')
            token = request.GET.get('token')
            print email
            if password == password_confirm:
                try:
                    user = User.objects.get(email=email)
                    token_gen = PasswordResetTokenGenerator()
                    if token_gen.check_token(user, token):
                        user.set_password(password)
                        user.save()
                        _query['success'] = 'password_changed'
                        _query['message'] = 'Tu password ha sido cambiado!'
                        # redirect ?success=password_changed
                    else:
                        _query['error'] = 'invalid_token'
                        _query['message'] = 'Esta url ha caducado o es inválida!'
                        # redirect ?error=invalid_token
                except ObjectDoesNotExist:
                    # redirect ?error=user_does_not_exist
                    _query['error'] = 'user_does_not_exist'
                    _query['message'] = 'El usuario no existe!'
            else:
                # redirect ?error=password_missmatch
                _query['error'] = 'password_missmatch'
                _query['message'] = 'Las contraseñas no coinciden!'
                pass
        else:
            email = request.POST.get('email')

            user = User.objects.get(email=email)
            if user:
                token_gen = PasswordResetTokenGenerator()
                token = token_gen.make_token(user)
                print user.username
                ctx = {
                    "name": user.username,
                    "url": request.build_absolute_uri(reverse('recuperar_pass')) + '?token=' + token + '&email=' + email
                }
                mensaje = get_template('registration/mail.recuperar.html').render(Context(ctx))
                to = [email]
                mail = EmailMessage('Recuperar Contraseña',
                                    mensaje,
                                    to=to,
                                    from_email=settings.EMAIL_HOST_USER)
                mail.content_type = 'html'
                mail.send()

            _query['success'] = 'email_sent'
            _query['message'] = 'Se ha enviado un correo con las instrucciones!'
            # redirect ?success=email_sent
        return redirect(reverse('recuperar_pass') + '?' + _query.urlencode())
示例#11
0
 def test_make_token(self):
     user = User.objects.create_user('tokentestuser', '*****@*****.**',
                                     'testpw')
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertTrue(p0.check_token(user, tk1))
示例#12
0
 def test_check_token_with_nonexistent_token_and_user(self):
     user = User.objects.create_user("tokentestuser", "*****@*****.**", "testpw")
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertIs(p0.check_token(None, tk1), False)
     self.assertIs(p0.check_token(user, None), False)
示例#13
0
 def test_make_token(self):
     user = User.objects.create_user("tokentestuser", "*****@*****.**", "testpw")
     p0 = PasswordResetTokenGenerator()
     tk1 = p0.make_token(user)
     self.assertIs(p0.check_token(user, tk1), True)
示例#14
0
def validate_token(user, token):
    password_reset = PasswordResetTokenGenerator()
    return password_reset.check_token(user, token)