Skip to content

Commit

Permalink
feat: add authentication for admin (#1)
Browse files Browse the repository at this point in the history
* feat: add authentication for admin

* chore: change workdir and port
  • Loading branch information
HADB authored Mar 14, 2024
1 parent 73035b6 commit 43655ed
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 14 deletions.
10 changes: 5 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
FROM python:3-alpine

WORKDIR /app
WORKDIR /var/lib/font2svg

COPY requirements.txt /app
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY src /app/src
COPY src ./src

EXPOSE 80
EXPOSE 8000

CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "80"]
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,37 @@

# Font2svg Api

Server-side project, written in Python. (ETA: 2024Q2)
Font2svg server-side project, written in Python. (ETA: 2024Q2)

## Getting started

### Docker

```
$ docker run -d --name font2svg-api \
-v /path/to/font2svg:/var/lib/font2svg/data \
-v /path/to/font2svg/logs:/var/lib/font2svg/logs \
-p 3001:8000 \
font2svg/font2svg-api:latest
```

### Deploy compose

```
services:
font2svg-api:
container_name: font2svg-api
image: font2svg/font2svg-api:latest
restart: always
ports:
- 3001:8000
volumes:
- /path/to/font2svg:/var/lib/font2svg/data
- /path/to/font2svg/logs:/var/lib/font2svg/logs
```

If all goes well, you'll be able to access your font2svg api on `http://localhost:3001` and `http://localhost:3001/docs` to access api docs.

## License

Expand Down
38 changes: 30 additions & 8 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,53 @@
import io
import os
import secrets
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Response, UploadFile
from fastapi import Depends, FastAPI, Header, HTTPException, Response, UploadFile
from fontTools.ttLib import TTFont
from freetype import Face
from yuanfen import ErrorResponse, Logger, SuccessResponse
from yuanfen import Config, ErrorResponse, Logger, SuccessResponse

from . import __version__
from .converter import Converter
from .utils import generate_font_info_cache, get_font_id, remove_font_svg_cache

logger = Logger()

# Create necessary directories and config file if not exists
if not os.path.exists("data/fonts"):
os.makedirs("data/fonts")
if not os.path.exists("data/cache"):
os.makedirs("data/cache")
if not os.path.exists("data/config.yaml"):
admin_token = secrets.token_urlsafe(16)
logger.info("config.yaml not found")
with open("data/config.yaml", "w") as f:
f.write(f"admin_token: {admin_token}\n")
logger.info(f"created config.yaml with random admin_token: {admin_token}")

config = Config("data/config.yaml")


@asynccontextmanager
async def lifespan(_: FastAPI):
logger.info(f"api service started, version: {__version__}")
if not os.path.exists("data/fonts"):
os.makedirs("data/fonts")
if not os.path.exists("data/cache"):
os.makedirs("data/cache")
yield
logger.info("api service stopped")


app = FastAPI(lifespan=lifespan)
app = FastAPI(
title="Font2svg Api",
summary="Font2svg server-side project, written in Python.",
version=__version__,
lifespan=lifespan,
)


def admin_auth(admin_token: str = Header(None)):
if admin_token != config["admin_token"]:
raise HTTPException(status_code=401, detail="Unauthorized")
return True


@app.get("/health", summary="Health check")
Expand All @@ -49,7 +71,7 @@ def get_character(font_file: str, unicode: str):
return Response(content=f.read(), media_type="image/svg+xml")


@app.post("/font", summary="Upload font file")
@app.post("/font", summary="Upload font file (admin_token needed)", dependencies=[Depends(admin_auth)])
def upload(file: UploadFile):
if file.content_type not in ["font/ttf", "font/otf"]:
return ErrorResponse(message="Only support ttf or otf fonts")
Expand Down

0 comments on commit 43655ed

Please sign in to comment.