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

feat(core): Update settings, routes, and auth with JWT authentication #5

Merged
merged 1 commit into from
Nov 17, 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
1 change: 1 addition & 0 deletions apidemo/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@
# For Controller Schemas
# FOR OBTAIN PAIR
'TOKEN_OBTAIN_PAIR_INPUT_SCHEMA': "core.auth.MyTokenObtainPairInputSchema",
'TOKEN_OBTAIN_PAIR_REFRESH_INPUT_SCHEMA': "core.auth.MyTokenRefreshInputSchema",
# 'TOKEN_OBTAIN_PAIR_REFRESH_INPUT_SCHEMA': "ninja_jwt.schema.TokenRefreshInputSchema",
# # FOR SLIDING TOKEN
# 'TOKEN_OBTAIN_SLIDING_INPUT_SCHEMA': "ninja_jwt.schema.TokenObtainSlidingInputSchema",
Expand Down
31 changes: 25 additions & 6 deletions apidemo/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,40 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from ninja import File, NinjaAPI
from ninja_extra import exceptions as extra_exceptions
from ninja_jwt.routers.obtain import obtain_pair_router

from employee.views import router as employee_router

api_v1 = NinjaAPI(version="1.0.0")

from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI, File
api_v1.add_router("/employee/", employee_router)
api_v1.add_router("/token", tags=["Auth"], router=obtain_pair_router)


def obtain_token_exception_handler(request, exc):
headers = {}

if isinstance(exc, extra_exceptions.APIException):
data = {
"message": exc.detail.get("detail", str(exc)),
"success": False,
"data": None,
}
else:
data = {"message": exc.detail, "success": False, "data": None}

response = api_v1.create_response(request, data, status=exc.status_code)
for k, v in headers.items():
response.setdefault(k, v)

api_v1 = NinjaAPI(version='1.0.0')
return response

api_v1.add_router('/employee/', employee_router)
api_v1.add_router('/token', tags=['Auth'], router=obtain_pair_router)

api_v1.exception_handler(extra_exceptions.APIException)(obtain_token_exception_handler)

urlpatterns = [
path("admin/", admin.site.urls),
Expand Down
39 changes: 33 additions & 6 deletions core/auth.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
# !/usr/bin/python3
# -*- coding: utf-8 -*-
from typing import Dict, Type
from typing import Dict, Optional, Type, Union

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from ninja import Schema
from ninja_jwt.schema import TokenObtainInputSchemaBase
from ninja_jwt.schema import (
TokenObtainInputSchemaBase,
TokenRefreshInputSchema,
TokenRefreshOutputSchema,
)
from ninja_jwt.tokens import RefreshToken

from core.schemas import StandResponse
Expand All @@ -22,6 +26,25 @@ class MyTokenObtainPairOutSchema(Schema):
user: UserSchema


class MyRefreshTokenOutSchema(TokenRefreshOutputSchema):
def dict(
self,
*,
include: Optional[Union["AbstractSetIntStr", "MappingIntStrAny"]] = None,
exclude: Optional[Union["AbstractSetIntStr", "MappingIntStrAny"]] = None,
by_alias: bool = False,
skip_defaults: Optional[bool] = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
) -> "DictStrAny":
return {
"data": {"access": self.access, "refresh": self.refresh},
"message": None,
"success": True,
}


class MyTokenObtainPairInputSchema(TokenObtainInputSchemaBase):
@classmethod
def get_response_schema(cls) -> Type[Schema]:
Expand All @@ -35,10 +58,14 @@ def get_token(cls, user) -> Dict:
refresh = RefreshToken.for_user(user)
values["refresh"] = str(refresh)
values["access"] = str(refresh.access_token)
values.update(
user=UserSchema.from_orm(user)
)
return {'data': values}
values.update(user=UserSchema.from_orm(user))
return {"data": values}


class MyTokenRefreshInputSchema(TokenRefreshInputSchema):
@classmethod
def get_response_schema(cls) -> Type[Schema]:
return MyRefreshTokenOutSchema


class CustomAuthBackend(ModelBackend):
Expand Down
Loading