Пользовательский токен Django не проходит аутентификацию пользователем, под которым он создан
i Создайте функцию views для установки user.is_active в true с помощью ссылки для активации учетной записи пользователя в django
Ссылка содержит uidb64 и токен
я генерирую токен при регистрации и отправляю эту ссылку по электронной почте, но она не проходит аутентификацию с пользователем
здесь находится функция отправки ссылок
def register(request):
error = None
if request.method == 'POST':
form = RegisterUser(data= request.POST)
email = request.POST['email']
first_name = request.POST['first_name']
last_name = request.POST['last_name']
phone_number = request.POST['phone_number']
password = request.POST['password']
password1 = request.POST['password1']
username = request.POST['email']
if (email) and (first_name) and (last_name) and (phone_number) and (password) and (password1) and (username):
try:
user = Account.objects.get(username = username)
error = 'user with this email already exists'
return render(request, 'account/register.html', {'error':error})
except Account.DoesNotExist:
if password == password1:
user = Account.objects.create_user(email= email,first_name= first_name,last_name= last_name,password= password, username=username)
user.phone_number = phone_number
# user activation
current_site = get_current_site(request)
email_subject = 'Activate your account'
message = render_to_string('account/email.html',{'user': user , 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)) ,
'token':default_token_generator.make_token(user)
})
email_from = settings.EMAIL_HOST_USER
to_email = email
send_email = EmailMessage(email_subject, message , to=[email])
send_email.send()
user.save()
print(user)
else:
error = "Passwords didn't match"
return render(request, 'account/register.html', {'error':error})
else:
error = 'Fill the form correctly'
return render(request, 'account/register.html', {'error':error})
context = {
}
return render(request, 'account/register.html',context)
вот код, где я проверяю токен
def activate(request, uidb64 ,token):
try:
uid = urlsafe_base64_decode(uidb64).decode()
user = Account._default_manager.get(pk = uid)
except (TypeError,ValueError,OverflowError,Account.DoesNotExist):
user = None
print(default_token_generator.check_token(user, token))
# This is retruning false
if user is not None:
if default_token_generator.check_token(user, token):
user.is_active = True
user.email = 'gnai'
user.save()
print(user)
print('thosi')
print(user.email)
return render(request , 'core/base.html')
else:
print(',a')
Проблема в том, что print(default_token_generator.check_token(user, token)) возвращает False
вот как я создаю пользователя
class MyAccountManager(BaseUserManager):
def create_user(self,first_name, last_name, username, email , password =None):
if not email:
raise ValueError('Email Address is not present.')
if not username:
raise ValueError('Username is not present')
user = self.model(
email = self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password)
user.save(using= self._db)
return user
def create_superuser(self,first_name, last_name, username, email , password):
user = self.create_user(
email = self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
password = password,
)
user.is_admin = True
user.is_staff = True
user.is_active = True
user.is_superadmin = True
user.save(using= self._db)
return user
# Create your models here.
class Account(AbstractBaseUser):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
username = models.CharField(max_length=50 , unique=True)
email = models.EmailField(max_length = 100 , unique=True)
phone_number = models.CharField( max_length=50)
# required fields for
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_superadmin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name' ,'last_name']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm , obj=None):
return self.is_admin
def has_module_perms(self , add_label):
return True
если необходима дополнительная информация, просто прокомментируйте ниже спасибо!
Я нашел ответ поскольку мы знаем, что токен также использует время для генерации токена. то в моем случае он использует время последнего входа в систему для генерирования токена затем теперь о решении Я перемещаю user.save до того, как токен будет сгенерирован
теперь новый код выглядит следующим образом
def register(request):
error = None
if request.method == 'POST':
form = RegisterUser(data= request.POST)
email = request.POST['email']
first_name = request.POST['first_name']
last_name = request.POST['last_name']
phone_number = request.POST['phone_number']
password = request.POST['password']
password1 = request.POST['password1']
username = request.POST['email']
if (email) and (first_name) and (last_name) and (phone_number) and (password) and (password1) and (username):
try:
user = Account.objects.get(username = username)
error = 'user with this email already exists'
return render(request, 'account/register.html', {'error':error})
except Account.DoesNotExist:
if password == password1:
user = Account.objects.create_user(email= email,first_name= first_name,last_name= last_name,password= password, username=username)
user.phone_number = phone_number
user.save()
token =default_token_generator.make_token(user)
print(user)
print(token)
# user activation
current_site = get_current_site(request)
email_subject = 'Activate your account'
message = render_to_string('account/email.html',{'user': user , 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)) ,
'token':token,
})
email_from = settings.EMAIL_HOST_USER
to_email = email
send_email = EmailMessage(email_subject, message , to=[email])
send_email.send()
print(user)
print(token)
else:
error = "Passwords didn't match"
return render(request, 'account/register.html', {'error':error})
else:
error = 'Fill the form correctly'
return render(request, 'account/register.html', {'error':error})
context = {
}
return render(request, 'account/register.html',context)