MCPcopy Create free account
hub / github.com/TextGeneratorio/text-generator.io / api_login

Function api_login

main.py:1078–1152  ·  view source on GitHub ↗

Login endpoint with fallback to in-memory storage

(request: Request, email: str = Form(...), password: str = Form(...), db: Session = Depends(get_db))

Source from the content-addressed store, hash-verified

1076
1077@app.post("/api/login")
1078async def api_login(request: Request, email: str = Form(...), password: str = Form(...), db: Session = Depends(get_db)):
1079 """Login endpoint with fallback to in-memory storage"""
1080 logger.info(f"Login attempt for {email}, USE_POSTGRES={USE_POSTGRES}")
1081
1082 if USE_POSTGRES:
1083 logger.info("Using PostgreSQL login")
1084 try:
1085 user = login_or_create_user(email, password, db)
1086 set_session_for_user(user)
1087
1088 # Ensure user has a valid Stripe customer
1089 valid_stripe_id = validate_stripe_customer(user.stripe_id, email) if user.stripe_id else None
1090 if not valid_stripe_id:
1091 logger.info(f"Creating/updating Stripe customer for user {email}")
1092 stripe_id = get_or_create_stripe_customer(email, user.id)
1093 if stripe_id:
1094 user.stripe_id = stripe_id
1095 db.commit()
1096 db.refresh(user)
1097 else:
1098 logger.error(f"Failed to create Stripe customer for user {email}")
1099 elif valid_stripe_id != user.stripe_id:
1100 # Update stored customer ID if we found a different valid one
1101 logger.info(f"Updating Stripe customer ID for user {email} from {user.stripe_id} to {valid_stripe_id}")
1102 user.stripe_id = valid_stripe_id
1103 db.commit()
1104 db.refresh(user)
1105
1106 # Check subscription status
1107 subscription_item_id = get_subscription_item_id_for_user_email(user.email)
1108 user.is_subscribed = subscription_item_id is not None
1109
1110 # Set session_secret cookie
1111 response = JSONResponse(user.to_dict())
1112 response.set_cookie(
1113 key="session_secret",
1114 value=user.secret,
1115 httponly=True,
1116 secure=False, # Set to True in production with HTTPS
1117 samesite="lax",
1118 path="/",
1119 )
1120 return response
1121 except HTTPException:
1122 raise
1123 except Exception as e:
1124 logger.error(f"PostgreSQL login error: {e}")
1125 raise HTTPException(status_code=401, detail="Invalid email or password")
1126 else:
1127 # Fallback to simple in-memory authentication
1128 logger.info("Using in-memory login")
1129 if email in test_users and test_users[email]["password"] == password:
1130 session_secret = random_string(32)
1131 user_data = {
1132 "id": test_users[email]["id"],
1133 "email": email,
1134 "secret": session_secret,
1135 "is_subscribed": False,

Callers

nothing calls this directly

Calls 7

login_or_create_userFunction · 0.90
set_session_for_userFunction · 0.90
validate_stripe_customerFunction · 0.90
random_stringFunction · 0.90
to_dictMethod · 0.45

Tested by

no test coverage detected