GeriLife / caregiving

GeriLife is a comprehensive toolkit designed to empower caregivers in elder-care communities, promoting wellness and ensuring equitable engagement in life-enriching activities. This project, rooted in real-world insights and collaborative innovation, aims to transform elder care by making quality-of-life activities visible and coordinated.
European Union Public License 1.2
7 stars 7 forks source link

[Feature]: Remove username field from user model #94

Open brylie opened 10 months ago

brylie commented 10 months ago

Feature Description

Remove the username field from the user model and use the email address as username.

Motivation

We don't have a use case for usernames.

hudy0 commented 10 months ago

Hello, @brylie I was working on this issue.

Issue

The task is to eliminate the username field from the user model while retaining the ability for users to log in using either a username or an email address.

Changes Made

Email Backend

UserModel = get_user_model()
class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserModel.objects.get(
                Q(email__iexact=username),
            )
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
            return
        except UserModel.MultipleObjectsReturned:
            user = (
                UserModel.objects.filter(
                    Q(email__iexact=username),
                )
                .order_by("id")
                .first()
            )

        if user.check_password(password) and self.user_can_authenticate(user):
            return user

LoginForm

class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Email / Username")

User Model

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_("email address"), unique=True)

LoginView

class LoginView(auth_views.LoginView):
    form_class = LoginForm
    template_name = "registration/login.html"

These changes have been tested and if are compatible with the project's requirements. I will submit the Pull request

Screenshot 2024-01-16 at 03 08 51
brylie commented 10 months ago

It looks good so far. Go ahead and fork this repository, commit your changes to your fork, and open a pull request. That way we can review and discuss the code. It will also make it easier to give you credit for your contributions.