注册后编写后端以使用帐号对用户进行身份验证

时间:2019-07-26 12:24:17

标签: django django-views django-authentication

我正在创建一个银行系统,该系统应该在注册后使用电子邮件和密码自动对用户进行身份验证。然后,应该在注册后立即为用户分配唯一的帐号。然后,这些帐号将用于登录期间的身份验证。当我尝试使用分配的帐号登录用户时出现问题。它标记错误帐户不存在

我尝试查看backends.py文件以找出错误。我意识到,后端似乎无法从数据库中获取用户。但是,我无法指出应用程序中的确切错误。请协助。

models.py:

class User(AbstractUser):
    username = models.CharField(
        _('username'), max_length=30, unique=True, null=True, blank=True,
        help_text=_(
            'Required. 30 characters or fewer. Letters, digits and '
            '@/./+/-/_ only.'
        ),
        validators=[
            RegexValidator(
                r'^[\w.@+-]+$',
                _('Enter a valid username. '
                    'This value may contain only letters, numbers '
                    'and @/./+/-/_ characters.'), 'invalid'),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        })

    email = models.EmailField(unique=True, blank=True, null=True)
    contact_no = models.IntegerField(unique=False, null=True, blank=True)
    account_no = models.PositiveIntegerField(
        unique=True,
        validators=[
            MinValueValidator(1000000000),
            MaxValueValidator(9999999999)
        ]
    )
    balance = models.DecimalField(
        default=0,
        max_digits=12,
        decimal_places=2
    )
    GENDER_CHOICE = (
        ("M", "Male"),
        ("F", "Female"),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICE)
    birth_date = models.DateField(null=True, blank=True)
    city = models.CharField(max_length=256, blank=True, null=True)
    postal_code = models.PositiveSmallIntegerField(blank=True, null=True)
    country = models.CharField(max_length=256, blank=True, null=True)
    picture = models.ImageField(
        null=True,
        blank=True,
        upload_to='account_pictures/',
    )

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', ]

    def __str__(self):
        return str(self.full_name)

    @property
    def full_name(self):
        return '{} {}'.format(self.first_name, self.last_name)

    @property
    def full_address(self):
        return '{}, {}, {}'.format(
            self.postal_code,
            self.city,
            self.country,
        )


backends.py:

User = get_user_model()


class AccountNoBackend():

    def authenticate(self, request, account_no=None, password=None):
        try:
            user = User.objects.get(account_no=account_no)
            if user and user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

views.py:


def login_view(request):
    if request.user.is_authenticated:
        return redirect("home")
    else:
        form = UserLoginForm(request.POST or None)
        if form.is_valid():
            account_no = form.cleaned_data.get("account_no")
            password = form.cleaned_data.get("password")
            # authenticate with Account No & Password
            user = authenticate(account_no=account_no, password=password)
            login(request, user, backend='accounts.backends.AccountNoBackend')
            messages.success(request, 'Welcome, {}!' .format(user.full_name))
            return redirect("home")

        context = {"form": form,
                   "title": "Load Account Details",
                   }

        return render(request, "accounts/login.html", context)

managers.py:

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Create and save a user with the given account_no and password.
        """
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('account_no', False)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

我希望用户应该能够登录

0 个答案:

没有答案