Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions backend/app/api/v1/auth.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from db.session import get_db
from core.security import create_access_token
from crud.user_crud import authenticate_user, create_user
from services.auth_service import register_user, login_user
from schemas.user_schema import UserCreate

router = APIRouter()

@router.post("/register")
def register(user_data:UserCreate, db: Session = Depends(get_db)):
user = create_user(db, user_data)
"""Route to register a new user."""
user = register_user(db, user_data)
if not user:
raise HTTPException(status_code=400, detail="Email already registered")
return {"message": "User created successfully"}


@router.post("/login")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
user = authenticate_user(db, form_data.username, form_data.password)
if not user:
"""Route to login a user."""
token = login_user(db, form_data.username, form_data.password)
if not token:
raise HTTPException(status_code=401, detail="Incorrect email or password")
access_token = create_access_token(user_id=user.id, data={"user_id": user.id})
return {"access_token": access_token, "token_type": "bearer"}
return {"access_token": token, "token_type": "bearer"}
97 changes: 26 additions & 71 deletions backend/app/api/v1/cipher.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,31 @@
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, Query
from services.process_service import encrypt_uploaded_file, decrypt_uploaded_file, get_task_status
from db.session import get_db
from models.document_model import Document
from schemas.document_schema import DocumentCreate
from crud.document_crud import create_document
from core.security import get_user_id_from_token
from .tasks import encrypt_file, decrypt_file
from celery.result import AsyncResult
import os

router = APIRouter()

@router.post("/encrypt_file")
async def encrypt_file_route(file_path: str, shift: int, token: str, db: Session = Depends(get_db)):
user_id = get_user_id_from_token(token)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")

if token:
task = encrypt_file.delay(file_path, shift)
document = DocumentCreate(
filename=os.path.basename(file_path),
content=open(file_path, "rb").read(),
status="encrypting",
task_id=task.id,
user_id=user_id,
)
create_document(db, document)
return {"message": "File encryption started", "task_id": task.id}
else:
task = encrypt_file.delay(file_path, shift)
return {"message": "File encryption started", "task_id": task.id}


@router.post("/decrypt_file")
async def decrypt_file_route(file_path: str, shift: int, token: str, db: Session = Depends(get_db)):
user_id = get_user_id_from_token(token)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")

if token:
task = decrypt_file.delay(file_path, shift)
document = DocumentCreate(
filename=os.path.basename(file_path),
content=open(file_path, "rb").read(),
status="decrypting",
user_id=user_id,
task_id=task.id
)
create_document(db, document)
return {"message": "File decryption started", "task_id": task.id}
else:
task = decrypt_file.delay(file_path, shift)
return {"message": "File decryption started", "task_id": task.id}


@router.get("/task_status/{task_id}")
async def task_status(task_id: str, db: Session = Depends(get_db)):
task = AsyncResult(task_id)
if task.state == "PENDING":
return {"status": "pending", "details": "Task is being processed"}
elif task.state == "SUCCESS":
file_path = task.result
file_name = os.path.basename(file_path)

document = db.query(Document).filter(Document.task_id == task_id).first()
if document:
document.status = "completed"
db.commit()

return {"status": "success", "details": "Task completed", "file_name": file_name}
elif task.state == "FAILURE":
return {"status": "failure", "details": str(task.info)}
else:
return {"status": task.state}
@router.post("/encrypt")
def encrypt_file_route(
file_path: str,
shift: int,
token: str = Query(None),
db: Session = Depends(get_db)
):
"""Route to encrypt a file using Caesar cipher."""
return encrypt_uploaded_file(file_path, shift, token, db)

@router.post("/decrypt")
def decrypt_file_route(
file_path: str,
shift: int,
token: str = Query(None),
db: Session = Depends(get_db)
):
"""Route to decrypt a file using Caesar cipher."""
return decrypt_uploaded_file(file_path, shift, token, db)

@router.get("/status/{task_id}")
def get_task_status_route(task_id: str, db: Session = Depends(get_db)):
"""Route to get the status of a task."""
return get_task_status(task_id, db)
35 changes: 35 additions & 0 deletions backend/app/api/v1/file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from fastapi import APIRouter, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from io import BytesIO
from services.file_service import upload_file, download_file, delete_file

router = APIRouter()

@router.post("/upload")
async def upload_file_route(file: UploadFile = File(...)):
"""Route to upload a file to cloud storage."""
return upload_file(file)


@router.get("/download")
async def download_route(file_url: str):
"""Route to download a file from cloud storage using its URL."""
try:
result = download_file(file_url)
file_content = result["file"]
media_type = result["media_type"]
filename = file_url.split('/')[-1]

return StreamingResponse(BytesIO(file_content), media_type=media_type, headers={
"Content-Disposition": f"attachment; filename={filename}"
})
except HTTPException as e:
raise e
except Exception:
raise HTTPException(status_code=500, detail="An error occurred while downloading the file")


@router.delete("/delete/{file_name}")
async def delete_file_route(file_name: str):
"""Route to delete a file in cloud storage by its name."""
return delete_file(file_name)
38 changes: 0 additions & 38 deletions backend/app/api/v1/file_handler.py

This file was deleted.

52 changes: 30 additions & 22 deletions backend/app/api/v1/tasks.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from celery import Celery
from firebase_admin import storage
from core.config import settings
from core import firebase_init
from core.ceaser_cipher import caesar_cipher, ReaderFactory
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Literal
import os


Expand All @@ -11,34 +14,39 @@
backend=settings.CELERY_RESULT_BACKEND
)

bucket = storage.bucket(settings.GCS_BUCKET_NAME)

@celery.task
def encrypt_file(file_path: Path, shift: int):
reader = ReaderFactory.get_reader(file_path)
data = reader.read()
encrypted_data = caesar_cipher(data, shift, decrypt=False)

file_name, file_extension = os.path.splitext(file_path)
encrypted_file_path = f"{file_name}_encrypted{file_extension}"
def process_file(file_path: str, shift: int, operation: Literal["encrypt", "decrypt"]) -> str:
"""Process file with Caesar cipher and upload to cloud storage."""

reader.write(encrypted_data, output_file=encrypted_file_path)
with TemporaryDirectory() as temp_dir:
local_file_path = os.path.join(temp_dir, os.path.basename(file_path))
blob = bucket.blob(file_path)
blob.download_to_filename(local_file_path)

os.remove(file_path)

return encrypted_file_path
reader = ReaderFactory.get_reader(local_file_path)
data = reader.read()
processed_data = caesar_cipher(data, shift, decrypt=(operation == "decrypt"))

output_file_name = f"{os.path.splitext(file_path)[0]}_{operation}{os.path.splitext(file_path)[1]}"
processed_file_path = os.path.join(temp_dir, output_file_name)
reader.write(processed_data, output_file=processed_file_path)

@celery.task
def decrypt_file(file_path: str, shift: int):
reader = ReaderFactory.get_reader(file_path)
data = reader.read()
decrypted_data = caesar_cipher(data, shift, decrypt=True)
destination_path = f"{operation}/{os.path.basename(processed_file_path)}"
processed_blob = bucket.blob(destination_path)
processed_blob.upload_from_filename(processed_file_path)

file_name, file_extension = os.path.splitext(file_path)
decrypted_file_path = f"{file_name}_decrypted{file_extension}"
return processed_blob.public_url

reader.write(decrypted_data, output_file=decrypted_file_path)

os.remove(file_path)
@celery.task
def encrypt_file(file_path: str, shift: int) -> str:
"""Encrypt a file and upload the result to cloud storage."""
return process_file(file_path, shift, operation="encrypt")

return decrypted_file_path

@celery.task
def decrypt_file(file_path: str, shift: int) -> str:
"""Decrypt a file and upload the result to cloud storage."""
return process_file(file_path, shift, operation="decrypt")
Loading