Add reset password api

This commit is contained in:
Chiaki
2017-04-18 11:57:57 +08:00
parent 8a68ad7ac9
commit e3692c2329
5 changed files with 75 additions and 13 deletions

View File

@@ -1,15 +1,25 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import codecs
from datetime import timedelta
from django.contrib import auth
from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned
from django.utils.translation import ugettext as _
from django.utils.timezone import now
from otpauth import OtpAuth
from utils.api import APIView, validate_serializer
from utils.captcha import Captcha
from utils.shortcuts import rand_str
from ..decorators import login_required
from ..models import User, UserProfile
from ..serializers import (UserChangePasswordSerializer, UserLoginSerializer,
UserRegisterSerializer)
UserRegisterSerializer,
ApplyResetPasswordSerializer)
class UserLoginAPI(APIView):
@@ -92,3 +102,44 @@ class UserChangePasswordAPI(APIView):
return self.success(_("Succeeded"))
else:
return self.error(_("Invalid old password"))
class ApplyResetPasswordAPI(APIView):
@validate_serializer(ApplyResetPasswordSerializer)
def post(self, request):
data = request.data
captcha = Captcha(request)
if not captcha.check(data["captcha"]):
return self.error(_("Invalid captcha"))
try:
user = User.objects.get(email=data["email"])
except User.DoesNotExist:
return self.error(_("User does not exist"))
if user.reset_password_token_expire_time and 0 < (
user.reset_password_token_expire_time - now()).total_seconds() < 20 * 60:
return self.error(_("You can only reset password once per 20 minutes"))
user.reset_password_token = rand_str()
user.reset_password_token_expire_time = now() + timedelta(minutes=20)
user.save()
# TODO:email template
# TODO:send email
return self.success(_("Succeeded"))
class ResetPasswordAPI(APIView):
def post(self, request):
data = request.data
captcha = Captcha(request)
if not captcha.check(data["captcha"]):
return self.error(_("Invalid captcha"))
try:
user = User.objects.get(reset_password_token=data["token"])
except User.DoesNotExist:
return self.error(_("Token dose not exist"))
if 0 < (user.reset_password_token_expire_time - now()).total_seconds() < 30 * 60:
return self.error(_("Token expired"))
user.reset_password_token = None
user.set_password(data["password"])
user.save()
return self.success(_("Succeeded"))