Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement authentication #2

Merged
merged 10 commits into from
Mar 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,13 @@ SECRET_KEY=secret

# database connection url string
DATABASE_URL=postgresql://username:password@host:port/database

# Google OAuth2 information
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY=
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET=

# Client domain
CLIENT_URL=http://localhost:3000

CORS_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
SOCIAL_AUTH_ALLOWED_REDIRECT_URIS='comma-separated-list-of-allowed-redirect-uris-for-social authentication'
5 changes: 5 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@ jobs:
runs-on: ubuntu-latest
needs: check-hooks
env:
CORS_ALLOWED_ORIGINS: http://localhost:3000
DATABASE_URL: postgresql://devuser:changeme@db:5432/devdb
DEBUG: True
SECRET_KEY: change_me
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY: ${{ secrets.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY }}
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET: ${{ secrets.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET }}
SOCIAL_AUTH_ALLOWED_REDIRECT_URIS: http://127.0.0.1:3000/login

steps:
- name: Login to Docker Hub
Expand Down
126 changes: 125 additions & 1 deletion b2b/b2b/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

import os
from datetime import timedelta
from typing import List

import environ
Expand Down Expand Up @@ -46,11 +47,21 @@
"django.contrib.staticfiles",
# Local apps
"core.apps.CoreConfig",
"user.apps.UserConfig",
# Third-party apps
"corsheaders",
"djoser",
"rest_framework",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
"social_django",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"social_django.middleware.SocialAuthExceptionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
Expand All @@ -71,6 +82,8 @@
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"social_django.context_processors.backends",
"social_django.context_processors.login_redirect",
],
},
},
Expand Down Expand Up @@ -131,4 +144,115 @@

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTH_USER_MODEL = "core.User"
AUTH_USER_MODEL = "user.User"

if DEBUG:
# Configure django debug toolbar for development
import socket

INSTALLED_APPS += [
"debug_toolbar",
]
MIDDLEWARE += [
"debug_toolbar.middleware.DebugToolbarMiddleware",
]

INTERNAL_IPS = [
"127.0.0.1",
"0.0.0.0:8000",
]

hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + [
"127.0.0.1",
"10.0.2.2",
"0.0.0.0:8000",
]

# Support static files in development
STATIC_ROOT = "/vol/web/static"

STATIC_ROOT = os.path.join(BASE_DIR, "static")

CORS_ALLOWED_ORIGINS: List[str] = list(
filter(None, env("CORS_ALLOWED_ORIGINS").split(","))
)
CORS_ALLOW_CREDENTIALS = True

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
}

SIMPLE_JWT = {
"AUTH_HEADER_TYPES": ("JWT",),
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
}
if DEBUG:
SIMPLE_JWT.update({"ACCESS_TOKEN_LIFETIME": timedelta(days=30)})


DOMAIN = env("CLIENT_URL")
SITE_NAME = "b2b"
DJOSER = {
"PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}",
"USERNAME_RESET_CONFIRM_URL": "username/reset/confirm/{uid}/{token}",
"ACTIVATION_URL": "activate/{uid}/{token}",
"SEND_ACTIVATION_EMAIL": True,
"SEND_CONFIRMATION_EMAIL": True,
"PASSWORD_CHANGED_EMAIL_CONFIRMATION": True,
"USERNAME_CHANGED_EMAIL_CONFIRMATION": True,
"SET_USERNAME_RETYPE": True,
"SET_PASSWORD_RETYPE": True,
"USER_CREATE_PASSWORD_RETYPE": True,
"USERNAME_RESET_CONFIRM_RETYPE": True,
"PASSWORD_RESET_CONFIRM_RETYPE": True,
"TOKEN_MODEL": None,
"SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy",
"SERIALIZERS": {},
}
DJOSER["SOCIAL_AUTH_ALLOWED_REDIRECT_URIS"] = list(
filter(None, env("SOCIAL_AUTH_ALLOWED_REDIRECT_URIS").split(","))
)

AUTHENTICATION_BACKENDS = (
"social_core.backends.google.GoogleOAuth2",
"django.contrib.auth.backends.ModelBackend",
)

SOCIAL_AUTH_PIPELINE = (
"social_core.pipeline.social_auth.social_details",
"social_core.pipeline.social_auth.social_uid",
"social_core.pipeline.social_auth.auth_allowed",
"social_core.pipeline.social_auth.social_user",
"social_core.pipeline.user.get_username",
"social_core.pipeline.social_auth.associate_by_email",
"social_core.pipeline.user.create_user",
"social_core.pipeline.social_auth.associate_user",
"social_core.pipeline.social_auth.load_extra_data",
"social_core.pipeline.user.user_details",
)
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY")
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET")
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
"https://www.googleapis.com/auth/userinfo.email",
]
SOCIAL_AUTH_PIPELINE = (
"social_core.pipeline.social_auth.social_details",
"social_core.pipeline.social_auth.social_uid",
"social_core.pipeline.social_auth.auth_allowed",
"social_core.pipeline.social_auth.social_user",
"social_core.pipeline.user.get_username",
"social_core.pipeline.social_auth.associate_by_email",
"social_core.pipeline.user.create_user",
"social_core.pipeline.social_auth.associate_user",
"social_core.pipeline.social_auth.load_extra_data",
"social_core.pipeline.user.user_details",
)

EMAIL_HOST = env("EMAIL_HOST")
EMAIL_HOST_USER = env("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD")
EMAIL_PORT = env("EMAIL_PORT")
DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL")
9 changes: 8 additions & 1 deletion b2b/b2b/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,16 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.urls import include, path

urlpatterns = [
path("admin/", admin.site.urls),
path("user/", include("user.urls")),
]

if settings.DEBUG:
urlpatterns += [
path(r"__debug__/", include("debug_toolbar.urls")),
]
9 changes: 9 additions & 0 deletions b2b/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Global project fixtures."""
import pytest
from rest_framework.test import APIClient


@pytest.fixture
def api_client():
"""Return API client."""
return APIClient()
8 changes: 0 additions & 8 deletions b2b/core/models.py

This file was deleted.

3 changes: 3 additions & 0 deletions b2b/djoser/.codacy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exclude_paths:
- "docs/**"
- "testproject/**"
1 change: 1 addition & 0 deletions b2b/djoser/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "2.2.0"
12 changes: 12 additions & 0 deletions b2b/djoser/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from djoser.conf import settings

__all__ = ["settings"]


def get_user_email(user):
email_field_name = get_user_email_field_name(user)
return getattr(user, email_field_name, None)


def get_user_email_field_name(user):
return user.get_email_field_name()
Loading