- Edited login page js

- Added get user or None functions
This commit is contained in:
Aykhan 2023-09-13 02:32:35 +04:00
parent 006f2af15b
commit acea33c0b2
5 changed files with 100 additions and 41 deletions

View File

@ -13,6 +13,7 @@
<div class="container" style="margin-top: 10rem;"> <div class="container" style="margin-top: 10rem;">
<div class="row"> <div class="row">
<div class="col-md-10 col-lg-4 mx-auto"> <div class="col-md-10 col-lg-4 mx-auto">
<p id="responseError"></p>
<form id="loginForm"> <form id="loginForm">
<div class="form-outline mb-4"> <div class="form-outline mb-4">
<input type="email" id="form2Example1" name="email" class="form-control" /> <input type="email" id="form2Example1" name="email" class="form-control" />
@ -42,13 +43,26 @@
method: 'POST', method: 'POST',
body: formData, body: formData,
}) })
.then(response => response.json()) .then(response => {
if (response.status === 200) {
console.log(response.json)
return response.json();
} else if (response.status === 400) {
throw new Error('Email or password incorrect.');
}
else {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
})
.then(data => { .then(data => {
console.log(data)
const accessToken = data.access_token; const accessToken = data.access_token;
localStorage.setItem('accessToken', accessToken) var now = new Date();
now.setDate(now.getDate() + 30);
document.cookie = `access_token=${accessToken};expires=${now.toUTCString()};path=/`;
}) })
.catch(error => { .catch(error => {
console.error('Login error:', error); document.getElementById('responseError').innerHTML = error.message;
}); });
} }
@ -58,18 +72,3 @@
</body> </body>
</html> </html>
<!-- <!DOCTYPE html>
<html>
<head>
<title>Login Example</title>
</head>
<body>
<form id="loginForm">
<input type="text" name="email" placeholder="email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</body>
</html> -->

View File

@ -29,14 +29,16 @@
</div> </div>
<hr> <hr>
{% endfor %} {% endfor %}
<div class="clearfix"> {% if posts|length > 5 %}
<button class="btn btn-primary float-end" type="button" style="margin-left: 2rem; background: rgb(0, 133, 161);"> <div class="clearfix">
<a href="/blog?skip={{skip}}" style="text-decoration: none; color: inherit;">Older Posts&nbsp;</a> <button class="btn btn-primary float-end" type="button" style="margin-left: 2rem; background: rgb(0, 133, 161);">
</button> <a href="/blog?skip={{skip}}" style="text-decoration: none; color: inherit;">Older Posts&nbsp;</a>
<button class="btn btn-primary float-end" type="button" style="background: rgb(0, 133, 161);"> </button>
<a href="/blog?skip={{skip}}&new=true" style="text-decoration: none; color: inherit;">&nbsp;Newer Posts</a> <button class="btn btn-primary float-end" type="button" style="background: rgb(0, 133, 161);">
</button> <a href="/blog?skip={{skip}}&new=true" style="text-decoration: none; color: inherit;">&nbsp;Newer Posts</a>
</div> </button>
</div>
{% endif %}
</div> </div>
</div> </div>
</div> </div>

View File

@ -46,15 +46,19 @@ def get_db() -> Generator:
async def get_async_db() -> Generator: async def get_async_db() -> Generator:
async with AsyncSessionLocal() as async_db: async with AsyncSessionLocal() as async_db:
yield await async_db yield async_db
async def get_access_token_from_cookie(access_token: Annotated[str, Cookie()]): async def get_access_token_from_cookie_or_die(access_token: Annotated[str, Cookie()]) -> str:
return access_token return access_token
async def get_current_user( async def get_access_token_from_cookie_or_none(access_token: Annotated[str, Cookie()] = None) -> str | None:
db: AsyncSession = Depends(get_async_db), token: str = Depends(get_access_token_from_cookie) return access_token
async def get_current_user_or_die(
db: AsyncSession = Depends(get_async_db), token: str = Depends(get_access_token_from_cookie_or_die)
) -> UserModel: ) -> UserModel:
try: try:
@ -79,8 +83,33 @@ async def get_current_user(
return user return user
async def get_current_active_user( async def get_current_user_or_none(
current_user: UserModel = Depends(get_current_user), db: AsyncSession = Depends(get_async_db), token: str | None = Depends(get_access_token_from_cookie_or_none)
) -> UserModel | None:
if token is None: return None
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
token_data = schemas.JWTTokenPayload(**payload)
except (jwt.JWTError, ValidationError):
return None
if token_data.sub is None:
return None
user = await crud.user.get_by_email(db, email=token_data.sub)
if user is None:
return None
return user
async def get_current_active_user_or_die(
current_user: UserModel = Depends(get_current_user_or_die),
) -> UserModel: ) -> UserModel:
if current_user.is_active is False: if current_user.is_active is False:
@ -88,8 +117,19 @@ async def get_current_active_user(
return current_user return current_user
async def get_current_active_superuser( async def get_current_active_user_or_none(
current_user: UserModel = Depends(get_current_active_user), current_user: UserModel | None = Depends(get_current_user_or_none),
) -> UserModel | None:
if current_user is None: return None
if current_user.is_active is False:
return None
return current_user
async def get_current_active_superuser_or_die(
current_user: UserModel = Depends(get_current_active_user_or_die),
) -> UserModel: ) -> UserModel:
if current_user.is_superuser is False: if current_user.is_superuser is False:
@ -99,6 +139,17 @@ async def get_current_active_superuser(
return current_user return current_user
async def get_current_active_superuser_or_none(
current_user: UserModel | None = Depends(get_current_active_user_or_none),
) -> UserModel | None:
if current_user is None: return None
if current_user.is_superuser is False:
return None
return current_user
async def handle_image(image: UploadFile = File(...)) -> str: async def handle_image(image: UploadFile = File(...)) -> str:
try: try:
pil_image = Image.open(io.BytesIO(image.file.read())) pil_image = Image.open(io.BytesIO(image.file.read()))
@ -115,8 +166,8 @@ async def handle_image(image: UploadFile = File(...)) -> str:
await save_image( await save_image(
image = pil_image, image = pil_image,
image_path = settings.MEDIA_PATH / image_path = settings.MEDIA_PATH /
settings.FILE_FOLDERS['post_images'] / settings.FILE_FOLDERS['post_images'] /
unique_image_name unique_image_name
) )
except Exception as e: except Exception as e:

View File

@ -20,7 +20,11 @@ from app.core.config import settings
from app.schemas import ListPostInTemplate from app.schemas import ListPostInTemplate
from app.schemas.main import SendEmail from app.schemas.main import SendEmail
from app.utils.email_utils import send_email_notification from app.utils.email_utils import send_email_notification
from app.views.depends import get_async_db from app.models.user import User as UserModel
from app.views.depends import (
get_async_db,
get_current_active_superuser_or_none
)
router = APIRouter() router = APIRouter()
@ -65,6 +69,7 @@ async def send_email(
async def blog( async def blog(
request: Request, request: Request,
db: AsyncSession = Depends(get_async_db), db: AsyncSession = Depends(get_async_db),
user: UserModel | None = Depends(get_current_active_superuser_or_none),
skip: Annotated[int, Query(gt=-1)] = 0, skip: Annotated[int, Query(gt=-1)] = 0,
new: bool = False new: bool = False
): ):
@ -86,6 +91,7 @@ async def blog(
{ {
'request': request, 'request': request,
'posts': posts, 'posts': posts,
'skip': skip 'skip': skip,
'user': user
} }
) )

View File

@ -21,7 +21,8 @@ from app.schemas import JWTToken, LoginForm
from app.core.config import settings from app.core.config import settings
from app.views.depends import ( from app.views.depends import (
get_async_db, get_async_db,
get_current_active_superuser get_current_active_superuser_or_die,
get_current_active_superuser_or_none
) )
@ -30,7 +31,7 @@ router = APIRouter()
templates = Jinja2Templates(directory=settings.APP_PATH / 'templates') templates = Jinja2Templates(directory=settings.APP_PATH / 'templates')
@router.get(f"/{settings.SECRET_KEY[-10:]}", response_class=HTMLResponse) @router.get(f"/{settings.SECRET_KEY[-10:]}", response_class=HTMLResponse, include_in_schema=False)
async def login( async def login(
request: Request request: Request
): ):
@ -44,7 +45,7 @@ async def login(
) )
@router.post(f"/{settings.SECRET_KEY[-10:]}", response_model=JWTToken) @router.post(f"/{settings.SECRET_KEY[-10:]}", response_model=JWTToken, include_in_schema=False)
async def login( async def login(
db: AsyncSession = Depends(get_async_db), db: AsyncSession = Depends(get_async_db),
form_data: LoginForm = Depends() form_data: LoginForm = Depends()