rsnarsna commited on
Commit ·
81d8c42
1
Parent(s): a65bc49
first commit
Browse filesFiles changed (12)
- .gitignoreAdded+216
- DockerfileAdded+20
- README.md+122-8
- backend/main.pyAdded+518
- backend/requirements.txtAdded+38
- backend/static/style.cssAdded+207
- backend/templates/base.htmlAdded+36
- backend/templates/dashboard.htmlAdded+69
- backend/templates/login.htmlAdded+25
- backend/templates/signup.htmlAdded+46
- task.mdAdded+87
- uploads/4_rsna_13_2_feb.pdfAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216# Byte-compiled / optimized / DLL files__pycache__/*.py[codz]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py.cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.# Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control# poetry.lock# poetry.toml
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.# https://pdm-project.org/en/latest/usage/project/#working-with-version-control# pdm.lock# pdm.toml.pdm-python.pdm-build/
# pixi# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.# pixi.lock# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one# in the .venv directory. It is recommended not to include this directory in version control..pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# Redis*.rdb*.aof*.pid
# RabbitMQmnesia/rabbitmq/rabbitmq-data/
# ActiveMQactivemq-data/
# SageMath parsed files*.sage.py
# Environments.env.envrc.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.# .idea/
# Abstra# Abstra is an AI-powered process automation framework.# Ignore directories containing user credentials, local state, and settings.# Learn more at https://abstra.io/docs.abstra/
# Visual Studio Code# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore# and can be added to the global gitignore or merged into this file. However, if you prefer, # you could uncomment the following to ignore the entire vscode folder# .vscode/
# Ruff stuff:.ruff_cache/
# PyPI configuration file.pypirc
# Marimomarimo/_static/marimo/_lsp/__marimo__/
# Streamlit.streamlit/secrets.toml1234567891011121314151617181920# Use an official lightweight Python imageFROM python:3.10-slim
# Set the working directory inside the containerWORKDIR /app
# Copy the requirements file into the containerCOPY backend/requirements.txt /app/backend/requirements.txt
# Install the dependenciesRUN pip install --no-cache-dir -r/app/backend/requirements.txt
# Copy the entire directory into the containerCOPY . /app
# Expose the correct port (Hugging Face Spaces uses 7860 by default, change if needed)EXPOSE 7860
# Command to run the FastAPI application using uvicornCMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011---title: Fullstack Simple Auth Docs Uploademoji: 🐨colorFrom: purplecolorTo: greensdk: dockerpinned: falselicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# Task 1: FastAPI File Management ApplicationA modern, fast, and secure web application built with **FastAPI**, **MySQL**, and **Jinja2**. This application allows users to register, log in, manage their profiles, and securely upload, download, and delete files through a beautiful dark-themed, glassmorphic UI.---## 🚀 Features- **User Authentication**: Secure signup and login functionality using hashed passwords (bcrypt) and cookie-based session management.- **File Management**: Upload (up to 2 files at once), download, and delete files securely.- **Interactive Dashboard**: A user-friendly dashboard to view all stored files, track upload times, and manage data.- **RESTful API**: Along with the frontend, the app provides standard JSON API endpoints for profile management and system interactions.- **Glassmorphic UI**: A stunning, responsive frontend built with customized CSS and Jinja2 templates.---## 🛠️ Tech Stack- **Backend**: FastAPI (Python)- **Database**: MySQL (via SQLAlchemy ORM)- **Frontend**: HTML5, CSS3 (Glassmorphism), Jinja2 Templates- **Authentication**: JWT token-based auth stored in HTTP-only cookies- **File Storage**: Local filesystem (`backend/uploaded_files/`)---## 📋 PrerequisitesBefore you begin, ensure you have the following installed:- Python 3.9+- MySQL Server (running locally or remotely)- `pip` (Python package manager)---## ⚙️ Installation & Setup1. **Clone or Download the Repository**Navigate to the project directory:```bashcd "g:\Soft Mania\internship\task 1"```2. **Set Up a Virtual Environment**```bashpython -m venv venv# On Windows:.\venv\Scripts\activate# On macOS/Linux:source venv/bin/activate```3. **Install Dependencies**Install all required packages from `req.txt`:```bashpip install -r req.txt```4. **Database Configuration**Ensure your MySQL server is running. Create a database (e.g., `testbd`).Update the `DATABASE_URL` string in `backend/main.py` if your database credentials differ from:```pythonSQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:root@localhost/testbd"```5. **Run the Application**Start the FastAPI development server using Uvicorn:```bashpython -m uvicorn backend.main:app --host 0.0.0.0 --port 8890 --reload```---## 📖 Usage GuideOnce the server is running, the application is accessible through your web browser.### 🌐 Web Interface (UI)- **Home / Login**: Navigate to `http://localhost:8890/login` to access the login portal.- **Sign Up**: If you are a new user, click "Sign up" on the login page or navigate to `http://localhost:8890/signup` to create a new account.- **Dashboard**: Upon logging in, you will be redirected to `http://localhost:8890/dashboard`.- **Uploading**: Use the "Upload Files" panel to select and upload up to 2 files (PDF, PNG, JPG/JPEG).- **Managing Files**: View your uploaded files in the "Your Files" table. Click **⬇ Download** to save them locally, or **🗑 Delete** to remove them permanently from the server.- **Logout**: Click the "Logout" button in the top right corner of the dashboard to securely end your session.### 🔌 API Endpoints (For Developers)The application also exposes JSON endpoints that can be tested via tools like Postman or cURL.*(Note: Some UI and API routes share paths depending on the method and `Accept` headers).*- `POST /signup` - Register a new user (Form Data or JSON).- `POST /login` - Authenticate and receive an access token.- `GET /users/me` - Retrieve current logged-in user details.- `POST /upload` - Upload files via API.- `GET /files` - List all files belonging to the auth user.- `DELETE /files/{id}` - Delete a specific file.---## 📂 Project Structure```texttask 1/│├── backend/│ ├── main.py # Main FastAPI application & routes│ ├── templates/ # Jinja2 HTML Templates│ │ ├── base.html # Global layout wrapper│ │ ├── login.html # Login page│ │ ├── signup.html # Registration page│ │ └── dashboard.html # User file management dashboard│ ├── static/│ │ └── style.css # Design system & Glassmorphic styles│ └── uploaded_files/ # Secure directory for user uploads│├── req.txt # Project dependencies list├── .gitignore # Files ignored by version control└── README.md # This documentation file```---## 🔒 Security Notes- Passwords are securely hashed using `bcrypt` before being stored in MySQL.- Uploaded files are renamed with unique identifiers to prevent overwriting and path traversal attacks.- Session tokens are stored in `httponly` browser cookies for the UI flow to mitigate XSS risks.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518import osfrom typing import Optional, Listfrom datetime import datetimefrom pathlib import Path
from fastapi import FastAPI, Depends, HTTPException, status, Request, Formfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestFormfrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom fastapi.responses import RedirectResponsefrom pydantic import BaseModel, EmailStrfrom passlib.context import CryptContext
from sqlalchemy import create_engine, Column, Integer, String, Text, ForeignKey, TIMESTAMPfrom sqlalchemy.sql import funcfrom sqlalchemy.orm import sessionmaker, declarative_base, relationship, Session
# ==========================================# Database Configuration# ==========================================SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", "mysql+mysqlconnector://root:@localhost:3306/fullstack_test")
engine = create_engine(SQLALCHEMY_DATABASE_URL)SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db(): db = SessionLocal() try: yield db finally: db.close()
# ==========================================# Models# ==========================================class User(Base): __tablename__ = "users"
id = Column(Integer, primary_key=True, index=True) name = Column(String(100), nullable=False) age = Column(Integer, nullable=False) address = Column(Text, nullable=False) email = Column(String(100), unique=True, index=True, nullable=False) mobile_number = Column(String(20), nullable=False) password_hash = Column(String(255), nullable=False) created_at = Column(TIMESTAMP, server_default=func.now())
files = relationship("File", back_populates="owner")
class File(Base): __tablename__ = "files"
id = Column(Integer, primary_key=True, index=True) filename = Column(String(255), nullable=False) file_type = Column(String(50), nullable=False) user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) upload_timestamp = Column(TIMESTAMP, server_default=func.now())
owner = relationship("User", back_populates="files")
# ==========================================# Schemas# ==========================================class UserCreate(BaseModel): name: str age: int address: str email: EmailStr mobile_number: str password: str
class UserLogin(BaseModel): email: EmailStr password: str
class UserResponse(BaseModel): id: int name: str email: str
class Config: from_attributes = True
class Token(BaseModel): access_token: str token_type: str
class TokenData(BaseModel): email: Optional[str] = None
# ==========================================# FastAPI App setup# ==========================================# Create DB tablesBase.metadata.create_all(bind=engine)
app = FastAPI(title="Task 1 API")
# --- Static files & Templates ---BASE_DIR = Path(__file__).resolve().parentapp.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
# --- Helper Functions ---def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password[:72], hashed_password)
def get_password_hash(password): return pwd_context.hash(password[:72])
def get_user_by_email(db: Session, email: str): return db.query(User).filter(User.email == email).first()
# ==========================================# API Endpoints# ==========================================@app.post("/signup", response_model=UserResponse, status_code=status.HTTP_201_CREATED)def signup(user: UserCreate, db: Session = Depends(get_db)): db_user = get_user_by_email(db, email=user.email) if db_user: raise HTTPException(status_code=400, detail="Email already registered") hashed_password = get_password_hash(user.password) new_user = User( name=user.name, age=user.age, address=user.address, email=user.email, mobile_number=user.mobile_number, password_hash=hashed_password ) db.add(new_user) db.commit() db.refresh(new_user) return new_user
@app.post("/login", response_model=Token)def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): # OAuth2PasswordRequestForm uses 'username' and 'password' # We map 'username' to 'email' in our DB user = get_user_by_email(db, email=form_data.username) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials", headers={"WWW-Authenticate": "Bearer"}, ) if not verify_password(form_data.password, user.password_hash): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials", headers={"WWW-Authenticate": "Bearer"}, ) # In a real app we'd create a proper JWT token here # For simplicity, returning a simple token string access_token = f"fake-jwt-token-for-{user.email}" return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me", response_model=UserResponse)def read_users_me(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): # This is a mock function since we aren't decoding real JWTs yet email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if user is None: raise HTTPException(status_code=401, detail="Invalid token") return user
# ==========================================# File Handling Endpoints# ==========================================
UPLOAD_DIR = "uploads"os.makedirs(UPLOAD_DIR, exist_ok=True)ALLOWED_EXTENSIONS = {".pdf", ".png", ".jpeg", ".jpg"}
from fastapi import UploadFile, File as FastAPIFilefrom fastapi.responses import FileResponseimport shutil
@app.post("/upload")async def upload_file( file: UploadFile = FastAPIFile(...), token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): # Authenticate user email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if not user: raise HTTPException(status_code=401, detail="Invalid token")
# Validate file type file_ext = os.path.splitext(file.filename)[1].lower() if file_ext not in ALLOWED_EXTENSIONS: raise HTTPException(status_code=400, detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_EXTENSIONS)}")
# Generate custom filename custom_filename = f"{user.id}_{user.name.replace(' ', '_')}_{file.filename}" file_path = os.path.join(UPLOAD_DIR, custom_filename)
# Save to disk with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
# Save metadata to database db_file = File( filename=custom_filename, file_type=file_ext, user_id=user.id ) db.add(db_file) db.commit() db.refresh(db_file)
return {"message": "File uploaded successfully", "file_id": db_file.id, "filename": custom_filename}
@app.get("/download/{file_id}")async def download_file( file_id: int, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): # Authenticate user email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if not user: raise HTTPException(status_code=401, detail="Invalid token")
# Fetch file record (Ensuring users can only see their own files) file_record = db.query(File).filter(File.id == file_id, File.user_id == user.id).first() if not file_record: raise HTTPException(status_code=404, detail="File not found")
file_path = os.path.join(UPLOAD_DIR, file_record.filename) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File is missing on the server")
return FileResponse(path=file_path, filename=file_record.filename)
# --- File metadata response schema ---class FileMetaResponse(BaseModel): id: int filename: str file_type: str upload_timestamp: Optional[datetime] = None
class Config: from_attributes = True
@app.get("/files", response_model=List[FileMetaResponse])async def list_files( token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): """List all files belonging to the authenticated user.""" email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if not user: raise HTTPException(status_code=401, detail="Invalid token")
files = db.query(File).filter(File.user_id == user.id).all() return files
@app.put("/files/{file_id}")async def update_file( file_id: int, file: UploadFile = FastAPIFile(...), token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): """Replace an existing file with a new upload.""" email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if not user: raise HTTPException(status_code=401, detail="Invalid token")
file_record = db.query(File).filter(File.id == file_id, File.user_id == user.id).first() if not file_record: raise HTTPException(status_code=404, detail="File not found")
# Validate new file type file_ext = os.path.splitext(file.filename)[1].lower() if file_ext not in ALLOWED_EXTENSIONS: raise HTTPException(status_code=400, detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_EXTENSIONS)}")
# Remove old physical file old_path = os.path.join(UPLOAD_DIR, file_record.filename) if os.path.exists(old_path): os.remove(old_path)
# Save new file custom_filename = f"{user.id}_{user.name.replace(' ', '_')}_{file.filename}" new_path = os.path.join(UPLOAD_DIR, custom_filename) with open(new_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
# Update DB record file_record.filename = custom_filename file_record.file_type = file_ext db.commit() db.refresh(file_record)
return {"message": "File updated successfully", "file_id": file_record.id, "filename": custom_filename}
@app.delete("/files/{file_id}")async def delete_file( file_id: int, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): """Delete a file record and its physical file.""" email = token.replace("fake-jwt-token-for-", "") user = get_user_by_email(db, email=email) if not user: raise HTTPException(status_code=401, detail="Invalid token")
file_record = db.query(File).filter(File.id == file_id, File.user_id == user.id).first() if not file_record: raise HTTPException(status_code=404, detail="File not found")
# Remove physical file file_path = os.path.join(UPLOAD_DIR, file_record.filename) if os.path.exists(file_path): os.remove(file_path)
db.delete(file_record) db.commit()
return {"message": "File deleted successfully"}
# ==========================================================# HTML Page Routes (Jinja2 Templates + cookie-based session)# ==========================================================
def _get_current_user_from_cookie(request: Request, db: Session): """Read the auth token from a cookie and return the User or None.""" token = request.cookies.get("access_token", "") if not token: return None email = token.replace("fake-jwt-token-for-", "") return get_user_by_email(db, email=email)
@app.get("/")def root_redirect(): return RedirectResponse(url="/login", status_code=302)
# ---- Sign-Up Page ----@app.get("/signup")def page_signup(request: Request): return templates.TemplateResponse("signup.html", {"request": request})
@app.post("/signup")def page_signup_post( request: Request, name: str = Form(...), age: int = Form(...), address: str = Form(...), email: str = Form(...), mobile_number: str = Form(...), password: str = Form(...), db: Session = Depends(get_db),): existing = get_user_by_email(db, email=email) if existing: return templates.TemplateResponse("signup.html", { "request": request, "message": "Email already registered", "msg_type": "error", })
new_user = User( name=name, age=age, address=address, email=email, mobile_number=mobile_number, password_hash=get_password_hash(password), ) db.add(new_user) db.commit()
response = RedirectResponse(url="/login", status_code=302) return response
# ---- Login Page ----@app.get("/login")def page_login(request: Request): return templates.TemplateResponse("login.html", {"request": request})
@app.post("/login")def page_login_post( request: Request, email: str = Form(...), password: str = Form(...), db: Session = Depends(get_db),): user = get_user_by_email(db, email=email) if not user or not verify_password(password, user.password_hash): return templates.TemplateResponse("login.html", { "request": request, "message": "Invalid email or password", "msg_type": "error", })
token = f"fake-jwt-token-for-{user.email}" response = RedirectResponse(url="/dashboard", status_code=302) response.set_cookie(key="access_token", value=token, httponly=True) return response
# ---- Dashboard ----@app.get("/dashboard")def page_dashboard(request: Request, db: Session = Depends(get_db)): user = _get_current_user_from_cookie(request, db) if not user: return RedirectResponse(url="/login", status_code=302)
files = db.query(File).filter(File.user_id == user.id).all() return templates.TemplateResponse("dashboard.html", { "request": request, "user": user, "files": files, })
# ---- Upload from browser ----@app.post("/upload")async def page_upload( request: Request, file1: UploadFile = FastAPIFile(...), file2: Optional[UploadFile] = FastAPIFile(None), db: Session = Depends(get_db),): user = _get_current_user_from_cookie(request, db) if not user: return RedirectResponse(url="/login", status_code=302)
uploaded = 0 for f in [file1, file2]: if f is None or f.filename == "": continue file_ext = os.path.splitext(f.filename)[1].lower() if file_ext not in ALLOWED_EXTENSIONS: continue # silently skip invalid types custom_filename = f"{user.id}_{user.name.replace(' ', '_')}_{f.filename}" dest = os.path.join(UPLOAD_DIR, custom_filename) with open(dest, "wb") as buf: shutil.copyfileobj(f.file, buf) db_file = File(filename=custom_filename, file_type=file_ext, user_id=user.id) db.add(db_file) uploaded += 1
db.commit() return RedirectResponse(url="/dashboard", status_code=302)
# ---- Download from browser ----@app.get("/download/{file_id}")async def page_download(file_id: int, request: Request, db: Session = Depends(get_db)): user = _get_current_user_from_cookie(request, db) if not user: return RedirectResponse(url="/login", status_code=302)
file_record = db.query(File).filter(File.id == file_id, File.user_id == user.id).first() if not file_record: return RedirectResponse(url="/dashboard", status_code=302)
file_path = os.path.join(UPLOAD_DIR, file_record.filename) if not os.path.exists(file_path): return RedirectResponse(url="/dashboard", status_code=302)
from fastapi.responses import FileResponse as FR return FR(path=file_path, filename=file_record.filename)
# ---- Delete from browser ----@app.get("/delete/{file_id}")def page_delete(file_id: int, request: Request, db: Session = Depends(get_db)): user = _get_current_user_from_cookie(request, db) if not user: return RedirectResponse(url="/login", status_code=302)
file_record = db.query(File).filter(File.id == file_id, File.user_id == user.id).first() if file_record: file_path = os.path.join(UPLOAD_DIR, file_record.filename) if os.path.exists(file_path): os.remove(file_path) db.delete(file_record) db.commit()
return RedirectResponse(url="/dashboard", status_code=302)
# ---- Logout ----@app.get("/logout")def page_logout(): response = RedirectResponse(url="/login", status_code=302) response.delete_cookie("access_token") return response1234567891011121314151617181920212223242526272829303132333435363738aiofiles==25.1.0annotated-doc==0.0.4annotated-types==0.7.0anyio==4.12.1bcrypt==4.0.1certifi==2026.2.25cffi==2.0.0charset-normalizer==3.4.4click==8.3.1colorama==0.4.6cryptography==46.0.5dnspython==2.8.0ecdsa==0.19.1email-validator==2.3.0fastapi==0.135.1greenlet==3.3.2h11==0.16.0idna==3.11Jinja2==3.1.6MarkupSafe==3.0.3mysql-connector-python==9.6.0passlib==1.7.4pyasn1==0.6.2pycparser==3.0pydantic==2.12.5pydantic_core==2.41.5PyMySQL==1.1.2python-jose==3.5.0python-multipart==0.0.22requests==2.32.5rsa==4.9.1six==1.17.0SQLAlchemy==2.0.47starlette==0.52.1typing-inspection==0.4.2typing_extensions==4.15.0urllib3==2.6.3uvicorn==0.41.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/* ================================================ Task 1 — Design System ================================================ */@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
:root { --bg-primary: #0f0f1a; --bg-card: rgba(255,255,255,0.05); --bg-card-hover:rgba(255,255,255,0.08); --accent: #6c63ff; --accent-glow: rgba(108,99,255,0.35); --success: #2ecc71; --danger: #e74c3c; --text: #e8e8f0; --text-muted: #8888a8; --border: rgba(255,255,255,0.08); --radius: 14px; --transition: .25s cubic-bezier(.4,0,.2,1);}
*, *::before, *::after { box-sizing: border-box; margin:0; padding:0; }
body { font-family: 'Inter', system-ui, sans-serif; background: var(--bg-primary); background-image: radial-gradient(ellipse 80% 60% at 50% -20%, rgba(108,99,255,.15), transparent), radial-gradient(ellipse 60% 50% at 80% 100%, rgba(99,200,255,.08), transparent); color: var(--text); min-height: 100vh; line-height: 1.6;}
a { color: var(--accent); text-decoration: none; transition: color var(--transition); }a:hover { color: #8b83ff; }
/* ---- Navbar ---- */.navbar { display: flex; align-items: center; justify-content: space-between; padding: 1rem 2rem; background: rgba(15,15,26,.85); backdrop-filter: blur(12px); border-bottom: 1px solid var(--border); position: sticky; top:0; z-index: 100;}.navbar .brand { font-size:1.25rem; font-weight:700; color: var(--accent); }.navbar .nav-links { display:flex; gap:1.2rem; align-items:center; }.navbar .nav-links a { font-size:.9rem; font-weight:500; color:var(--text-muted); }.navbar .nav-links a:hover { color:var(--text); }.navbar .user-badge { background: var(--bg-card); padding:.35rem .9rem; border-radius:20px; font-size:.85rem; color:var(--accent); border:1px solid var(--border);}
/* ---- Container ---- */.container { max-width:960px; margin:0 auto; padding:2rem 1.5rem; }
/* ---- Cards ---- */.card { background: var(--bg-card); backdrop-filter: blur(16px); border: 1px solid var(--border); border-radius: var(--radius); padding: 2.5rem; transition: transform var(--transition), box-shadow var(--transition);}.card:hover { transform: translateY(-2px); box-shadow: 0 8px 32px rgba(0,0,0,.25);}.card-narrow { max-width:480px; margin:3rem auto; }
.card h2 { font-size:1.6rem; font-weight:700; margin-bottom:.3rem; background: linear-gradient(135deg, var(--accent), #63c6ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent;}.card .subtitle { color:var(--text-muted); margin-bottom:1.8rem; font-size:.92rem; }
/* ---- Forms ---- */.form-group { margin-bottom:1.15rem; }.form-group label { display:block; font-size:.82rem; font-weight:600; color:var(--text-muted); margin-bottom:.35rem; text-transform:uppercase; letter-spacing:.05em;}.form-group input,.form-group textarea,.form-group select { width:100%; padding:.7rem 1rem; background: rgba(255,255,255,0.04); border:1px solid var(--border); border-radius:8px; color:var(--text); font-size:.95rem; font-family:inherit; transition: border-color var(--transition), box-shadow var(--transition);}.form-group input:focus,.form-group textarea:focus { outline:none; border-color:var(--accent); box-shadow: 0 0 0 3px var(--accent-glow);}.form-group textarea { resize:vertical; min-height:70px; }
.form-row { display:grid; grid-template-columns:1fr 1fr; gap:0 1rem; }
/* ---- Buttons ---- */.btn { display:inline-flex; align-items:center; justify-content:center; gap:.4rem; padding:.72rem 1.6rem; border:none; border-radius:8px; font-family:inherit; font-size:.92rem; font-weight:600; cursor:pointer; transition: all var(--transition);}.btn-primary { background: linear-gradient(135deg, var(--accent), #4f46e5); color:#fff; box-shadow: 0 4px 15px var(--accent-glow);}.btn-primary:hover { transform:translateY(-1px); box-shadow:0 6px 20px var(--accent-glow); }
.btn-danger { background:var(--danger); color:#fff; }.btn-danger:hover { background:#c0392b; }
.btn-sm { padding:.4rem .9rem; font-size:.82rem; border-radius:6px; }
.btn-outline { background:transparent; border:1px solid var(--border); color:var(--text-muted);}.btn-outline:hover { border-color:var(--accent); color:var(--accent); }
/* ---- Flash Messages ---- */.flash { padding:.85rem 1.2rem; border-radius:8px; margin-bottom:1.5rem; font-size:.9rem; font-weight:500; animation: slideDown .35s ease-out;}.flash-success { background:rgba(46,204,113,.12); border:1px solid rgba(46,204,113,.3); color:var(--success); }.flash-error { background:rgba(231,76,60,.12); border:1px solid rgba(231,76,60,.3); color:var(--danger); }
@keyframes slideDown { from { opacity:0; transform:translateY(-10px); } to { opacity:1; transform:translateY(0); }}
/* ---- File Upload Area ---- */.upload-area { border:2px dashed var(--border); border-radius:var(--radius); padding:2rem; text-align:center; cursor:pointer; transition: border-color var(--transition), background var(--transition);}.upload-area:hover { border-color:var(--accent); background:rgba(108,99,255,.04); }.upload-area .icon { font-size:2rem; margin-bottom:.5rem; }.upload-area p { color:var(--text-muted); font-size:.88rem; }.upload-area input[type="file"] { display:none; }
.file-inputs { display:flex; gap:1rem; margin-top:1rem; flex-wrap:wrap; }.file-input-wrapper { flex:1; min-width:200px; background:rgba(255,255,255,.03); border:1px solid var(--border); border-radius:8px; padding:.6rem 1rem; display:flex; align-items:center; gap:.5rem; font-size:.88rem; color:var(--text-muted);}.file-input-wrapper input[type="file"] { flex:1; color:var(--text-muted); font-size:.85rem; }.file-input-wrapper input[type="file"]::file-selector-button { background:var(--accent); color:#fff; border:none; padding:.3rem .7rem; border-radius:5px; font-size:.8rem; cursor:pointer; margin-right:.5rem;}
/* ---- Table ---- */.table-wrap { overflow-x:auto; margin-top:1.5rem; }table { width:100%; border-collapse:collapse; }thead th { text-align:left; padding:.75rem 1rem; font-size:.78rem; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--border);}tbody td { padding:.75rem 1rem; font-size:.9rem; border-bottom:1px solid var(--border);}tbody tr { transition: background var(--transition); }tbody tr:hover { background:var(--bg-card-hover); }
.badge { display:inline-block; padding:.15rem .55rem; border-radius:4px; font-size:.75rem; font-weight:600; text-transform:uppercase;}.badge-pdf { background:rgba(231,76,60,.15); color:#e74c3c; }.badge-png { background:rgba(46,204,113,.15); color:#2ecc71; }.badge-jpg { background:rgba(243,156,18,.15); color:#f39c12; }.badge-jpeg { background:rgba(243,156,18,.15); color:#f39c12; }
.actions { display:flex; gap:.5rem; }
/* ---- Empty state ---- */.empty-state { text-align:center; padding:3rem 1rem; color:var(--text-muted);}.empty-state .icon { font-size:3rem; margin-bottom:.8rem; opacity:.5; }
/* ---- Footer text ---- */.form-footer { text-align:center; margin-top:1.4rem; font-size:.88rem; color:var(--text-muted); }
/* ---- Responsive ---- */@media (max-width:600px) { .form-row { grid-template-columns:1fr; } .card-narrow { margin:1.5rem 1rem; padding:1.5rem; } .navbar { padding:.8rem 1rem; } .file-inputs { flex-direction:column; }}123456789101112131415161718192021222324252627282930313233343536<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Task 1 — Full-Stack File Management Application"> <title>{% block title %}Task 1 App{% endblock %}</title> <link rel="stylesheet" href="/static/style.css"></head><body>
<!-- Navbar --> <nav class="navbar"> <a href="/dashboard" class="brand">📁 Task 1</a> <div class="nav-links"> {% if user %} <span class="user-badge">👤 {{ user.name }}</span> <a href="/logout">Logout</a> {% else %} <a href="/login">Login</a> <a href="/signup">Sign Up</a> {% endif %} </div> </nav>
<!-- Flash Messages --> <div class="container"> {% if message %} <div class="flash flash-{{ msg_type | default('success') }}">{{ message }}</div> {% endif %}
{% block content %}{% endblock %} </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869{% extends "base.html" %}{% block title %}Dashboard — Task 1{% endblock %}
{% block content %}
<!-- Upload Card --><div class="card" style="margin-bottom:2rem;"> <h2>Upload Files</h2> <p class="subtitle">Accepted formats: PDF, PNG, JPEG (max 2 files at a time)</p>
<form method="POST" action="/upload" enctype="multipart/form-data" id="upload-form"> <div class="file-inputs"> <div class="file-input-wrapper"> <span>📄 File 1</span> <input type="file" name="file1" accept=".pdf,.png,.jpg,.jpeg" required> </div> </div> <button type="submit" class="btn btn-primary" style="margin-top:1.2rem;">⬆ Upload</button> </form></div>
<!-- File List Card --><div class="card"> <h2>Your Files</h2> <p class="subtitle">{{ files | length }} file{{ 's' if files | length != 1 else '' }} stored</p>
{% if files %} <div class="table-wrap"> <table> <thead> <tr> <th>#</th> <th>Filename</th> <th>Type</th> <th>Uploaded</th> <th>Actions</th> </tr> </thead> <tbody> {% for f in files %} <tr> <td>{{ loop.index }}</td> <td>{{ f.filename }}</td> <td> {% set ext = f.file_type | replace('.','') %} <span class="badge badge-{{ ext }}">{{ ext | upper }}</span> </td> <td>{{ f.upload_timestamp.strftime('%d %b %Y, %H:%M') if f.upload_timestamp else '—' }}</td> <td class="actions"> <a href="/download/{{ f.id }}" class="btn btn-outline btn-sm">⬇ Download</a> <form action="/delete/{{ f.id }}" method="get" style="display:inline;" onsubmit="return confirm('Delete this file?')"> <button type="submit" class="btn btn-danger btn-sm">🗑 Delete</button> </form> </td> </tr> {% endfor %} </tbody> </table> </div> {% else %} <div class="empty-state"> <div class="icon">📂</div> <p>No files yet — upload your first file above!</p> </div> {% endif %}</div>
{% endblock %}12345678910111213141516171819202122232425{% extends "base.html" %}{% block title %}Login — Task 1{% endblock %}
{% block content %}<div class="card card-narrow"> <h2>Welcome Back</h2> <p class="subtitle">Sign in to access your dashboard</p>
<form method="POST" action="/login" id="login-form"> <div class="form-group"> <label for="email">Email</label> <input type="email" id="email" name="email" placeholder="you@example.com" required> </div>
<div class="form-group"> <label for="password">Password</label> <input type="password" id="password" name="password" placeholder="••••••••" required> </div>
<button type="submit" class="btn btn-primary" style="width:100%; margin-top:.5rem;">Log In</button> </form>
<p class="form-footer">Don't have an account? <a href="/signup">Sign up</a></p></div>{% endblock %}12345678910111213141516171819202122232425262728293031323334353637383940414243444546{% extends "base.html" %}{% block title %}Sign Up — Task 1{% endblock %}
{% block content %}<div class="card card-narrow"> <h2>Create Account</h2> <p class="subtitle">Fill in your details to get started</p>
<form method="POST" action="/signup" id="signup-form"> <div class="form-group"> <label for="name">Full Name</label> <input type="text" id="name" name="name" placeholder="John Doe" required> </div>
<div class="form-row"> <div class="form-group"> <label for="age">Age</label> <input type="number" id="age" name="age" placeholder="25" min="1" max="150" required> </div> <div class="form-group"> <label for="mobile_number">Mobile Number</label> <input type="tel" id="mobile_number" name="mobile_number" placeholder="9876543210" required> </div> </div>
<div class="form-group"> <label for="address">Address</label> <textarea id="address" name="address" placeholder="123 Main Street, City" required></textarea> </div>
<div class="form-group"> <label for="email">Email</label> <input type="email" id="email" name="email" placeholder="you@example.com" required> </div>
<div class="form-group"> <label for="password">Password</label> <input type="password" id="password" name="password" placeholder="••••••••" minlength="6" required> </div>
<button type="submit" class="btn btn-primary" style="width:100%; margin-top:.5rem;">Sign Up</button> </form>
<p class="form-footer">Already have an account? <a href="/login">Log in</a></p></div>{% endblock %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687Full-Stack Developer Pre-InterviewAssessment
Objective
The purpose of this assessment is to evaluate your ability to design, develop, host, anddeliver a full-stack web application using Python for the backend, MySQL for thedatabase, and a frontend stack of your choice.
You will be assessed on functionality, deployment skills, code quality, database design,and documentation.
Requirements
1. Frontend
. You may use any frontend technology (HTML/CSS/JS, React, Angular, Vue, etc.).. The application should include:Sign-Up Pageo Fields: Name, Age, Address, Email, Mobile Number, Password.o On successful signup, details must be stored in MySQL.o After signup, redirect to the login page.Login Pageo Validate credentials against data stored in MySQL.o On success, redirect to the main dashboard.
2. Backend
. Must be written only in Python.. You may use Flask, Django, FastAPI, or any Python web framework.. Must handle:Sign-up -> Store user details in MySQL.Login -> Validate credentials.File download -> Provide a test file for download (static or generated).File upload -> Two fields, restricted to PDF, PNG, or JPEG.
3. File Handling
. Uploaded files should be:Restricted to PDF, PNG, or JPEG.Stored in a directory on the server where the backend is hosted.Saved with filenames including the user's name (from login).
4. Database
. Must use MySQL.. Should store:User details (from sign-up).Uploaded file metadata (filename, file type, upload timestamp, userassociation).
Non-Functional Requirements
. Code must be modular, clean, and documented.. Include error handling for invalid inputs and file types.. Apply basic security best practices (password hashing, input validation).. The application must be hosted on a platform of your choice (e.g., Vercel, Netify,Render, AWS, GCP, Azure etc.).. The application must be publicly accessible through a link.
Deliverables
1. GitHub Repository containing:Source code (frontend + backend).Database schema (SQL file or migration).A README.md with:o Local setup instructions.o Hosting details (platform used + deployed link).o Database setup.o Any assumptions made.2. Publicly accessible application URL (hosted version).
Time Limit
You have 3 days to complete and submit your solution.
Submission Guidelines
. Share the GitHub repository link.. Share the hosted application link (must be publicly accessible).. Ensure setup instructions are clear for both local and hosted versions.
Also, please refer to the videos provided in the following link, as we may ask questionsbased on them during the interview.
https://documents.softmania.in/external/manual/appendix/article/links?p=8925397ddf335351a1488377eefdb7c5522becd5be0e42b8c4706fc7e92f8faf.gitignoreAdded+216
DockerfileAdded+20
README.md+122-8
backend/main.pyAdded+518
backend/requirements.txtAdded+38
backend/static/style.cssAdded+207
backend/templates/base.htmlAdded+36
backend/templates/dashboard.htmlAdded+69
backend/templates/login.htmlAdded+25
backend/templates/signup.htmlAdded+46
task.mdAdded+87
uploads/4_rsna_13_2_feb.pdfAdded