![](/img/trans.png)
[英]Email verification and password reset - django rest framework and angularjs
[英]Django password reset with email using REST APIs
我正在使用 DjangoRest 和 Flutter 開發一個網站,我想使用 email 添加密碼重置。
我知道 django.contrib.auth 具有有助於密碼重置的視圖(PasswordResetView、PasswordResetDoneView 等)。 但只要我看到,當你在 Postman 中調用它們時,它們會返回 HTML 個文件作為響應。
有什么方法可以使用相同的易於使用的視圖,而不是獲取 HTML 文件,而是獲取 HTTP 響應,以便 Flutter 應用程序可以調用它?
這基本上可以通過兩個步驟來處理:
1. 一種是發送 OTP 或重置鏈接查看 email
2. 第二個是使用新密碼驗證 OTP/鏈接是否有效。
這可以通過簡單的基於函數的 API 視圖來實現:我可以使用 OTP 演示最簡單的形式來進行基本理解,正如你所說的,你在前端使用 flutter,這將更容易管理 otp 而不是鏈接
第1步:在用戶Model中添加一個top字段。假設我們在用戶model中有字段otp。稍后我們將其用於驗證目的。
class CustomerUser(models.Model):
#...
otp = models.CharField(
max_length=6, null=True, blank=True)
# Method to Put a Random OTP in the CustomerUser table.
def save(self, *args, **kwargs):
number_list = [x for x in range(10)] # Use of list comprehension
code_items_for_otp = []
for i in range(6):
num = random.choice(number_list)
code_items_for_otp.append(num)
code_string = "".join(str(item)
for item in code_items_for_otp) # list comprehension again
# A six digit random number from the list will be saved in top field
self.otp = code_string
super().save(*args, **kwargs)
步驟:2:Function 根據用戶請求發送帶有 OTP 的 Email
@api_view(['POST'])
def reset_request(request):
data = request.data
email = data['email']
user = CustomUser.objects.get(email=email)
if CustomUser.objects.filter(email=email).exists():
# send email with otp
send_mail(
'Subject here',
f'Here is the message with {user.otp}.',
'from@example.com',
[user.email],
fail_silently=False,
)
message = {
'detail': 'Success Message'}
return Response(message, status=status.HTTP_200_OK)
else:
message = {
'detail': 'Some Error Message'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
最后一步:驗證 OTP 並重置密碼
@api_view(['PUT'])
def reset_password(request):
"""reset_password with email, OTP and new password"""
data = request.data
user = CustomUser.objects.get(email=data['email'])
if user.is_active:
# Check if otp is valid
if data['otp'] == user.opt:
if new_password != '':
# Change Password
user.set_password(data['password'])
user.save() # Here user otp will also be changed on save automatically
return Response('any response or you can add useful information with response as well. ')
else:
message = {
'detail': 'Password cant be empty'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
else:
message = {
'detail': 'OTP did not matched'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
else:
message = {
'detail': 'Something went wrong'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
因此,您也可以使用自定義方法復制它並輕松重構它。 我在這些示例中使用了簡單的API 視圖,您也可以在 DRF DOCS 請求和響應部分查看詳細信息
因此,您根本不必使用 HTML,只需根據需要使用 Response、HttpResponse。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.