Oviya commited on
Commit
62afd3f
1 Parent(s): fb88498

update communitypost

Browse files
Files changed (2) hide show
  1. pytrade.py +138 -3
  2. signin.py +30 -0
pytrade.py CHANGED
@@ -78,8 +78,11 @@ def _encode_jwt(payload: dict, minutes: Optional[int] = None, days: Optional[int
78
  }
79
  return jwt.encode(to_encode, app.config["JWT_SECRET"], algorithm="HS256")
80
 
81
- def create_access_token(user_id: int, email: str) -> str:
82
- return _encode_jwt({"sub": str(user_id), "email": email, "type": "access"}, minutes=ACCESS_MINUTES)
 
 
 
83
 
84
  def create_refresh_token(user_id: int, email: str) -> str:
85
  return _encode_jwt({"sub": str(user_id), "email": email, "type": "refresh"}, days=REFRESH_DAYS)
@@ -406,7 +409,7 @@ def sign_in():
406
  if not user:
407
  return jsonify({"message": "Invalid email or password"}), 401
408
 
409
- access_token = create_access_token(user_id=user["userId"], email=user["email"])
410
  refresh_token = create_refresh_token(user_id=user["userId"], email=user["email"])
411
 
412
  payload = {
@@ -481,6 +484,138 @@ def logout():
481
  clear_token_cookies(resp)
482
  return resp
483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
  # ------------------------------------------------------------------------------
485
  # Run
486
  # ------------------------------------------------------------------------------
 
78
  }
79
  return jwt.encode(to_encode, app.config["JWT_SECRET"], algorithm="HS256")
80
 
81
+ def create_access_token(user_id: int, email: str, name: Optional[str] = None) -> str:
82
+ payload = {"sub": str(user_id), "email": email, "type": "access"}
83
+ if name:
84
+ payload["name"] = name # optional convenience for UI
85
+ return _encode_jwt(payload, minutes=ACCESS_MINUTES)
86
 
87
  def create_refresh_token(user_id: int, email: str) -> str:
88
  return _encode_jwt({"sub": str(user_id), "email": email, "type": "refresh"}, days=REFRESH_DAYS)
 
409
  if not user:
410
  return jsonify({"message": "Invalid email or password"}), 401
411
 
412
+ access_token = create_access_token(user_id=user["userId"], email=user["email"], name=user["name"])
413
  refresh_token = create_refresh_token(user_id=user["userId"], email=user["email"])
414
 
415
  payload = {
 
484
  clear_token_cookies(resp)
485
  return resp
486
 
487
+
488
+ #community forum to post the data
489
+
490
+ # --- Add this API anywhere below other routes ---
491
+ @app.post("/posts")
492
+ @jwt_required
493
+ def create_community_post():
494
+ """
495
+ TEMP: Open endpoint. Expects JSON:
496
+ { userId?, userName?, title?, category?, tags?, body }
497
+ """
498
+ data = request.get_json(silent=True) or {}
499
+
500
+ user_id = int((data.get("userId") or 0))
501
+ user_name = (data.get("userName") or "").strip() or "Guest"
502
+ title = (data.get("title") or "").strip()
503
+ category = (data.get("category") or "").strip()
504
+ tags = (data.get("tags") or "").strip()
505
+ body = (data.get("body") or "").strip()
506
+
507
+ if not body:
508
+ return jsonify({"message": "body is required"}), 400
509
+
510
+ conn = get_db_connection()
511
+ cursor = None
512
+ try:
513
+ cursor = conn.cursor()
514
+ # Return the new identity in the same statement (more reliable than SCOPE_IDENTITY())
515
+ cursor.execute("""
516
+ INSERT INTO Community (user_id, user_name, title, category, tags, body)
517
+ OUTPUT INSERTED.id
518
+ VALUES (?, ?, ?, ?, ?, ?)
519
+ """, (user_id, user_name, title, category, tags, body))
520
+
521
+ row = cursor.fetchone()
522
+ conn.commit()
523
+
524
+ if not row or row[0] is None:
525
+ return jsonify({"error": "Failed to retrieve new post id"}), 500
526
+
527
+ new_id = int(row[0])
528
+
529
+ return jsonify({
530
+ "id": new_id,
531
+ "message": "Post created",
532
+ "userId": user_id,
533
+ "userName": user_name
534
+ }), 201
535
+ except Exception as e:
536
+ app.logger.exception("create_community_post failed")
537
+ return jsonify({"error": str(e)}), 500
538
+ finally:
539
+ try:
540
+ if cursor: cursor.close()
541
+ except:
542
+ pass
543
+ conn.close()
544
+
545
+
546
+ @app.get("/posts")
547
+ def list_community_posts():
548
+ """
549
+ List community posts (public). Supports paging:
550
+ GET /posts?limit=50&offset=0
551
+ Returns: { total, offset, limit, count, results: Post[] }
552
+ """
553
+ limit_raw = request.args.get("limit", "50")
554
+ offset_raw = request.args.get("offset", "0")
555
+ try:
556
+ limit = max(1, min(200, int(limit_raw)))
557
+ except Exception:
558
+ limit = 50
559
+ try:
560
+ offset = max(0, int(offset_raw))
561
+ except Exception:
562
+ offset = 0
563
+
564
+ conn = get_db_connection()
565
+ cur = None
566
+ try:
567
+ cur = conn.cursor()
568
+ # data page
569
+ cur.execute("""
570
+ SELECT
571
+ id,
572
+ user_id AS userId,
573
+ user_name AS userName,
574
+ title,
575
+ category,
576
+ tags,
577
+ body,
578
+ created_at AS createdAt
579
+ FROM Community
580
+ ORDER BY created_at DESC
581
+ OFFSET ? ROWS FETCH NEXT ? ROWS ONLY
582
+ """, (offset, limit))
583
+ rows = cur.fetchall()
584
+
585
+ posts = [
586
+ {
587
+ "id": int(r[0]),
588
+ "userId": int(r[1]),
589
+ "userName": r[2],
590
+ "title": r[3],
591
+ "category": r[4],
592
+ "tags": r[5],
593
+ "body": r[6],
594
+ "createdAt": r[7].isoformat() if hasattr(r[7], "isoformat") else r[7],
595
+ }
596
+ for r in rows
597
+ ]
598
+
599
+ # total count
600
+ cur.execute("SELECT COUNT(*) FROM Community")
601
+ total = int(cur.fetchone()[0])
602
+
603
+ return jsonify({
604
+ "total": total,
605
+ "offset": offset,
606
+ "limit": limit,
607
+ "count": len(posts),
608
+ "results": posts
609
+ }), 200
610
+ except Exception as e:
611
+ app.logger.exception("list_community_posts failed")
612
+ return jsonify({"error": str(e)}), 500
613
+ finally:
614
+ try:
615
+ if cur: cur.close()
616
+ except:
617
+ pass
618
+ conn.close()
619
  # ------------------------------------------------------------------------------
620
  # Run
621
  # ------------------------------------------------------------------------------
signin.py CHANGED
@@ -55,3 +55,33 @@ def ensure_user_table_exists():
55
  try: cur.close()
56
  except: pass
57
  conn.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  try: cur.close()
56
  except: pass
57
  conn.close()
58
+
59
+
60
+ # --- Add below existing ensure_user_table_exists() call ---
61
+ def ensure_community_table_exists() -> None:
62
+ conn = get_db_connection()
63
+ try:
64
+ cursor = conn.cursor()
65
+ cursor.execute("""
66
+ IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Community' AND xtype='U')
67
+ BEGIN
68
+ CREATE TABLE Community (
69
+ id INT IDENTITY(1,1) PRIMARY KEY,
70
+ user_id INT NOT NULL,
71
+ user_name NVARCHAR(200) NOT NULL,
72
+ title NVARCHAR(300) NULL,
73
+ category NVARCHAR(100) NULL,
74
+ tags NVARCHAR(1000) NULL,
75
+ body NVARCHAR(MAX) NOT NULL,
76
+ created_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
77
+ );
78
+ CREATE INDEX IX_Community_UserId ON Community(user_id);
79
+ CREATE INDEX IX_Community_CreatedAt ON Community(created_at DESC);
80
+ END
81
+ """)
82
+ conn.commit()
83
+ finally:
84
+ try: cursor.close()
85
+ except: pass
86
+ conn.close()
87
+