Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # urls.py
- from django.contrib import admin
- from django.urls import include, path
- from dj_rest_auth.registration.views import VerifyEmailView, ConfirmEmailView
- from dj_rest_auth.views import PasswordResetConfirmView
- urlpatterns = [
- path('admin/', admin.site.urls),
- path('dj-rest-auth/', include('dj_rest_auth.urls'), name='dj-rest-auth'),
- path(
- 'dj-rest-auth/registration/account-confirm-email/<str:key>/',
- ConfirmEmailView.as_view(),
- ),
- path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
- path('dj-rest-auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'),
- path(
- 'rest-auth/password/reset/confirm/<slug:uidb64>/<slug:token>/',
- PasswordResetConfirmView.as_view(),
- name='password_reset_confirm',
- ),
- ]
- ================================================================================================================
- # settings.py
- from datetime import timedelta
- from functools import partial
- from pathlib import Path
- import dj_database_url
- from decouple import Csv, config
- # 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/3.1/howto/deployment/checklist/
- # SECURITY WARNING: keep the secret key used in production secret!
- SECRET_KEY = config('SECRET_KEY')
- # SECURITY WARNING: don't run with debug turned on in production!
- DEBUG = config('DEBUG', cast=bool)
- # Allowed Hosts
- ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
- # Tells the framework which will be the default class used as a user
- AUTH_USER_MODEL = 'accounts.User'
- # Application definition
- INSTALLED_APPS = [
- # Django Apps
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- # Local Apps
- 'billapp.accounts',
- # Third-Party Apps
- 'rest_framework',
- 'rest_framework.authtoken',
- 'corsheaders',
- 'dj_rest_auth',
- 'django.contrib.sites',
- 'allauth',
- 'allauth.account',
- 'allauth.socialaccount',
- 'dj_rest_auth.registration',
- ]
- AUTHENTICATION_BACKENDS = [
- # Needed to login by email in Django admin, regardless of allauth
- 'django.contrib.auth.backends.ModelBackend',
- # allauth specific authentication methods, such as login by e-mail
- 'allauth.account.auth_backends.AuthenticationBackend',
- ]
- SITE_ID = 1
- ACCOUNT_AUTHENTICATION_METHOD = 'email'
- ACCOUNT_EMAIL_REQUIRED = True
- ACCOUNT_UNIQUE_EMAIL = True
- ACCOUNT_USER_MODEL_USERNAME_FIELD = None
- ACCOUNT_USERNAME_REQUIRED = False
- # ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
- ACCOUNT_CONFIRM_EMAIL_ON_GET = True
- LOGIN_URL = 'http://localhost:8000/dj-rest-auth/login'
- REST_USE_JWT = True
- JWT_AUTH_COOKIE = 'billapp'
- REST_AUTH_REGISTER_SERIALIZERS = {
- 'REGISTER_SERIALIZER': 'billapp.accounts.serializers.CustomRegisterSerializer',
- }
- REST_AUTH_SERIALIZERS = {
- 'USER_DETAILS_SERIALIZER': 'billapp.accounts.serializers.CustomRegisterSerializer',
- }
- EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
- # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
- # EMAIL_HOST = 'your.email.host'
- # EMAIL_USE_TLS = True
- # EMAIL_PORT = 587
- # EMAIL_HOST_USER = 'your email host user'
- # EMAIL_HOST_PASSWORD = 'your email host password'
- MIDDLEWARE = [
- 'corsheaders.middleware.CorsMiddleware',
- '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',
- ]
- # CONFIGURATION CORS
- CORS_ORIGIN_ALLOW_ALL = True
- CORS_ALLOW_CREDENTIALS = True
- # CORS_ORIGIN_WHITELIST = [
- # 'https://127.0.0.1:8080',
- # 'https://127.0.0.1:8000',
- # ]
- # CONFIGURATION REST_FRAMEWORK
- REST_FRAMEWORK = {
- 'TEST_REQUEST_RENDERER_CLASSES': [
- 'rest_framework.renderers.MultiPartRenderer',
- 'rest_framework.renderers.JSONRenderer',
- 'rest_framework.renderers.TemplateHTMLRenderer',
- ],
- 'DEFAULT_AUTHENTICATION_CLASSES': [
- 'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
- # 'rest_framework_simplejwt.authentication.JWTAuthentication',
- ],
- 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
- 'PAGE_SIZE': 20,
- }
- # CONFIGURATION SIMPLE JWT
- SIMPLE_JWT = {
- 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
- 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=60),
- 'ROTATE_REFRESH_TOKENS': False,
- 'BLACKLIST_AFTER_ROTATION': True,
- 'UPDATE_LAST_LOGIN': False,
- 'ALGORITHM': 'HS256',
- 'VERIFYING_KEY': None,
- 'AUDIENCE': None,
- 'ISSUER': None,
- 'AUTH_HEADER_TYPES': ('Bearer',),
- 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
- 'USER_ID_FIELD': 'id',
- 'USER_ID_CLAIM': 'user_id',
- 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
- 'TOKEN_TYPE_CLAIM': 'token_type',
- 'JTI_CLAIM': 'jti',
- 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
- 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
- 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
- }
- ROOT_URLCONF = 'billapp.urls'
- 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 = 'billapp.wsgi.application'
- # Database
- # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
- default_db_url = default_db_url = 'sqlite:///' + str(BASE_DIR / 'db.sqlite3')
- parse_database = partial(dj_database_url.parse, conn_max_age=600)
- DATABASES = {'default': config('DATABASE_URL', default=default_db_url, cast=parse_database)}
- # Password validation
- # https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
- LANGUAGE_CODE = 'en-us'
- TIME_ZONE = 'UTC'
- USE_I18N = True
- USE_L10N = True
- USE_TZ = True
- # Static files (CSS, JavaScript, Images)
- # https://docs.djangoproject.com/en/3.1/howto/static-files/
- STATIC_URL = '/static/'
- ================================================================================================================
- # serializers.py
- from django.db import transaction
- from rest_framework import serializers
- from dj_rest_auth.registration.serializers import RegisterSerializer
- class CustomRegisterSerializer(RegisterSerializer):
- first_name = serializers.CharField(max_length=30)
- last_name = serializers.CharField(max_length=150)
- email = serializers.EmailField()
- cpf = serializers.CharField(max_length=11)
- # Define transaction.atomic to rollback the save operation in case of error
- @transaction.atomic
- def save(self, request):
- user = super().save(request)
- user.first_name = self.data.get('first_name')
- user.last_name = self.data.get('last_name')
- user.email = self.data.get('email')
- user.cpf = self.data.get('cpf')
- user.save()
- return user
- ================================================================================================================
- # conftest.py
- import pytest
- from django.contrib.auth import get_user_model
- from rest_framework.test import APIClient
- from rest_framework_simplejwt.tokens import RefreshToken
- @pytest.fixture
- def create_user(db):
- # This fixture is responsable for create user.
- first_name = 'Foo'
- last_name = 'Bar'
- email = 'foo@email.com'
- cpf = '17786146806'
- password = 'bar'
- user = get_user_model().objects.create_user(
- first_name=first_name, last_name=last_name, email=email, password=password, cpf=cpf
- )
- return user
- @pytest.fixture
- def api_client(create_user):
- # This fixture is responsable for authorization
- client = APIClient()
- refresh = RefreshToken.for_user(create_user)
- client.credentials(HTTP_AUTHORIZATION=f'Bearer {refresh.access_token}')
- return client
- # app/tests/test_user.py
- from django.urls import reverse
- from rest_framework import status
- from conftest import get_user_model, pytest
- def test_count_user(create_user):
- assert get_user_model().objects.count() == 1
- def test_get_first_name(create_user):
- assert get_user_model().objects.first().first_name == 'Foo'
- def test_get_last_name(create_user):
- assert get_user_model().objects.first().last_name == 'Bar'
- def test_get_email(create_user):
- assert get_user_model().objects.first().email == 'foo@email.com'
- def test_get_cpf(create_user):
- assert get_user_model().objects.first().cpf == '17786146806'
- Obs.: Esses 5 primeiros passam (success)
- ================================================================================================================
- Obs.: Daqui pra baixo falha:
- def test_user_create(api_client):
- resp = api_client.post(
- '/dj-rest-auth/registration/',
- data={
- 'first_name': 'Fulano',
- 'last_name': 'de Tal',
- 'email': 'fulano@email.com',
- 'cpf': '17786146806',
- 'password1': 'teste@123',
- 'password2': 'teste@123',
- },
- format='json',
- )
- assert resp.status_code == status.HTTP_201_CREATED
- @pytest.mark.django_db
- @pytest.mark.parametrize(
- 'email, password, status_code',
- [
- ('', '', status.HTTP_400_BAD_REQUEST),
- ('', 'bar', status.HTTP_400_BAD_REQUEST),
- ('foo@email.com', '', status.HTTP_400_BAD_REQUEST),
- ('foo@email.com', 1, status.HTTP_401_UNAUTHORIZED),
- ('foo@email.com', 'bar', status.HTTP_200_OK),
- ],
- )
- def test_login_data_validation(email, password, status_code, api_client):
- url = reverse('dj-rest-auth:login')
- data = {'email': email, 'password': password}
- response = api_client.post(url, data=data)
- assert response.status_code == status_code
- ================================================================================================================
- Erro:
- > raise NoReverseMatch("%s is not a registered namespace" % key)
- E django.urls.exceptions.NoReverseMatch: 'dj-rest-auth' is not a registered namespace
- .venv/lib/python3.9/site-packages/django/urls/base.py:83: NoReverseMatch
- ============================================ short test summary info =============================================
- FAILED billapp/accounts/tests/test_user.py::test_user_create - django.db.utils.IntegrityError: UNIQUE constrain...
- FAILED billapp/accounts/tests/test_user.py::test_login_data_validation[--400] - django.urls.exceptions.NoRevers...
- FAILED billapp/accounts/tests/test_user.py::test_login_data_validation[-bar-400] - django.urls.exceptions.NoRev...
- FAILED billapp/accounts/tests/test_user.py::test_login_data_validation[foo@email.com--400] - django.urls.except...
- FAILED billapp/accounts/tests/test_user.py::test_login_data_validation[foo@email.com-1-401] - django.urls.excep...
- FAILED billapp/accounts/tests/test_user.py::test_login_data_validation[foo@email.com-bar-200] - django.urls.exc...
- ========================================== 6 failed, 5 passed in 8.57s ===========================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement