feat: added endpoints: auth, pofile, account, keyring
This commit is contained in:
@@ -1,4 +1,12 @@
|
||||
list_of_routes = []
|
||||
from api.endpoints.auth import api_router as auth_router
|
||||
from api.endpoints.pofile import api_router as pofile_router
|
||||
from api.endpoints.account import api_router as account_router
|
||||
from api.endpoints.keyring import api_router as keyring_router
|
||||
list_of_routes = [
|
||||
auth_router,
|
||||
pofile_router,
|
||||
account_router,
|
||||
keyring_router]
|
||||
|
||||
__all__ = [
|
||||
"list_of_routes",
|
||||
|
145
api/api/endpoints/account.py
Normal file
145
api/api/endpoints/account.py
Normal file
@@ -0,0 +1,145 @@
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Body,
|
||||
Depends,
|
||||
Form,
|
||||
HTTPException,
|
||||
Request,
|
||||
Response,
|
||||
status,
|
||||
)
|
||||
|
||||
|
||||
from fastapi_jwt_auth import AuthJWT
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection
|
||||
|
||||
from api.db.connection.session import get_connection_dep
|
||||
|
||||
from api.db.logic.account import get_user_id, put_user_id, post_add_user,get_user_login
|
||||
|
||||
from api.schemas.account.account import Role,Status
|
||||
from api.schemas.endpoints.account import UserUpdate
|
||||
|
||||
from api.services.access_token_validadtion import AccessTokenValidadtion
|
||||
from api.services.user_role_validation import db_user_role_validation
|
||||
from api.services.update_data_validation import put_user_data_validator
|
||||
|
||||
api_router = APIRouter(
|
||||
prefix="/account",
|
||||
tags=["User accountModel"],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@api_router.get("/{user_id}")
|
||||
async def get_account(user_id: int,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()):
|
||||
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@api_router.post("/{user_id}")
|
||||
async def post_account(
|
||||
user_id: int,
|
||||
user: UserUpdate,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
user_validation = await get_user_id(connection, user_id)
|
||||
|
||||
if user_validation is None:
|
||||
|
||||
user_new = await post_add_user(connection,user,user_id,authorize_user.id)
|
||||
return user_new
|
||||
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="An account with this information already exists.")
|
||||
|
||||
|
||||
|
||||
|
||||
@api_router.put("/{user_id}")
|
||||
async def put_account(
|
||||
user_id: int,
|
||||
user_update: UserUpdate,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found")
|
||||
|
||||
|
||||
update_values = put_user_data_validator(user_update,user)
|
||||
|
||||
if update_values is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
await put_user_id(connection, update_values, user)
|
||||
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
|
||||
return user
|
||||
|
||||
@api_router.delete("/{user_id}")
|
||||
async def delete_account(
|
||||
user_id: int,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found")
|
||||
|
||||
|
||||
user_update = UserUpdate(status=Status.DELETED.value)
|
||||
|
||||
update_values = put_user_id_validator(user_update,user)
|
||||
|
||||
if update_values is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
await put_user_id(connection, update_values, user)
|
||||
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
|
||||
return user
|
143
api/api/endpoints/auth.py
Normal file
143
api/api/endpoints/auth.py
Normal file
@@ -0,0 +1,143 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Body,
|
||||
Depends,
|
||||
Form,
|
||||
HTTPException,
|
||||
Request,
|
||||
Response,
|
||||
status,
|
||||
)
|
||||
|
||||
|
||||
from loguru import logger
|
||||
from pydantic.main import BaseModel
|
||||
from fastapi_jwt_auth import AuthJWT
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection
|
||||
|
||||
from api.config import get_settings
|
||||
from api.db.connection.session import get_connection_dep
|
||||
from api.services.auth import authenticate_user
|
||||
|
||||
from api.db.logic.auth import add_new_refresh_token,upgrade_old_refresh_token
|
||||
|
||||
from api.schemas.endpoints.auth import Auth
|
||||
|
||||
api_router = APIRouter(
|
||||
prefix="/auth",
|
||||
tags=["User auth"],
|
||||
)
|
||||
|
||||
|
||||
class Settings(BaseModel):
|
||||
authjwt_secret_key: str = get_settings().SECRET_KEY
|
||||
# Configure application to store and get JWT from cookies
|
||||
authjwt_token_location: set = {"headers", "cookies"}
|
||||
authjwt_cookie_domain: str = get_settings().DOMAIN
|
||||
|
||||
# Only allow JWT cookies to be sent over https
|
||||
authjwt_cookie_secure: bool = get_settings().ENV == "prod"
|
||||
# Enable csrf double submit protection. default is True
|
||||
authjwt_cookie_csrf_protect: bool = False
|
||||
authjwt_cookie_samesite: str = "lax"
|
||||
|
||||
|
||||
@AuthJWT.load_config
|
||||
def get_config():
|
||||
return Settings()
|
||||
|
||||
|
||||
@api_router.post("/")
|
||||
async def login_for_access_token(
|
||||
user: Auth,
|
||||
response: Response,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends(),
|
||||
):
|
||||
|
||||
"""Авторизирует, выставляет токены в куки."""
|
||||
|
||||
user = await authenticate_user(connection, user.login, user.password)
|
||||
|
||||
print("login_for_access_token", user)
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
# headers={"WWW-Authenticate": "Bearer"},
|
||||
|
||||
)
|
||||
access_token_expires = timedelta(
|
||||
minutes=get_settings().ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
refresh_token_expires = timedelta(
|
||||
days=get_settings().REFRESH_TOKEN_EXPIRE_DAYS
|
||||
)
|
||||
|
||||
logger.debug(f"refresh_token_expires {refresh_token_expires}")
|
||||
|
||||
access_token = Authorize.create_access_token(
|
||||
subject=user.login, expires_time=access_token_expires
|
||||
)
|
||||
refresh_token = Authorize.create_refresh_token(
|
||||
subject=user.login, expires_time=refresh_token_expires
|
||||
)
|
||||
|
||||
refresh_token_expires_time = datetime.now(timezone.utc) + refresh_token_expires
|
||||
|
||||
await upgrade_old_refresh_token(connection,user)
|
||||
|
||||
await add_new_refresh_token(connection,refresh_token,refresh_token_expires_time,user)
|
||||
|
||||
Authorize.set_refresh_cookies(refresh_token)
|
||||
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
# "access_token_expires": access_token_expires_time,
|
||||
# "refresh_token": refresh_token,
|
||||
# "refresh_token_expires": refresh_token_expires_time
|
||||
}
|
||||
|
||||
|
||||
@api_router.post("/refresh")
|
||||
def refresh(
|
||||
request: Request,
|
||||
Authorize: AuthJWT = Depends()):
|
||||
"""Обновляет access токен."""
|
||||
|
||||
refresh_token = request.cookies.get("refresh_token_cookie")
|
||||
print("Refresh Token:", refresh_token)
|
||||
|
||||
|
||||
if not refresh_token:
|
||||
raise HTTPException(status_code=401, detail="Refresh token is missing")
|
||||
|
||||
try:
|
||||
|
||||
Authorize.jwt_refresh_token_required()
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid refresh token",
|
||||
)
|
||||
|
||||
|
||||
current_user = Authorize.get_jwt_subject()
|
||||
|
||||
access_token_expires = timedelta(minutes=get_settings().ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
new_access_token = Authorize.create_access_token(
|
||||
subject=current_user, expires_time=access_token_expires
|
||||
)
|
||||
|
||||
Authorize.set_access_cookies(new_access_token)
|
||||
|
||||
return {"msg": "The token has been refresh"}
|
150
api/api/endpoints/keyring.py
Normal file
150
api/api/endpoints/keyring.py
Normal file
@@ -0,0 +1,150 @@
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Body,
|
||||
Depends,
|
||||
Form,
|
||||
HTTPException,
|
||||
Request,
|
||||
Response,
|
||||
status,
|
||||
)
|
||||
|
||||
from fastapi_jwt_auth import AuthJWT
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection
|
||||
|
||||
from api.db.connection.session import get_connection_dep
|
||||
|
||||
from api.db.logic.account import get_user_login
|
||||
from api.db.logic.keyring import get_key_id,post_add_key,put_key_id
|
||||
|
||||
|
||||
from api.schemas.account.account import Role,Status
|
||||
from api.schemas.endpoints.account_keyring import AccountKeyringUpdate
|
||||
|
||||
from api.services.access_token_validadtion import AccessTokenValidadtion
|
||||
from api.services.user_role_validation import db_user_role_validation
|
||||
from api.services.update_data_validation import put_key_data_validator
|
||||
|
||||
|
||||
api_router = APIRouter(
|
||||
prefix="/keyring",
|
||||
tags=["User KeyringModel"],
|
||||
)
|
||||
|
||||
|
||||
@api_router.get("/{user_id}/{key_id}")
|
||||
async def get_keyring(
|
||||
key_id: str,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()):
|
||||
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
|
||||
if keyring is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Key not found")
|
||||
|
||||
return keyring
|
||||
|
||||
|
||||
@api_router.post("/{user_id}/{key_id}")
|
||||
async def post_keyring(
|
||||
user_id: int,
|
||||
key_id: str,
|
||||
key: AccountKeyringUpdate,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
|
||||
if keyring is None:
|
||||
print(key.key_type)
|
||||
user_new = await post_add_key(connection,key, key_id, )
|
||||
return user_new
|
||||
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="An keyring with this information already exists.")
|
||||
|
||||
|
||||
|
||||
@api_router.put("/{user_id}/{key_id}")
|
||||
async def put_keyring(
|
||||
user_id: int,
|
||||
key_id: str,
|
||||
keyring_update: AccountKeyringUpdate,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
if keyring is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="keyring not found")
|
||||
|
||||
|
||||
update_values = put_key_data_validator(keyring_update,keyring)
|
||||
|
||||
if update_values is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
await put_key_id(connection, update_values, keyring)
|
||||
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
|
||||
return keyring
|
||||
|
||||
@api_router.delete("/{user_id}/{key_id}")
|
||||
async def delete_keyring(
|
||||
user_id: int,
|
||||
key_id: str,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await db_user_role_validation(connection, current_user)
|
||||
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
if keyring is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="keyring not found")
|
||||
|
||||
|
||||
keyring_update = AccountKeyringUpdate(status=Status.DELETED.value)
|
||||
|
||||
update_values = put_key_validator(keyring_update,keyring)
|
||||
|
||||
if update_values is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
await put_key_id(connection, update_values, keyring)
|
||||
|
||||
|
||||
keyring = await get_key_id(connection, key_id)
|
||||
|
||||
return keyring
|
90
api/api/endpoints/pofile.py
Normal file
90
api/api/endpoints/pofile.py
Normal file
@@ -0,0 +1,90 @@
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Body,
|
||||
Depends,
|
||||
Form,
|
||||
HTTPException,
|
||||
Request,
|
||||
Response,
|
||||
status,
|
||||
)
|
||||
|
||||
from fastapi_jwt_auth import AuthJWT
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection
|
||||
|
||||
from api.db.connection.session import get_connection_dep
|
||||
from api.db.logic.account import get_user_id, put_user_id,get_user_login
|
||||
from api.services.update_data_validation import put_user_data_validator
|
||||
|
||||
from api.schemas.endpoints.account import UserUpdate
|
||||
|
||||
from api.services.access_token_validadtion import AccessTokenValidadtion
|
||||
|
||||
|
||||
api_router = APIRouter(
|
||||
prefix="/pofile",
|
||||
tags=["User accountModel"],
|
||||
)
|
||||
|
||||
|
||||
@api_router.get("/{user_id}")
|
||||
async def get_pofile(user_id: int,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()):
|
||||
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
authorize_user = await get_user_login(connection, current_user)
|
||||
if authorize_user.id != user_id :
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@api_router.put("/{user_id}")
|
||||
async def put_pofile(
|
||||
user_id: int,
|
||||
user_updata: UserUpdate,
|
||||
connection: AsyncConnection = Depends(get_connection_dep),
|
||||
Authorize: AuthJWT = Depends()
|
||||
):
|
||||
|
||||
current_user = AccessTokenValidadtion(Authorize)
|
||||
|
||||
|
||||
authorize_user = await get_user_login(connection, current_user)
|
||||
if authorize_user.id != user_id :
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found")
|
||||
|
||||
|
||||
update_values = put_user_data_validator(user_updata,user)
|
||||
|
||||
if update_values is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="The provided data already exists in the database")
|
||||
|
||||
await put_user_id(connection, update_values, user)
|
||||
|
||||
user = await get_user_id(connection, user_id)
|
||||
|
||||
return user
|
Reference in New Issue
Block a user