from fastapi.security import OAuth2PasswordRequestForm from fastapi import Depends from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse from pony.orm import db_session from app.utils.pydantic_security import * from app.settings.config import cfg from app.dependencies import * from app.db import models as m from app.utils.utils_of_security import generate_security, basic_login, scopes_to_db from app.utils.jinja2_utils import _roles_to_home_urls SECRET_KEY = cfg.get('keys', "user") ACCESS_TOKEN_TIME = int(cfg.get('keys', "user_time")) token_path = "user_token" # user_oauth2_scheme = OAuth2PasswordBearer(tokenUrl=token_path) [get_user, authenticate_user, get_current_user, create_user_access_token] = generate_security(m.User) user = APIRouter( tags=["user"], responses={404: { "description": "Not found" }}, # dependencies=[Depends(open_db_session)] ) @user.post('/' + token_path, response_model=Token) @db_session
def old_connect_with_db(db_path=DB_PATH, deep=0, db_l=db): """ Создает соединение с БД для Pony ORM версии 0.73 :param db_path: путь к БД :param deep: глубина рекурсии :param db_l: объект БД :return: """ from os.path import isfile, split, join from os import remove, rename from sys import exit from time import ctime from shutil import copy as shutil_copy if deep > 5: print( 'в коннекте с базой данных наблюдается большая рекурсия, значит что-то идет не так' ) exit() if not isfile(db_path): db_l.bind(provider=cfg.get("db", "type"), filename=db_path, create_db=True) db_l.generate_mapping(create_tables=True) """ db_l.connect(allow_auto_upgrade=True, create_tables=True, create_db=True, provider=cfg.get("db", "type"), filename=db_path) """ print('create db') else: try: db_l.bind(provider=cfg.get("db", "type"), filename=db_path) db_l.generate_mapping() except Exception as e: print( 'при создании бд произошла какая-то ошибка (видимо, структура БД была изменена)\n', e) print('попытка исправить.....') try: db_l.bind( provider=cfg.get("db", "type"), filename=db_path, create_tables=True, ) db_l.generate_mapping() print('получилось') except Exception as e: print("Создаём бекап а затем удаляем БД") t = ctime().split()[1:] t[0], t[1], t[2] = t[2], t[1], t[0] copy_name = shutil_copy(db_path, DB_BACKUPS) new_name = join( split(copy_name)[0], '_'.join(t).replace(":", "-") + "_" + split(db_path)[1]) rename(copy_name, new_name) print("создан бекап:", new_name) print("Удалена исходная база данных, создаём новую") remove(db_path) print( '\n=========================================\n\n\t\tдля создания новой БД перезапустите код.....' ) print('\n=========================================') exit()
SecurityScopes, ) from app.db import models as m from app.settings.config import cfg from app.utils.pydantic_security import TokenData, HumanInDB, Token, BaseModel from app.pydantic_models.standart_methhods_redefinition import AccessType, AccessMode from app.pydantic_models.gen import db_models as pd_db from app.utils.exceptions import ChildHTTPException as HTTPException from app.utils.responses import RedirectResponseWithBody from app.pydantic_models.response_models import Ajax300Answer, ResponseType from app.utils.html_utils import Alert from app.utils.jinja2_utils import _roles_to_home_urls pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") ALGORITHM = cfg.get('db', "hash_algorithm") SECRET_KEY = cfg.get('keys', "basic") def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def basic_create_access_token(data: dict, expires_delta: Optional[timedelta] = None): """ Создание токена для пользователя """ to_encode = data.copy()
from fastapi.security import OAuth2PasswordRequestForm from fastapi import Depends from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse from pony.orm import db_session from app.utils.pydantic_security import * from app.settings.config import cfg from app.dependencies import * from app.db import models as m from app.utils.utils_of_security import generate_security, basic_login, scopes_to_db from app.utils.jinja2_utils import _roles_to_home_urls SECRET_KEY = cfg.get('keys', "admin") ACCESS_TOKEN_TIME = int(cfg.get('keys', "admin_time")) token_path = "admin_token" # admin_oauth2_scheme = OAuth2PasswordBearer(tokenUrl=token_path) admin = APIRouter( tags=["admin"], responses={404: { "description": "Not found" }}, # dependencies=[Depends(open_db_session)] ) [get_admin, authenticate_admin, get_current_admin, create_admin_access_token] = generate_security(m.Admin) @admin.post("/" + token_path)
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordRequestForm from fastapi import Depends from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse from pony.orm import db_session from app.utils.pydantic_security import * from app.settings.config import cfg from app.dependencies import * from app.db import models as m from app.utils.utils_of_security import generate_security, basic_login, scopes_to_db from app.utils.jinja2_utils import _roles_to_home_urls SECRET_KEY = cfg.get('keys', "direction_expert") ACCESS_TOKEN_TIME = int(cfg.get('keys', "direction_expert_time")) token_path = "direction_expert_token" direction_expert_oauth2_scheme = OAuth2PasswordBearer(tokenUrl=token_path) [ get_direction_expert, authenticate_direction_expert, get_current_direction_expert, create_direction_expert_access_token ] = generate_security(m.DirectionExpert) direction_expert = APIRouter( tags=["direction_expert"], responses={404: { "description": "Not found" }}, # dependencies=[Depends(open_db_session)] )