Skip to content
Merged
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
24 changes: 24 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"permissions": {
"allow": [
"Bash(ruff check *)",
"Bash(ruff format *)",
"Bash(pytest *)",
"Bash(git status *)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(npm test *)"
],
"ask": [
"Bash(git push *)"
],
"deny": [
"Read(**/.env)",
"Read(**/.env.local)",
"Read(**/.env.*.local)",
"Edit(**/.env)",
"Edit(**/.env.local)",
"Edit(**/.env.*.local)"
]
}
}
4 changes: 4 additions & 0 deletions App/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
# Register static files (images, videos)
app.mount("/static", StaticFiles(directory="static"), name="static")

# CSRF defense: reject state-changing requests without the custom header
# (registered before CORS so CORS stays outside it and still handles preflight)
app.add_middleware(middleware.CSRFHeaderMiddleware)

# CORS Setup for cross-origin requests
# FrontEnd: React, BackEnd: FastAPI
origins_str = os.getenv("CORS_ALLOWED_ORIGINS")
Expand Down
2 changes: 1 addition & 1 deletion App/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ async def login_user(request: Request,
"status": "success"
}

@router.get("/logout", status_code=status.HTTP_200_OK, response_class=JSONResponse, summary="로그아웃")
@router.post("/logout", status_code=status.HTTP_200_OK, response_class=JSONResponse, summary="로그아웃")
async def logout_user(request: Request):
request.state.session.clear()
return {
Expand Down
4 changes: 2 additions & 2 deletions App/services/auth_svc.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async def get_user_by_email(conn: Connection, email: str) -> UserData | None:
HTTPException 500: When an unexpected exception occurs.
"""
try:
query = f"""
query = """
SELECT id, name, email from user
where email = :email
"""
Expand Down Expand Up @@ -86,7 +86,7 @@ async def register_user(conn: Connection, name: str, email:str, hashed_password:
HTTPException 400: When the DB INSERT fails or the request data is invalid.
"""
try:
query = f"""
query = """
INSERT INTO user(name, email, hashed_password)
values (:name, :email, :hashed_password)
"""
Expand Down
27 changes: 24 additions & 3 deletions App/utils/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from fastapi import Request, FastAPI
from fastapi import Request, FastAPI, status
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import redis.asyncio as aioredis
import uuid
Expand Down Expand Up @@ -51,7 +52,7 @@ async def dispatch(self, request: Request, call_next):
or request.headers.get('x-forwarded-proto') == 'https')

response.set_cookie(self.session_cookie, session_id, max_age=self.max_age, httponly=True,
secure=is_https, samesite='None' if is_https else 'Lax')
secure=is_https, samesite='Lax')
await redis_client.setex(session_id, self.max_age, json.dumps(request.state.session))

else:
Expand All @@ -63,4 +64,24 @@ async def dispatch(self, request: Request, call_next):

return response



# CSRF defense: state-changing requests must carry a custom header.
# A cross-origin page can't add it without passing a CORS preflight, and requests
# without it (e.g. plain <form> POSTs) are rejected here.
CSRF_HEADER = "X-CSRF-Guard"
CSRF_PROTECTED_METHODS = {"POST", "PUT", "PATCH", "DELETE"}


class CSRFHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if request.method in CSRF_PROTECTED_METHODS and CSRF_HEADER not in request.headers:
return JSONResponse(
content={
"error_type": "http",
"status_code": status.HTTP_403_FORBIDDEN,
"title_message": "불편을 드려 죄송합니다",
"detail": "허용되지 않은 요청입니다. 페이지를 새로고침한 뒤 다시 시도해주세요.",
},
status_code=status.HTTP_403_FORBIDDEN,
)
return await call_next(request)
Binary file removed client/public/samples/images/asian_fake_2.JPG
Binary file not shown.
2 changes: 1 addition & 1 deletion client/src/components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const Navbar = ({ variant = 'dark', sessionUser, onLogout, links = [], logoutRed
const handleLogoutClick = async () => {
if (!window.confirm("로그아웃 하시겠습니까?")) return;
try {
await axios.get('/auth/logout');
await axios.post('/auth/logout');
if (onLogout) onLogout();
alert("성공적으로 로그아웃되었습니다.");
navigate(logoutRedirect);
Expand Down
1 change: 1 addition & 0 deletions client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import axios from 'axios';
axios.defaults.withCredentials = true;
axios.defaults.baseURL = '/api';
axios.defaults.headers.common['ngrok-skip-browser-warning'] = 'true';
axios.defaults.headers.common['X-CSRF-Guard'] = '1';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
Expand Down
6 changes: 3 additions & 3 deletions client/src/pages/AnalysisDetailPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ const VERDICT_COPY = {
},
real: {
badge: '실제 얼굴로 보여요',
image: '뚜렷한 위조 흔적이 발견되지 않았어요. 히트맵에서 모델이 본 부위를 확인할 수 있어요.',
video: '뚜렷한 위조 흔적이 발견되지 않았어요. 타임라인에서 구간별 결과를 확인할 수 있어요.',
image: '뚜렷한 위조 흔적이 발견되지 않았어요.',
video: '영상에서 뚜렷한 위조 흔적이 발견되지 않았어요.',
},
unknown: {
badge: '판정할 수 없어요',
Expand Down Expand Up @@ -277,7 +277,7 @@ const AnalysisDetailPage = ({ sessionUser }) => {
<ProbGauge prob={prob} tone={verdictTone} />
<span className={`dg-detail__badge dg-detail__badge--${verdictTone}`}>{VERDICT_COPY[verdictTone].badge}</span>
<p className="dg-detail__desc">{VERDICT_COPY[verdictTone][isVideo ? 'video' : 'image']}</p>
{mediaLoc && (
{mediaLoc && verdictTone !== 'real' && (
<Button variant="primary" className="dg-btn--block dg-detail__xai-btn"
onClick={isVideo ? handleVideoHeatmap : handleImageHeatmap}>
{isVideo ? '타임라인으로 근거 보기' : '히트맵으로 근거 보기'}
Expand Down
30 changes: 29 additions & 1 deletion client/src/pages/VideoAnalysisPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const VideoAnalysisPage = ({ sessionUser, onLogout, setSessionUser }) => {
const [history, setHistory] = useState([]);

const [isCameraOpen, setIsCameraOpen] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [selectedSample, setSelectedSample] = useState(null);

const [modelType, setModelType] = useState('fast');
Expand Down Expand Up @@ -195,6 +196,30 @@ const VideoAnalysisPage = ({ sessionUser, onLogout, setSessionUser }) => {
setSelectedSample(null); // clear the selection when coming in from a path other than a sample
};

// Drag-and-drop upload — not accepted during webcam capture/analysis
const canDrop = !isCameraOpen && !isAnalyzing;
const handleDragOver = (e) => {
e.preventDefault();
if (!canDrop) return;
e.dataTransfer.dropEffect = 'copy';
if (!isDragOver) setIsDragOver(true);
};
const handleDragLeave = (e) => {
if (!e.currentTarget.contains(e.relatedTarget)) setIsDragOver(false);
};
const handleDrop = (e) => {
e.preventDefault();
setIsDragOver(false);
if (!canDrop) return;
const dropped = e.dataTransfer.files?.[0];
if (!dropped) return;
if (!dropped.type.startsWith('video/')) {
alert("동영상 파일만 올릴 수 있어요.");
return;
}
handleFileSelect(dropped);
};

// Convert the sample video to a File, feed it into the existing upload flow, and set the domain automatically
const handleSelectSample = async (sample) => {
try {
Expand Down Expand Up @@ -428,8 +453,11 @@ const VideoAnalysisPage = ({ sessionUser, onLogout, setSessionUser }) => {

<div className="dg-analysis__panes">
<div
className={`dg-analysis__pane dg-analysis__drop${previewUrl ? ' has-preview' : ''}${isCameraOpen ? ' is-camera' : ''}`}
className={`dg-analysis__pane dg-analysis__drop${previewUrl ? ' has-preview' : ''}${isCameraOpen ? ' is-camera' : ''}${isDragOver ? ' is-active' : ''}`}
onClick={() => { if (!previewUrl && !isCameraOpen) document.getElementById('vIn').click(); }}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{isCameraOpen ? (
<WebcamCapture mode="video" onCapture={handleFileSelect} onClose={() => setIsCameraOpen(false)} />
Expand Down
1 change: 0 additions & 1 deletion client/src/pages/analysispage.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import AnalysisWarning from '../components/AnalysisWarning';
// Sample images (the actual files must be placed under public/samples/images/)
const SAMPLE_IMAGES = [
{ name: 'asian_fake_1.JPG', src: '/samples/images/asian_fake_1.JPG', domain: 'asian', label: '동양인 Fake' },
{ name: 'asian_fake_2.JPG', src: '/samples/images/asian_fake_2.JPG', domain: 'asian', label: '동양인 Fake' },
{ name: 'western_fake_1.JPG', src: '/samples/images/western_fake_1.JPG', domain: 'western', label: '서양인 Fake' },
{ name: 'western_fake_2.JPG', src: '/samples/images/western_fake_2.JPG', domain: 'western', label: '서양인 Fake' },
];
Expand Down
Loading