-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
250 lines (216 loc) · 8.67 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
from fastapi import FastAPI, HTTPException, Header
from pydantic import BaseModel, Field
from bson import ObjectId
import bcrypt
import jwt
import datetime
from typing import List
import os
import dotenv
from fastapi.middleware.cors import CORSMiddleware
import motor.motor_asyncio
import logging
import heapq
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[
logging.FileHandler('system.log'), # Log messages to a file
logging.StreamHandler() # Log messages to the console
]
)
# Load environment variables
dotenv.load_dotenv()
MONGO_URI = os.environ.get("MONGO_URI")
SECRET_KEY = os.environ.get("SECRET_KEY")
ALGORITHM = os.environ.get("ALGORITHM")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust this to the specific domain of your frontend
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# MongoDB Connection using Motor (asynchronous)
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
db = client.get_database("leetcode_twitter")
users_collection = db.get_collection("users")
time_delta_collection = db.get_collection("time_delta")
# Helper Functions
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
def create_jwt(user_id: str) -> str:
payload = {
"user_id": user_id,
}
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
return token
def verify_jwt(token: str) -> dict:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token has expired.")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token.")
async def decrement_time_delta():
time_delta_doc = await time_delta_collection.find_one({})
if not time_delta_doc:
raise HTTPException(status_code=500, detail="Time delta document not found.")
new_time_delta = time_delta_doc['time'] - 0.01
await time_delta_collection.update_one({}, {"$set": {"time": new_time_delta}})
return new_time_delta
# Models
class PyObjectId(ObjectId):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v, field=None):
if not ObjectId.is_valid(v):
raise ValueError('Invalid ObjectId')
return ObjectId(v)
@classmethod
def __get_pydantic_json_schema__(cls, schema, model):
schema.update(type='string')
return schema
class UserOutModel(BaseModel):
id: PyObjectId = Field(alias="_id")
username: str
followers: List[str] = []
following: List[str] = []
tweets: List[dict] = []
class Config:
json_encoders = {ObjectId: str}
class SignupModel(BaseModel):
username: str = Field(..., max_length=50)
password: str = Field(..., min_length=8)
class LoginModel(BaseModel):
username: str
password: str
class TweetModel(BaseModel):
content: str = Field(..., max_length=280)
class UserModel(BaseModel):
username: str
hashed_password: str
followers: List[str] = []
following: List[str] = []
tweets: List[dict] = []
# Endpoints
@app.post("/signup")
async def signup(user: SignupModel):
if await users_collection.find_one({"username": user.username}):
raise HTTPException(status_code=400, detail="Username is already taken.")
hashed_password = hash_password(user.password)
user_data = {
"username": user.username,
"hashed_password": hashed_password,
"followers": [],
"following": [],
"tweets": []
}
result = await users_collection.insert_one(user_data)
await decrement_time_delta()
return {"message": "User registered successfully", "user_id": str(result.inserted_id)}
@app.post("/login")
async def login(credentials: LoginModel):
user = await users_collection.find_one({"username": credentials.username})
if not user or not verify_password(credentials.password, user["hashed_password"]):
raise HTTPException(status_code=401, detail="Invalid username or password.")
token = create_jwt(str(user["_id"]))
await decrement_time_delta()
return {"message": "Login successful", "token": token}
@app.get("/profile", response_model=UserOutModel)
async def get_profile(token: str = Header(None)):
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)}, {"hashed_password": 0})
if not user:
raise HTTPException(status_code=404, detail="User not found.")
return user
@app.get("/search")
async def search_users(prefix: str, token: str = Header(None)):
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)})
users = await users_collection.find({"username": {"$regex": f"^{prefix}", "$options": "i"}}).to_list(100)
results = []
for u in users:
results.append({
"username": u["username"],
"is_following": u["username"] in user["following"]
})
return results
@app.post("/tweet")
async def post_tweet(tweet: TweetModel, token: str = Header(None)):
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)})
time_delta = await decrement_time_delta()
timestamp = datetime.datetime.utcnow().isoformat()
tweet_data = {
"time_delta": time_delta,
"timestamp": timestamp,
"content": tweet.content
}
await users_collection.update_one({"_id": ObjectId(user_id)}, {"$push": {"tweets": tweet_data}})
return {"message": "Tweet posted successfully."}
@app.post("/follow")
async def follow_user(data: dict, token: str = Header(None)):
target_username = data.get("target_username")
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)})
target_user = await users_collection.find_one({"username": target_username})
if not target_user:
raise HTTPException(status_code=404, detail="User not found.")
if target_username in user["following"]:
raise HTTPException(status_code=400, detail="Already following this user.")
await users_collection.update_one({"_id": ObjectId(user_id)}, {"$push": {"following": target_username}})
await users_collection.update_one({"username": target_username}, {"$push": {"followers": user["username"]}})
await decrement_time_delta()
return {"message": "User followed successfully."}
@app.post("/unfollow")
async def unfollow_user(data: dict, token: str = Header(None)):
target_username = data.get("target_username")
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)})
if target_username not in user["following"]:
raise HTTPException(status_code=400, detail="You are not following this user.")
await users_collection.update_one({"_id": ObjectId(user_id)}, {"$pull": {"following": target_username}})
await users_collection.update_one({"username": target_username}, {"$pull": {"followers": user["username"]}})
await decrement_time_delta()
return {"message": "User unfollowed successfully."}
@app.get("/feed")
async def get_feed(token: str = Header(None)):
payload = verify_jwt(token)
user_id = payload.get("user_id")
user = await users_collection.find_one({"_id": ObjectId(user_id)})
following = user["following"]
following.append(user["username"]) # Include the user themselves
# Fetch tweets from users being followed
tweets = []
q = []
for username in following:
user_doc = await users_collection.find_one({"username": username})
if user_doc and "tweets" in user_doc:
for tweet in user_doc["tweets"]:
tweet_with_username = {
"username": username,
"content": tweet["content"],
"time_delta": tweet["time_delta"],
"timestamp": tweet["timestamp"]
}
heapq.heappush(q, (tweet_with_username["time_delta"], tweet_with_username))
while q and len(tweets) < 10:
_, tweet = heapq.heappop(q)
tweets.append(tweet)
return tweets
@app.get("/")
async def root():
return {"message": "LeetCode API is running!"}