vumichien commited on
Commit
460e51f
·
1 Parent(s): edf9ade

simple authen

Browse files
Files changed (6) hide show
  1. auth.py +3 -3
  2. config.py +4 -0
  3. routes/auth.py +0 -17
  4. routes/health.py +3 -38
  5. routes/predict.py +12 -8
  6. simple_auth.py +34 -0
auth.py CHANGED
@@ -25,10 +25,10 @@ def get_user(db, username: str):
25
  def authenticate_user(fake_db, username: str, password: str):
26
  user = get_user(fake_db, username)
27
  if not user:
28
- return False
29
  if not verify_password(password, user.hashed_password):
30
- return False
31
- return user
32
 
33
  def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
34
  to_encode = data.copy()
 
25
  def authenticate_user(fake_db, username: str, password: str):
26
  user = get_user(fake_db, username)
27
  if not user:
28
+ return None
29
  if not verify_password(password, user.hashed_password):
30
+ return None
31
+ return user # Return the user object, not a boolean
32
 
33
  def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
34
  to_encode = data.copy()
config.py CHANGED
@@ -5,6 +5,10 @@ SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
5
  ALGORITHM = "HS256"
6
  ACCESS_TOKEN_EXPIRE_HOURS = 24
7
 
 
 
 
 
8
  # Paths
9
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
10
  DATA_DIR = os.path.join(BASE_DIR, "data")
 
5
  ALGORITHM = "HS256"
6
  ACCESS_TOKEN_EXPIRE_HOURS = 24
7
 
8
+ # Simple API Key (for HF Spaces)
9
+ API_KEY = "meisai-api-key-2025"
10
+ API_KEY_NAME = "X-API-KEY"
11
+
12
  # Paths
13
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
14
  DATA_DIR = os.path.join(BASE_DIR, "data")
routes/auth.py CHANGED
@@ -37,20 +37,3 @@ async def register_user(user_data: UserCreate):
37
  if not success:
38
  raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message)
39
  return {"message": message}
40
-
41
-
42
- @router.get("/generate-test-token/{username}")
43
- async def generate_test_token(username: str):
44
- """
45
- Generate a test token for a user without requiring password
46
- (For testing only, should be disabled in production)
47
- """
48
- users = get_users()
49
- if username not in users:
50
- raise HTTPException(status_code=404, detail="User not found")
51
-
52
- access_token_expires = timedelta(hours=ACCESS_TOKEN_EXPIRE_HOURS)
53
- access_token = create_access_token(
54
- data={"sub": username}, expires_delta=access_token_expires
55
- )
56
- return {"access_token": access_token, "token_type": "bearer", "username": username}
 
37
  if not success:
38
  raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message)
39
  return {"message": message}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
routes/health.py CHANGED
@@ -1,9 +1,5 @@
1
- from fastapi import APIRouter, Depends, Header, Request
2
- from auth import get_current_user
3
- from models import User
4
- import time
5
- import jwt
6
- from config import SECRET_KEY, ALGORITHM
7
 
8
  router = APIRouter()
9
 
@@ -16,7 +12,7 @@ async def health_check():
16
 
17
 
18
  @router.get("/auth-check")
19
- async def auth_check(current_user: User = Depends(get_current_user)):
20
  """
21
  Debug endpoint to verify authentication is working
22
  """
@@ -25,34 +21,3 @@ async def auth_check(current_user: User = Depends(get_current_user)):
25
  "username": current_user.username,
26
  "message": "Authentication successful",
27
  }
28
-
29
-
30
- @router.get("/debug-auth")
31
- async def debug_auth(request: Request, authorization: str = Header(None)):
32
- """
33
- Debug endpoint to manually inspect the authorization header and token
34
- """
35
- headers = dict(request.headers)
36
- auth_header = headers.get("authorization", "Not found")
37
-
38
- token_info = {"valid": False, "error": None, "payload": None}
39
-
40
- if authorization and authorization.startswith("Bearer "):
41
- token = authorization.replace("Bearer ", "")
42
- try:
43
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
44
- token_info["valid"] = True
45
- token_info["payload"] = payload
46
- except Exception as e:
47
- token_info["error"] = str(e)
48
-
49
- return {
50
- "headers": headers,
51
- "auth_header": auth_header,
52
- "token_info": token_info,
53
- "host_info": {
54
- "url": str(request.url),
55
- "base_url": str(request.base_url),
56
- "method": request.method,
57
- },
58
- }
 
1
+ from fastapi import APIRouter, Depends
2
+ from simple_auth import get_current_user_from_api_key
 
 
 
 
3
 
4
  router = APIRouter()
5
 
 
12
 
13
 
14
  @router.get("/auth-check")
15
+ async def auth_check(current_user=Depends(get_current_user_from_api_key)):
16
  """
17
  Debug endpoint to verify authentication is working
18
  """
 
21
  "username": current_user.username,
22
  "message": "Authentication successful",
23
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
routes/predict.py CHANGED
@@ -5,6 +5,7 @@ from pathlib import Path
5
  from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Body
6
  from fastapi.responses import FileResponse
7
  from auth import get_current_user
 
8
  from services.sentence_transformer_service import SentenceTransformerService, sentence_transformer_service
9
  from data_lib.input_name_data import InputNameData
10
  from data_lib.base_name_data import COL_NAME_SENTENCE
@@ -23,14 +24,17 @@ import traceback
23
 
24
  router = APIRouter()
25
 
 
26
  @router.post("/predict")
27
  async def predict(
28
- current_user=Depends(get_current_user),
29
  file: UploadFile = File(...),
30
- sentence_service: SentenceTransformerService = Depends(lambda: sentence_transformer_service)
 
 
31
  ):
32
  """
33
- Process an input CSV file and return standardized names (requires authentication)
34
  """
35
  if not file.filename.endswith(".csv"):
36
  raise HTTPException(status_code=400, detail="Only CSV files are supported")
@@ -116,13 +120,13 @@ async def predict(
116
  @router.post("/embeddings")
117
  async def create_embeddings(
118
  request: EmbeddingRequest,
119
- current_user=Depends(get_current_user),
120
  sentence_service: SentenceTransformerService = Depends(
121
  lambda: sentence_transformer_service
122
  ),
123
  ):
124
  """
125
- Create embeddings for a list of input sentences (requires authentication)
126
  """
127
  try:
128
  start_time = time.time()
@@ -143,13 +147,13 @@ async def create_embeddings(
143
  @router.post("/predict-raw", response_model=PredictRawResponse)
144
  async def predict_raw(
145
  request: PredictRawRequest,
146
- current_user=Depends(get_current_user),
147
  sentence_service: SentenceTransformerService = Depends(
148
  lambda: sentence_transformer_service
149
  ),
150
  ):
151
  """
152
- Process raw input records and return standardized names (requires authentication)
153
  """
154
  try:
155
  # Convert input records to DataFrame
@@ -212,7 +216,7 @@ async def predict_raw(
212
  print(f"Error mapping standard names: {e}")
213
  traceback.print_exc()
214
  raise HTTPException(status_code=500, detail=str(e))
215
-
216
  important_columns = ['確定', '標準科目', '標準項目名', '基準名称類似度']
217
  for column in important_columns:
218
  if column not in df_predicted.columns:
 
5
  from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Body
6
  from fastapi.responses import FileResponse
7
  from auth import get_current_user
8
+ from simple_auth import get_current_user_from_api_key
9
  from services.sentence_transformer_service import SentenceTransformerService, sentence_transformer_service
10
  from data_lib.input_name_data import InputNameData
11
  from data_lib.base_name_data import COL_NAME_SENTENCE
 
24
 
25
  router = APIRouter()
26
 
27
+
28
  @router.post("/predict")
29
  async def predict(
30
+ current_user=Depends(get_current_user_from_api_key),
31
  file: UploadFile = File(...),
32
+ sentence_service: SentenceTransformerService = Depends(
33
+ lambda: sentence_transformer_service
34
+ ),
35
  ):
36
  """
37
+ Process an input CSV file and return standardized names (requires API Key authentication)
38
  """
39
  if not file.filename.endswith(".csv"):
40
  raise HTTPException(status_code=400, detail="Only CSV files are supported")
 
120
  @router.post("/embeddings")
121
  async def create_embeddings(
122
  request: EmbeddingRequest,
123
+ current_user=Depends(get_current_user_from_api_key),
124
  sentence_service: SentenceTransformerService = Depends(
125
  lambda: sentence_transformer_service
126
  ),
127
  ):
128
  """
129
+ Create embeddings for a list of input sentences (requires API Key authentication)
130
  """
131
  try:
132
  start_time = time.time()
 
147
  @router.post("/predict-raw", response_model=PredictRawResponse)
148
  async def predict_raw(
149
  request: PredictRawRequest,
150
+ current_user=Depends(get_current_user_from_api_key),
151
  sentence_service: SentenceTransformerService = Depends(
152
  lambda: sentence_transformer_service
153
  ),
154
  ):
155
  """
156
+ Process raw input records and return standardized names (requires API Key authentication)
157
  """
158
  try:
159
  # Convert input records to DataFrame
 
216
  print(f"Error mapping standard names: {e}")
217
  traceback.print_exc()
218
  raise HTTPException(status_code=500, detail=str(e))
219
+
220
  important_columns = ['確定', '標準科目', '標準項目名', '基準名称類似度']
221
  for column in important_columns:
222
  if column not in df_predicted.columns:
simple_auth.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Security, HTTPException, status, Depends
2
+ from fastapi.security.api_key import APIKeyHeader
3
+ from config import API_KEY, API_KEY_NAME
4
+ from typing import Optional
5
+
6
+ # Define the API key header
7
+ api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
8
+
9
+
10
+ async def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
11
+ """
12
+ Validate API key from header
13
+ """
14
+ if api_key_header == API_KEY:
15
+ return api_key_header
16
+ raise HTTPException(
17
+ status_code=status.HTTP_401_UNAUTHORIZED,
18
+ detail="Invalid API Key",
19
+ )
20
+
21
+
22
+ # Simple function to get a dummy user for API key auth
23
+ async def get_current_user_from_api_key(api_key: str = Depends(get_api_key)):
24
+ """
25
+ Return a dummy user for API key authentication
26
+ """
27
+ # This provides a compatible interface with the JWT auth
28
+ return SimpleUser(username="api_user", disabled=False)
29
+
30
+
31
+ class SimpleUser:
32
+ def __init__(self, username: str, disabled: bool = False):
33
+ self.username = username
34
+ self.disabled = disabled