add function add startup

This commit is contained in:
Valentin CZERYBA 2023-10-13 21:44:30 +02:00
parent 6b0a5a7b65
commit 680634aeee
5 changed files with 24 additions and 2 deletions

View File

@ -0,0 +1,5 @@
from pymongo import MongoClient
import os
client = MongoClient(host=os.environ["MONGO_HOST"], username=os.environ["MONGO_USER"], password=os.environ["MONGO_PASSWORD"])
database = client[os.environ["MONGO_DATABASE"]]

View File

@ -0,0 +1,11 @@
from ..models import users
from ..dependencies import database
from passlib.context import CryptContext
def add(username="", password="", roles="User", disabled=False):
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
user = users.User(username=username, password=pwd_context.hash(password), roles=roles, disabled=disabled)
user_repository = users.UserRepository(database=database.database)
user_repository.save(user)
print("{O} added".format(username))

View File

@ -1,6 +1,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Annotated from typing import Annotated
from pymongo import MongoClient
from fastapi import Depends, HTTPException, status from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt from jose import JWTError, jwt

View File

@ -1,13 +1,18 @@
from fastapi import FastAPI from fastapi import FastAPI
from .routers import users, token from .routers import users, token
from .dependencies import user_add
app = FastAPI() app = FastAPI()
app.include_router(users.router) app.include_router(users.router)
app.include_router(token.router) app.include_router(token.router)
@app.on_event("startup")
async def startup_event():
user_add.add(username="Peter93", password="toto", roles="Admin")
@app.get("/") @app.get("/")
async def root(): async def root():
return {"message": "Hello World !"} return {"message": "Hello World !"}

View File

@ -1,5 +1,5 @@
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from ..dependencies import users_active, permissions_checker from ..dependencies import users_active, permissions_checker, database
from ..models import users from ..models import users
from typing import Annotated from typing import Annotated