rohanshaw commited on
Commit
3b97cd9
·
verified ·
1 Parent(s): 1a8351b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -29
app.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import logging
3
  import firebase_admin.messaging
4
  import requests
 
5
  from fastapi import FastAPI, HTTPException, status, Body
6
  from fastapi.middleware.cors import CORSMiddleware
7
  from pydantic import BaseModel, Field, EmailStr
@@ -21,6 +22,7 @@ if not MONGODB_URI:
21
  # --- Configuration ---
22
  DATABASE_NAME = "userAuthDB"
23
  COLLECTION_NAME = "users"
 
24
 
25
  # --- Logging Setup ---
26
  logging.basicConfig(level=logging.INFO)
@@ -31,9 +33,9 @@ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
31
 
32
  # --- FastAPI App Initialization ---
33
  app = FastAPI(
34
- title="User Authentication API",
35
- description="API for user signup and login for WhereIParked.",
36
- version="1.0.0",
37
  )
38
 
39
  # --- CORS Configuration ---
@@ -129,6 +131,9 @@ class TokenModel(BaseModel):
129
  email: str
130
  token: str
131
 
 
 
 
132
  # --- Helper Functions ---
133
  def verify_password(plain_password, hashed_password):
134
  return pwd_context.verify(plain_password, hashed_password)
@@ -166,11 +171,11 @@ FCM_SERVER_KEY = os.getenv("FCM_SERVER_KEY")
166
 
167
  def send_push(token: str, title: str, body: str):
168
  message = firebase_admin.messaging.Message(
169
- notification=firebase_admin.messaging.Notification(
170
- title=title,
171
- body=body,
172
- image="/icon.png"
173
- ),
174
  data={
175
  "title": title,
176
  "body": body
@@ -182,10 +187,7 @@ def send_push(token: str, title: str, body: str):
182
 
183
  print('Successfully sent message:', response)
184
 
185
- async def send_user_push(email: str, title: str, body: str):
186
- user = await db.users.find_one({"email": email})
187
- if user and "fcm_token" in user:
188
- send_push(user["fcm_token"], title, body)
189
 
190
 
191
  # --- API Endpoints ---
@@ -254,38 +256,41 @@ async def login(login_data: UserLogin = Body(...)):
254
 
255
  @app.post("/api/save-token")
256
  async def save_token(token_model: TokenModel):
257
- db.users.update_one(
258
- {"email": token_model.email},
259
- {"$set": {"fcm_token": token_model.token}}
260
- )
 
 
 
261
  return {"message": "Token saved"}
262
 
263
-
264
  @app.post("/api/parked")
265
- async def user_parked(email: str):
266
- await send_user_push(email,"WhereIParked", "You parked your car. Timer started!")
267
  return {"message": "Notification sent"}
268
 
 
269
  @app.post("/api/clear-location")
270
- async def user_cleared(email: str):
271
- await send_user_push(email, "WhereIParked", "Parking location cleared. Safe drive!")
272
  return {"message": "Notification sent"}
273
 
274
  @app.post("/api/park-duration")
275
- async def park_duration(email: str):
276
- await send_user_push(email, "Reminder", "You’ve been parked for over 60 minutes!")
277
  return {"message": "Notification sent"}
278
 
279
  @app.post("/admin/push")
280
- async def admin_push(title: str, body: str):
281
- users = await db.users.find().to_list(length=None)
282
- for user in users:
283
- if "fcm_token" in user and user["fcm_token"]:
284
- send_push(user["fcm_token"], title, body)
285
  return {"message": "Notifications sent"}
286
 
287
 
 
288
  @app.get("/", status_code=status.HTTP_200_OK)
289
  async def read_root():
290
  """Root endpoint to check if the API is running."""
291
- return {"message": "Authentication API is running!"}
 
2
  import logging
3
  import firebase_admin.messaging
4
  import requests
5
+ import datetime
6
  from fastapi import FastAPI, HTTPException, status, Body
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from pydantic import BaseModel, Field, EmailStr
 
22
  # --- Configuration ---
23
  DATABASE_NAME = "userAuthDB"
24
  COLLECTION_NAME = "users"
25
+ TOKEN_COLLECTION_NAME = "fcmtokens"
26
 
27
  # --- Logging Setup ---
28
  logging.basicConfig(level=logging.INFO)
 
33
 
34
  # --- FastAPI App Initialization ---
35
  app = FastAPI(
36
+ title="Backend API",
37
+ description="API for WhereIParked Backend OPerations.",
38
+ version="1.5.0",
39
  )
40
 
41
  # --- CORS Configuration ---
 
131
  email: str
132
  token: str
133
 
134
+ class InAppEventNotification(BaseModel):
135
+ token: str
136
+
137
  # --- Helper Functions ---
138
  def verify_password(plain_password, hashed_password):
139
  return pwd_context.verify(plain_password, hashed_password)
 
171
 
172
  def send_push(token: str, title: str, body: str):
173
  message = firebase_admin.messaging.Message(
174
+ # notification=firebase_admin.messaging.Notification(
175
+ # title=title,
176
+ # body=body,
177
+ # image="./icon.png"
178
+ # ),
179
  data={
180
  "title": title,
181
  "body": body
 
187
 
188
  print('Successfully sent message:', response)
189
 
190
+ return response
 
 
 
191
 
192
 
193
  # --- API Endpoints ---
 
256
 
257
  @app.post("/api/save-token")
258
  async def save_token(token_model: TokenModel):
259
+ existing = await db.fcmtokens.find_one({"token": token_model.token})
260
+ if not existing:
261
+ await db.fcmtokens.insert_one({
262
+ "email": token_model.email,
263
+ "token": token_model.token,
264
+ "createdAt": datetime.datetime.utcnow()
265
+ })
266
  return {"message": "Token saved"}
267
 
 
268
  @app.post("/api/parked")
269
+ async def user_parked(requestBody: InAppEventNotification = Body(...)):
270
+ send_push(requestBody.token, "WhereIParked", "You parked your car. Timer started!")
271
  return {"message": "Notification sent"}
272
 
273
+
274
  @app.post("/api/clear-location")
275
+ async def user_cleared(requestBody: InAppEventNotification = Body(...)):
276
+ send_push(requestBody.token, "WhereIParked", "Parking location cleared. Safe drive!")
277
  return {"message": "Notification sent"}
278
 
279
  @app.post("/api/park-duration")
280
+ async def park_duration(requestBody: InAppEventNotification = Body(...), duration = str):
281
+ send_push(requestBody.token, "Reminder", "You’ve been parked for over " + duration + " minutes!")
282
  return {"message": "Notification sent"}
283
 
284
  @app.post("/admin/push")
285
+ async def admin_push(title: str = Body(...), body: str = Body(...)):
286
+ tokens = await db.fcmtokens.find().to_list(length=None)
287
+ for token_entry in tokens:
288
+ send_push(token_entry["token"], title, body)
 
289
  return {"message": "Notifications sent"}
290
 
291
 
292
+
293
  @app.get("/", status_code=status.HTTP_200_OK)
294
  async def read_root():
295
  """Root endpoint to check if the API is running."""
296
+ return {"message": "Authentication API is running!"}