Spaces:
Runtime error
Runtime error
Commit ·
e941a76
1
Parent(s): 9af3b3c
update-delete
Browse filesFiles changed (20)
- KTP.jpgDeleted
- app/__pycache__/dependencies.cpython-310.pyc
- app/__pycache__/main.cpython-310.pyc
- app/api/v1/endpoints/__pycache__/auth.cpython-310.pyc
- app/api/v1/endpoints/__pycache__/ocrtemplate.cpython-310.pyc
- app/api/v1/endpoints/__pycache__/user.cpython-310.pyc
- app/api/v1/endpoints/auth.py+2-2
- app/api/v1/endpoints/ocrtemplate.py+12
- app/api/v1/endpoints/user.py+24-7
- app/core/__pycache__/middleware.cpython-310.pycAdded
- app/crud/__pycache__/ocrtemplate.cpython-310.pyc
- app/crud/__pycache__/users.cpython-310.pyc
- app/crud/ocrtemplate.py+18-3
- app/crud/users.py+1-1
- app/dependencies.py+5-5
- app/main.py+1-1
- app/models/__pycache__/token.cpython-310.pyc
- app/models/__pycache__/users.cpython-310.pyc
- app/models/token.py+1
- app/models/users.py+8-2
14 unmodified lines151617181920212223242514 unmodified linesif not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Incorrect username or password",headers={"WWW-Authenticate": "Bearer"},)access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)access_token = create_access_token(data={"sub": user["username"]}, expires_delta=access_token_expires)return {"access_token": access_token, "token_type": "bearer"}14 unmodified lines151617181920212223242514 unmodified linesif not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Incorrect email or password",headers={"WWW-Authenticate": "Bearer"},)access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)access_token = create_access_token(data={"sub": user["email"]}, expires_delta=access_token_expires)return {"access_token": access_token, "token_type": "bearer"}
8 unmodified lines910111213141 unmodified line1617181920218 unmodified lines3031323334358 unmodified lines# In-memory storage for simplicity; replace with your database logictemplates = {}@router.post("/", response_model=OCRTemplate)async def create_OCR_template(template: OCRTemplate, current_user: User = Depends(get_current_user)):1 unmodified linetemplate = await create_template(template, current_user['user_id'])return template@router.get("/", response_model=List[Union[OCRTemplateInDB, dict]])async def get_OCR_templates_for_user(template_name:Optional[bool] = False, current_user: User = Depends(get_current_user)):8 unmodified linesraise HTTPException(status_code=404, detail="Template not found")return template@router.put("/templates", response_model=OCRTemplate)async def update_template_endpoint(template: OCRTemplate, user: str = Depends(get_current_user)):print("Updating template:", template)8 unmodified lines91011121314151617181 unmodified line2021222324252627282930318 unmodified lines40414243444546478 unmodified lines# In-memory storage for simplicity; replace with your database logictemplates = {}@router.get("/all", response_model=List[OCRTemplateInDB])async def get_all_templates_endpoint():templates = await get_all_templates()return templates@router.post("/", response_model=OCRTemplate)async def create_OCR_template(template: OCRTemplate, current_user: User = Depends(get_current_user)):1 unmodified linetemplate = await create_template(template, current_user['user_id'])return template@router.post("/templateForAll", response_model=OCRTemplate)async def create_OCR_template(template: OCRTemplate, current_user: User = Depends(get_current_user)):template = await create_template(template, current_user['user_id'], templateForAll=True)return template@router.get("/", response_model=List[Union[OCRTemplateInDB, dict]])async def get_OCR_templates_for_user(template_name:Optional[bool] = False, current_user: User = Depends(get_current_user)):8 unmodified linesraise HTTPException(status_code=404, detail="Template not found")return template@router.put("/templates", response_model=OCRTemplate)async def update_template_endpoint(template: OCRTemplate, user: str = Depends(get_current_user)):print("Updating template:", template)
123456789101112131415161718192021222324# app/api/v1/endpoints/user.pyfrom fastapi import APIRouter, Depends, HTTPExceptionfrom app.models import usersfrom app.crud.users import *from app.core.security import get_password_hashfrom app.dependencies import get_current_userrouter = APIRouter()@router.post("/")async def register_user(user: users.User):db_user = await get_user_by_username(user.username)if db_user:raise HTTPException(status_code=400, detail="Username already exists")db_user = await get_user_by_email(user.email)if db_user:raise HTTPException(status_code=400, detail="Email already exists")user_in_db = UserInDB(**user.dict(), hashed_password=get_password_hash(user.password))user = await create_user(user_in_db)1234567891011121314151617181920212223242526272829303132333435363738394041# app/api/v1/endpoints/user.pyfrom fastapi import APIRouter, Depends, HTTPException, Formfrom app.models import usersfrom app.crud.users import *from app.core.security import get_password_hashfrom app.dependencies import get_current_userfrom pydantic import EmailStrrouter = APIRouter()@router.post("/")async def register_user( first_name: str = Form(...),surname: str = Form(...),email: EmailStr = Form(...),phone: str = Form(...),country: str = Form(...),address: str = Form(...),password: str = Form(...)):# db_user = await get_user_by_username(user.username)# if db_user:# raise HTTPException(status_code=400, detail="Username already exists")db_user = await get_user_by_email(email)if db_user:raise HTTPException(status_code=400, detail="Email already exists! Please try another one.")user = User(first_name=first_name,surname=surname,phone=phone,country=country,address=address,email=email,password=password)user_in_db = UserInDB(**user.dict(), hashed_password=get_password_hash(user.password))print("User in db:", user_in_db)user = await create_user(user_in_db)
8 unmodified lines9101112131415161718192021222324252627282930318 unmodified linesasync def create_template(template: OCRTemplate, user_id: str):existing_template = await get_template_by_name_and_user(template.template_name, user_id)if existing_template:raise HTTPException(status_code=401, detail="Template already exists")template_dict = template.dict()template_dict["user_id"] = user_iddb = get_database(settings.MongoDB_NAME)template = await db["templates"].insert_one(template_dict)if template:return OCRTemplate(**template_dict)return Noneasync def get_all_templates_by_user_id(user_id: str, template_name: Optional[bool] = False)-> Union[List[OCRTemplateInDB], List[dict]]:db = get_database(settings.MongoDB_NAME)templates = await db["templates"].find({"user_id": user_id}).to_list(1000)if template_name:# Return only the template_name field8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445468 unmodified linesasync def create_template(template: OCRTemplate, user_id: str, templateForAll: Optional[bool] = False):existing_template = await get_template_by_name_and_user(template.template_name, user_id)if existing_template:raise HTTPException(status_code=401, detail="Template already exists")template_dict = template.dict()if templateForAll:template_dict["user_id"] = "all"else:template_dict["user_id"] = user_iddb = get_database(settings.MongoDB_NAME)template = await db["templates"].insert_one(template_dict)if template:return OCRTemplate(**template_dict)return Noneasync def get_all_templates():db = get_database(settings.MongoDB_NAME)templates = await db["templates"].find().to_list(1000)return [OCRTemplateInDB(**template) for template in templates]async def get_all_templates_by_user_id(user_id: str, template_name: Optional[bool] = False)-> Union[List[OCRTemplateInDB], List[dict]]:db = get_database(settings.MongoDB_NAME)# Query to find templates with user_id equal to the given user_id or "all"templates = await db["templates"].find({"$or": [{"user_id": user_id},{"user_id": "all"}]}).to_list(1000)# templates = await db["templates"].find({"user_id": user_id}).to_list(1000)if template_name:# Return only the template_name field
28 unmodified lines2930313233343528 unmodified linesreturn userasync def authenticate_user(username: str, password: str):user = await get_user_by_username(username)print("User:", user)if user and verify_password(password, user["password"]):return user28 unmodified lines2930313233343528 unmodified linesreturn userasync def authenticate_user(username: str, password: str):user = await get_user_by_email(username)print("User:", user)if user and verify_password(password, user["password"]):return user
2 unmodified lines34567896 unmodified lines161718192021222324252627282 unmodified linesfrom fastapi.security import OAuth2PasswordBearerfrom jose import JWTError, jwtfrom app.models.token import TokenDatafrom app.crud.users import get_user_by_usernamefrom app.core.config import settingsoauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")6 unmodified lines)try:payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])username: str = payload.get("sub")if username is None:raise credentials_exceptiontoken_data = TokenData(username=username)except JWTError:raise credentials_exceptionuser = await get_user_by_username(username=token_data.username)if user is None:raise credentials_exceptionreturn user2 unmodified lines34567896 unmodified lines161718192021222324252627282 unmodified linesfrom fastapi.security import OAuth2PasswordBearerfrom jose import JWTError, jwtfrom app.models.token import TokenDatafrom app.crud.users import get_user_by_username, get_user_by_emailfrom app.core.config import settingsoauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")6 unmodified lines)try:payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])email: str = payload.get("sub")if email is None:raise credentials_exceptiontoken_data = TokenData(email=email)except JWTError:raise credentials_exceptionuser = await get_user_by_email(email)if user is None:raise credentials_exceptionreturn user
54 unmodified lines5556575859606154 unmodified linesapp.add_middleware(BasicAuthMiddleware, username=os.getenv("fastapiusername"), password=os.getenv("fastapipassword"))# Allow CORS for specific origin with credentialsorigins = [os.getenv("client")54 unmodified lines5556575859606154 unmodified lines# app.add_middleware(BasicAuthMiddleware, username=os.getenv("fastapiusername"), password=os.getenv("fastapipassword"))# Allow CORS for specific origin with credentialsorigins = [os.getenv("client")
7 unmodified lines89107 unmodified linesclass TokenData(BaseModel):username: Optional[str] = None7 unmodified lines8910117 unmodified linesclass TokenData(BaseModel):username: Optional[str] = Noneemail: Optional[str] = None
4 unmodified lines567891011121 unmodified line1415164 unmodified linesimport uuidclass User(BaseModel):user_id: str = Field(default_factory=uuid.uuid4())username: stremail: EmailStrpassword: str1 unmodified lineis_validated: bool = Field(default=False)created_at: datetime = Field(default_factory=datetime.utcnow)updated_at: Optional[str] = None4 unmodified lines5678910111213141516171 unmodified line192021224 unmodified linesimport uuidclass User(BaseModel):user_id: str = Field(default_factory=lambda: str(uuid.uuid4()))first_name: strsurname: strphone: strcountry: straddress: str# username: stremail: EmailStrpassword: str1 unmodified lineis_validated: bool = Field(default=False)created_at: datetime = Field(default_factory=datetime.utcnow)updated_at: Optional[str] = None
KTP.jpgDeleted
app/__pycache__/dependencies.cpython-310.pyc
app/__pycache__/main.cpython-310.pyc
app/api/v1/endpoints/__pycache__/auth.cpython-310.pyc
app/api/v1/endpoints/__pycache__/ocrtemplate.cpython-310.pyc
app/api/v1/endpoints/__pycache__/user.cpython-310.pyc
app/api/v1/endpoints/auth.py+2-2
app/api/v1/endpoints/ocrtemplate.py+12
app/api/v1/endpoints/user.py+24-7
app/core/__pycache__/middleware.cpython-310.pycAdded
app/crud/__pycache__/ocrtemplate.cpython-310.pyc
app/crud/__pycache__/users.cpython-310.pyc
app/crud/ocrtemplate.py+18-3
app/crud/users.py+1-1
app/dependencies.py+5-5
app/main.py+1-1
app/models/__pycache__/token.cpython-310.pyc
app/models/__pycache__/users.cpython-310.pyc
app/models/token.py+1
app/models/users.py+8-2