我希望注冊用戶首先使用電子郵件或電話號碼和密碼登錄。如果用戶忘記了密碼,那么應該有可能繞過密碼通過 OTP 登錄,該密碼將通過用戶電話號碼上的 SMS 提供。那么有沒有可能實作這一目標?
這是始終需要密碼欄位的官方檔案。 https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example 我知道如果我們愿意,我們可以將用戶名更改為電子郵件或電話號碼,但我們如何把使用密碼/隨機 OTP 登錄的條件。那么我們如何才能做到這一點呢?建議將不勝感激。謝謝
uj5u.com熱心網友回復:
是的,我們可以使用強制登錄來做到這一點,這是一個例子,我是如何做到的,請看看我有一個與用戶一對一關系的個人資料
def login_otp(request):
mobile = request.session['mobile']
context = {'mobile':mobile}
if request.method == 'POST':
otp = request.POST.get('otp')
profile = Profile.objects.filter(mobile=mobile).first()
if otp == profile.otp:
user = User.objects.get(id = profile.user.id)
login(request , user)
return redirect('cart')
else:
context = {'message' : 'Wrong OTP' , 'class' : 'danger','mobile':mobile }
return render(request,'login_otp.html' , context)
return render(request,'login_otp.html' , context)
uj5u.com熱心網友回復:
你可以自己CustomLoginBackend做
from django.contrib.auth import get_user_model
class CustomLoginBackend(object):
def authenticate(self, request, email, password, otp):
User = get_user_model()
try:
user = User.objects.using(db_name).get(email=email)
except User.DoesNotExist:
return None
else:
if password is not None:
if getattr(user, 'is_active', False) and user.check_password(password):
return user
else:
if getattr(user, 'is_active', False) and user.otp == otp: #<-- otp included in user table
return user
return None
那么在你login看來。
from django.contrib.auth import authenticate, login
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
email = request.POST.get('email', None)
password = request.POST.get('password', None)
otp = request.POST.get('otp', None)
user = authenticate(request, email=email, password=password, otp=otp)
if user is not None:
login(request, user)
# redirect to a success page
return redirect('dashboard')
else:
if password is not None:
# return either email or password incorrect
messages.error(request, "Invalid Email or Password")
return redirect('login')
else:
# return invalid otp
messages.error(request, "Invalid OTP")
return redirect('login')
return render(request, 'login.html')
最后別忘了添加AUTHENTICATION_BACKENDS你的settings.pyas
AUTHENTICATION_BACKENDS = ['path_to_your.CustomLoginBackend ',]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422731.html
標籤:
上一篇:我的視圖物件在Django中“沒有屬性”{我的屬性}
下一篇:我的分頁似乎不起作用-DRF問題
