Skip to content

Commit

Permalink
jwt auth
Browse files Browse the repository at this point in the history
  • Loading branch information
fivan999 committed Feb 22, 2024
1 parent 1415be1 commit 6ce5bab
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 9 deletions.
14 changes: 12 additions & 2 deletions backend/cfehome/cfehome/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
'algoliasearch_django',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt',
'corsheaders',
'products.apps.ProductsConfig',
'users.apps.UsersConfig',
'search.apps.SearchConfig',
Expand All @@ -40,6 +42,7 @@
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
Expand Down Expand Up @@ -116,8 +119,7 @@

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
Expand All @@ -131,3 +133,11 @@
'APPLICATION_ID': os.getenv('ALGOLIA_APPLICATION_ID', 'app_id'),
'API_KEY': os.getenv('ALGOLIA_API_KEY', 'api_key'),
}

CORS_ALLOWED_ORIGINS = []
if DEBUG:
CORS_ALLOWED_ORIGINS = [
'http://localhost:8111',
'https://localhost:8111',
]
CORS_URLS_REGEX = r"^/api/.*$"
20 changes: 18 additions & 2 deletions backend/cfehome/cfehome/test_settings.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import pathlib


Expand All @@ -18,12 +19,15 @@
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt',
'corsheaders',
'products.apps.ProductsConfig',
'users.apps.UsersConfig',
'search.apps.SearchConfig',
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
Expand Down Expand Up @@ -98,8 +102,7 @@

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
Expand All @@ -108,3 +111,16 @@
'LimitOffsetPagination',
'PAGE_SIZE': 10,
}

ALGOLIA = {
'APPLICATION_ID': os.getenv('ALGOLIA_APPLICATION_ID', 'app_id'),
'API_KEY': os.getenv('ALGOLIA_API_KEY', 'api_key'),
}

CORS_ALLOWED_ORIGINS = []
if DEBUG:
CORS_ALLOWED_ORIGINS = [
'http://localhost:8111',
'https://localhost:8111',
]
CORS_URLS_REGEX = r"^/api/.*$"
18 changes: 14 additions & 4 deletions backend/cfehome/users/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import rest_framework.authtoken.views
import rest_framework_simplejwt.views

import django.urls

Expand All @@ -7,8 +7,18 @@

urlpatterns = [
django.urls.path(
'login/',
rest_framework.authtoken.views.obtain_auth_token,
name='login',
'token/',
rest_framework_simplejwt.views.TokenObtainPairView.as_view(),
name='token_obtain',
),
django.urls.path(
'token/refresh/',
rest_framework_simplejwt.views.TokenRefreshView.as_view(),
name='token_refresh',
),
django.urls.path(
'token/verify/',
rest_framework_simplejwt.views.TokenVerifyView.as_view(),
name='token_verify',
),
]
107 changes: 107 additions & 0 deletions js_client/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const loginForm = document.getElementById('login-form')
const contentContainer = document.getElementById('content-container')
const searchForm = document.getElementById('search-form')
const baseEndpoint = 'http://localhost:8000/api'
if (loginForm) {
loginForm.addEventListener('submit', handleLogin)
}
if (searchForm){
searchForm.addEventListener('submit', getProductList)
}
console.log(searchForm)

function handleLogin(event) {
event.preventDefault()
const loginEndpoint = `${baseEndpoint}/auth/token/`
let loginFormData = new FormData(loginForm)
let loginObjectData = Object.fromEntries(loginFormData)
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(loginObjectData)
}
fetch(loginEndpoint, options).then(response=>{
return response.json()
}).then(authData => {
handleAuthData(authData, getProductList)
})
}

function handleAuthData(authData, callback){
localStorage.setItem('access', authData.access)
localStorage.setItem('refresh', authData.refresh)
if (callback){
callback()
}
}

function isTokenValid(jsonData) {
if (jsonData.code && jsonData.code === 'token_not_valid'){
alert('Войдите в аккаунт снова')
return false
} return true
}

function validateJWTToken(){
const endpoint = `${baseEndpoint}/auth/token/verify/`
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
token: localStorage.getItem('access')
})
}
fetch(endpoint, options)
.then(response=>response.json())
.then(x => {
isTokenValid(x)
})
}

function getFetchOptions(method, body){
return {
method: method === null ? 'GET': method,
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('access')}`
},
body: body === null ? null: body
}
}

function getProductList(event){
let endpoint = `${baseEndpoint}/products/`
if (event){
event.preventDefault()
let searchFormData = new FormData(searchForm)
let searchData = Object.fromEntries(searchFormData)
searchParams = new URLSearchParams(searchData)
endpoint = `${baseEndpoint}/products/?${searchParams}`
}
const options = {
method: 'GET',
headers: {
'content-type': 'application/json',
}
}
console.log(endpoint)
fetch(endpoint, options)
.then(response=>{
return response.json()
})
.then(data=>{
if (isTokenValid(data)) {
writeInContentContainer(data)
}
})
}

function writeInContentContainer(data) {
if (contentContainer) {
contentContainer.innerHTML = '<pre>' + JSON.stringify(data, null, 4) + '</pre>'
}
}
26 changes: 26 additions & 0 deletions js_client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta name="msapplication-TileColor" content="#da532c" />
<meta charset="utf-8" />
</head>
<body>
<form id="login-form">
<input type="text" name="username" placeholder="Имя пользователя" />
<input type="password" name="password" placeholder="Пароль" />
<input type="submit" value="Войти" />
</form>

<form id="search-form">
<input type="text" name="query" placeholder="Введите запрос" />
<input type="text" name="user" placeholder="Создатель товара" />
<input type="submit" value="Поиск" />
</form>

<div id="content-container">

</div>

<script src="client.js"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ django-cors-headers==4.3.1
djangorestframework==3.14.0
python-dotenv==1.0.1
django_debug_toolbar==4.2.0
algoliasearch-django==3.0.0
algoliasearch-django==3.0.0
djangorestframework-simplejwt==5.3.1

0 comments on commit 6ce5bab

Please sign in to comment.