ChandimaPrabath commited on
Commit
9c055f7
·
verified ·
1 Parent(s): dd02fae

Upload services.py

Browse files
Files changed (1) hide show
  1. services.py +53 -0
services.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services.py
2
+ from fastapi import FastAPI, HTTPException
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ from typing import List
6
+ import json
7
+
8
+ app = FastAPI()
9
+
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=["*"], # Allow all origins; use specific domains for security
13
+ allow_credentials=True,
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ # Temporary user dictionary for storing credentials
19
+ USERS = {
20
+ "user1": "password1",
21
+ "user2": "password2",
22
+ "alice": "password3",
23
+ "bob": "password4",
24
+ }
25
+
26
+ class User(BaseModel):
27
+ username: str
28
+ password: str
29
+
30
+ @app.post("/register")
31
+ async def register_user(user: User):
32
+ """Register a new user."""
33
+ if user.username in USERS:
34
+ raise HTTPException(status_code=400, detail="Username already exists")
35
+ USERS[user.username] = user.password
36
+ return {"message": "User registered successfully"}
37
+
38
+ @app.post("/login")
39
+ async def login_user(user: User):
40
+ """Authenticate a user."""
41
+ if user.username not in USERS or USERS[user.username] != user.password:
42
+ raise HTTPException(status_code=401, detail="Invalid credentials")
43
+ return {"message": "Login successful"}
44
+
45
+ @app.get("/search")
46
+ async def search_users(query: str) -> List[str]:
47
+ """Search for users by username."""
48
+ matching_users = [username for username in USERS if query.lower() in username.lower()]
49
+
50
+ if not matching_users:
51
+ raise HTTPException(status_code=404, detail="No users found matching the query")
52
+
53
+ return matching_users