-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrf-user_model.ps1
369 lines (273 loc) · 9.96 KB
/
drf-user_model.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
$working_dir = $args[0]
New-Item $working_dir -ItemType Directory -ea 0
Set-Location $working_dir
python -m venv .\venv
.\venv\Scripts\Activate.ps1
@'
djangorestframework>=3.14
'@ | Out-File -FilePath .\requirements.txt -Encoding utf8
pip install -r requirements.txt
django-admin startproject config .
# User Model
python manage.py startapp users
@'
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .managers import ApplicationUserManager
class ApplicationUser(AbstractBaseUser, PermissionsMixin):
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = ApplicationUserManager()
def __str__(self):
return self.email
def get_absolute_url(self):
return reverse('user_detail', kwargs={'pk': self.pk})
'@ | Out-File -FilePath .\users\models.py -Encoding utf8
@'
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-qt-sq3+6fm!)qcmxyugofjyz_0dn8p7ej$h^j=quntuw!4(x2-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'users',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_USER_MODEL = 'users.ApplicationUser'
DJANGO_SUPERUSER_PASSWORD = 'batman29'
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
'@ | Out-File -FilePath .\config\settings.py -Encoding utf8
@'
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import ApplicationUserCreationForm, ApplicationUserChangeForm
from .models import ApplicationUser
@admin.register(ApplicationUser)
class ApplicationUserAdmin(UserAdmin):
add_form = ApplicationUserCreationForm
form = ApplicationUserChangeForm
model = ApplicationUser
list_display = ('email', 'is_staff', 'is_active',)
list_filter = ('email', 'is_staff', 'is_active',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_staff', 'is_active', 'groups', 'user_permissions')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': (
'email', 'password1', 'password2', 'is_staff',
'is_active', 'groups', 'user_permissions'
)}
),
)
search_fields = ('email',)
ordering = ('email',)
'@ | Out-File -FilePath .\users\admin.py -Encoding utf8
@'
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import ApplicationUser
class ApplicationUserCreationForm(UserCreationForm):
class Meta:
model = ApplicationUser
fields = ('email',)
class ApplicationUserChangeForm(UserChangeForm):
class Meta:
model = ApplicationUser
fields = ('email',)
'@ | Out-File -FilePath .\users\forms.py -Encoding utf8
@'
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _
class ApplicationUserManager(BaseUserManager):
'''
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
'''
def create_user(self, email, password, **extra_fields):
'''
Create and save a user with the given email and password.
'''
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
'''
Create and save a SuperUser with the given email and password.
'''
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', 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)
'@ | Out-File -FilePath .\users\managers.py -Encoding utf8
@'
from rest_framework import serializers
from .models import ApplicationUser
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = ApplicationUser
fields = ['email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = ApplicationUser(
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
'@ | Out-File -FilePath .\users\serializers.py -Encoding utf8
@'
from . import views
from django.urls import path
urlpatterns = [
path('create/', views.Register.as_view(), name='register'),
path('login/', views.Login.as_view(), name='login'),
path('logout/', views.Logout.as_view(), name='logout'),
]
'@ | Out-File -FilePath .\users\urls.py -Encoding utf8
@'
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import status
from rest_framework.authentication import authenticate
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework import views
from .models import ApplicationUser
from .serializers import UserSerializer
class Register(views.APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Login(views.APIView):
def post(self, request):
email = request.data.get('email')
password = request.data.get('password')
user = None
if '@' in email:
try:
user = ApplicationUser.objects.get(email=email)
except ObjectDoesNotExist:
print('invalid email')
if not user:
user = authenticate(email=email, password=password)
if user:
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=status.HTTP_200_OK)
return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
class Logout(views.APIView):
def get(self, request, format=None):
request.user.auth_token.delete()
return Response(status=status.HTTP_200_OK)
'@ | Out-File -FilePath .\users\views.py -Encoding utf8
@'
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
]
'@ | Out-File -FilePath .\config\urls.py -Encoding utf8
Write-Output 'Migrations are coming...'
python manage.py makemigrations
python manage.py migrate