[extensions-web/feature/custom-user-class-step2: 3/4] users: migrate to custom User class




commit 525f0450e4837ac3698e5c96aa4fd98489e5097e
Author: Yuri Konotopov <ykonotopov gnome org>
Date:   Sun May 22 16:17:37 2022 +0400

    users: migrate to custom User class
    
    See-Also: 
https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project
    See-Also: https://code.djangoproject.com/ticket/25313

 sweettooth/auth/backends.py                        |  2 +-
 sweettooth/auth/forms.py                           | 12 ++++++--
 .../extensions/testdata/test_upgrade_data.json     |  2 +-
 sweettooth/settings.py                             |  1 +
 sweettooth/users/migrations/0001_initial.py        | 35 +++++++++++++++++++++-
 .../users/migrations/0002_change_user_type.py      | 29 ++++++++++++++++++
 .../users/migrations/0003_rename_users_table.py    | 17 +++++++++++
 sweettooth/users/models.py                         | 15 ++++++++++
 8 files changed, 108 insertions(+), 5 deletions(-)
---
diff --git a/sweettooth/auth/backends.py b/sweettooth/auth/backends.py
index 2486572..9c2708f 100644
--- a/sweettooth/auth/backends.py
+++ b/sweettooth/auth/backends.py
@@ -9,7 +9,7 @@
 """
 
 from django.contrib.auth.backends import ModelBackend, UserModel
-from django.contrib.auth.models import User
+
 
 class LoginEmailAuthentication(ModelBackend):
     def authenticate(self, request, username=None, password=None, **kwargs):
diff --git a/sweettooth/auth/forms.py b/sweettooth/auth/forms.py
index c9c4291..b9d9cb6 100644
--- a/sweettooth/auth/forms.py
+++ b/sweettooth/auth/forms.py
@@ -1,8 +1,12 @@
 
 from django import forms
-from django.contrib.auth import forms as auth_forms
+from django.contrib.auth import forms as auth_forms, get_user_model
 from django.utils.translation import gettext_lazy as _
-from django_registration.forms import RegistrationFormCaseInsensitive, RegistrationFormUniqueEmail
+from django_registration.forms import (
+    RegistrationForm as BaseRegistrationForm,
+    RegistrationFormCaseInsensitive,
+    RegistrationFormUniqueEmail
+)
 
 class PlainOutputForm(object):
     def as_plain(self):
@@ -41,7 +45,11 @@ class AuthenticationForm(LoginOrEmailAuthenticationForm, AutoFocusForm,
                         auth_forms.AuthenticationForm):
     pass
 
+
 class RegistrationForm(RegistrationFormCaseInsensitive, RegistrationFormUniqueEmail):
+    class Meta(BaseRegistrationForm.Meta):
+        model = get_user_model()
+
     # Copies the standard setting from the django.contrib.auth.forms
     username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
         help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
diff --git a/sweettooth/extensions/testdata/test_upgrade_data.json 
b/sweettooth/extensions/testdata/test_upgrade_data.json
index 8391737..5b7f7da 100644
--- a/sweettooth/extensions/testdata/test_upgrade_data.json
+++ b/sweettooth/extensions/testdata/test_upgrade_data.json
@@ -139,7 +139,7 @@
   },
   {
     "pk": 1,
-    "model": "auth.User",
+    "model": "users.User",
     "fields": {
       "username": "Test",
       "email": "test@localhost.local",
diff --git a/sweettooth/settings.py b/sweettooth/settings.py
index 09f9f08..947350d 100644
--- a/sweettooth/settings.py
+++ b/sweettooth/settings.py
@@ -73,6 +73,7 @@ if 'EGO_CORS_ORIGINS' in os.environ:
     INSTALLED_APPS.append('corsheaders')
     CORS_ORIGIN_WHITELIST = list(map(str.strip, os.environ['EGO_CORS_ORIGINS'].split(",")))
 
+AUTH_USER_MODEL = 'users.User'
 AUTHENTICATION_BACKENDS = ['sweettooth.auth.backends.LoginEmailAuthentication']
 
 SECURE_BROWSER_XSS_FILTER = True
diff --git a/sweettooth/users/migrations/0001_initial.py b/sweettooth/users/migrations/0001_initial.py
index 34c177f..40eba69 100644
--- a/sweettooth/users/migrations/0001_initial.py
+++ b/sweettooth/users/migrations/0001_initial.py
@@ -1,12 +1,45 @@
 # Generated by Django 3.2.13 on 2022-05-21 17:58
 
-from django.db import migrations
+import django.contrib.auth.models
+import django.contrib.auth.validators
+from django.db import migrations, models
+import django.utils.timezone
 
 
 class Migration(migrations.Migration):
 
+    initial = True
+
     dependencies = [
+        ('auth', '0012_alter_user_first_name_max_length'),
     ]
 
     operations = [
+        migrations.CreateModel(
+            name='User',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, 
verbose_name='ID')),
+                ('password', models.CharField(max_length=128, verbose_name='password')),
+                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
+                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has 
all permissions without explicitly assigning them.', verbose_name='superuser status')),
+                ('username', models.CharField(error_messages={'unique': 'A user with that username already 
exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', 
max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], 
verbose_name='username')),
+                ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
+                ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
+                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
+                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can 
log into this admin site.', verbose_name='staff status')),
+                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user 
should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
+                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date 
joined')),
+                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A 
user will get all permissions granted to each of their groups.', related_name='user_set', 
related_query_name='user', to='auth.Group', verbose_name='groups')),
+                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for 
this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user 
permissions')),
+            ],
+            options={
+                'verbose_name': 'user',
+                'verbose_name_plural': 'users',
+                'abstract': False,
+                'db_table': 'auth_user',
+            },
+            managers=[
+                ('objects', django.contrib.auth.models.UserManager()),
+            ],
+        ),
     ]
diff --git a/sweettooth/users/migrations/0002_change_user_type.py 
b/sweettooth/users/migrations/0002_change_user_type.py
new file mode 100644
index 0000000..c3c6bc9
--- /dev/null
+++ b/sweettooth/users/migrations/0002_change_user_type.py
@@ -0,0 +1,29 @@
+# Generated by Django 3.2.13 on 2022-05-22 10:22
+
+from django.apps.registry import Apps
+from django.db import migrations
+from django.contrib.contenttypes.models import ContentType as ContentTypeModel
+from django.db.backends.base.schema import BaseDatabaseSchemaEditor
+
+
+def change_user_type(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
+    ContentType: ContentTypeModel = apps.get_model('contenttypes', 'ContentType')
+    ct = ContentType.objects.filter(
+        app_label='auth',
+        model='user'
+    ).first()
+
+    if ct:
+        ct.app_label = 'user'
+        ct.save()
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('users', '0001_initial'),
+    ]
+
+    operations = [
+        migrations.RunPython(change_user_type, elidable=True),
+    ]
diff --git a/sweettooth/users/migrations/0003_rename_users_table.py 
b/sweettooth/users/migrations/0003_rename_users_table.py
new file mode 100644
index 0000000..e78c682
--- /dev/null
+++ b/sweettooth/users/migrations/0003_rename_users_table.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.13 on 2022-05-22 10:59
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('users', '0002_change_user_type'),
+    ]
+
+    operations = [
+        migrations.AlterModelTable(
+            name='user',
+            table=None,
+        ),
+    ]
diff --git a/sweettooth/users/models.py b/sweettooth/users/models.py
new file mode 100644
index 0000000..61487eb
--- /dev/null
+++ b/sweettooth/users/models.py
@@ -0,0 +1,15 @@
+"""
+    GNOME Shell extensions repository
+    Copyright (C) 2022  Yuri Konotopov <ykonotopov gnome org>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+"""
+
+from django.contrib.auth.models import AbstractUser
+
+
+class User(AbstractUser):
+    pass


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]