MarisiaS / SMM

0 stars 0 forks source link

BE- Create a custom user model and manager #35

Closed viriponce closed 7 months ago

viriponce commented 7 months ago

This PR addresses issue #34

Implementation

1. backend/api/managers.py

In order to create a custom user model we need to create first a user manager. Created a CustomUserManager that extends from BaseUserManager that uses the email as the unique identifier instead of a username.

2. backend/api/models.py

We decided that we wanted to keep most of the field provided by default in Django User model, so I created a new class called CustomUser that subclasses AbstractUser.

Removed the username field. Made the email field required and unique. Set the USERNAME_FIELD which defines the unique identifier for the User model to email. Set the REQUIRED_FIELDS to first_name, last_name. Specified that all objects for the class come from the CustomUserManager.

3. backend/project/settings.py Set AUTH_USER_MODEL in the settings file in order to use the new custom user class:

AUTH_USER_MODEL = "api.CustomUser"

After all the setup mentioned above, I created the migration running the makemigrations coomand:

python manage.py makemigrations

The migration file with the initial migration was generated in _backend/api/migrations/0001initial.py which creates the table for the custom users.

All the other changes is because I had to change the name of the app from SMMapp to api because the upercase letter were causing issues when trying to access the tables using psql.

We can confirm the table was created in the database. It has email as unique:

Screenshot 2024-02-08 at 4 46 52 PM

Swagger

The endpoint POST /api/auth/users/ offered by djoser, now has first_name and last name when creating a new user:

Screenshot 2024-02-08 at 4 52 42 PM

The login endpoint now has email key instead of username:

Screenshot 2024-02-08 at 4 49 22 PM