araeyn commited on
Commit
3116fdf
·
1 Parent(s): 6cb8604

added uuid generation and token creation

Browse files

now using token for authentication instead of password and username

Files changed (2) hide show
  1. app.py +91 -60
  2. client.py +30 -13
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import asyncio
2
  import json
3
  import secrets
 
4
  from datetime import datetime
5
  from pathlib import Path
6
 
@@ -94,22 +95,45 @@ def register_user(username: str, password: str):
94
  if username in users:
95
  raise HTTPException(status_code=400, detail="User already exists")
96
  hashed = ph.hash(password)
97
- users[username] = hashed
 
 
 
 
 
 
98
  save_json(USERS_FILE, users)
 
99
 
100
 
101
- def verify_user(username: str, password: str):
 
 
 
 
 
 
 
 
102
  users = load_json(USERS_FILE)
103
  if username not in users:
104
  return False
105
  try:
106
- ph.verify(users[username], password)
107
  return True
108
  except Exception as e:
109
  print(f"Verification error: {e}")
110
  return False
111
 
112
 
 
 
 
 
 
 
 
 
113
  # ---------------------- Glares System ---------------------- #
114
 
115
 
@@ -150,21 +174,25 @@ def update_user_glares(username: str, earnings: float):
150
 
151
  @app.post("/register")
152
  def register(username: str = Form(...), password: str = Form(...)):
153
- register_user(username, password)
154
- return JSONResponse(content={"message": "User registered successfully"})
 
 
155
 
156
 
157
  @app.post("/login")
158
  def login(username: str = Form(...), password: str = Form(...)):
159
- if verify_user(username, password):
160
- return JSONResponse(content={"message": "Login successful"})
 
161
  raise HTTPException(status_code=401, detail="Invalid credentials")
162
 
163
 
164
  @app.get("/glares")
165
- def get_glares(username: str, password: str):
166
- if not verify_user(username, password):
167
- raise HTTPException(status_code=401, detail="Invalid credentials")
 
168
  current = get_updated_glares(username)
169
  return {"username": username, "glares": current}
170
 
@@ -179,11 +207,10 @@ async def coinflip(websocket: WebSocket):
179
  try:
180
  # First message must be auth
181
  auth = await websocket.receive_json()
182
- username = auth.get("username")
183
- password = auth.get("password")
184
-
185
- if not username or not password or not verify_user(username, password):
186
- await websocket.send_json({"error": "Invalid credentials"})
187
  await websocket.close()
188
  return
189
 
@@ -249,11 +276,10 @@ async def roulette(websocket: WebSocket):
249
  try:
250
  # First message must be auth
251
  auth = await websocket.receive_json()
252
- username = auth.get("username")
253
- password = auth.get("password")
254
-
255
- if not username or not password or not verify_user(username, password):
256
- await websocket.send_json({"error": "Invalid credentials"})
257
  await websocket.close()
258
  return
259
 
@@ -439,11 +465,10 @@ async def spinner(websocket: WebSocket):
439
  try:
440
  # First message must be auth
441
  auth = await websocket.receive_json()
442
- username = auth.get("username")
443
- password = auth.get("password")
444
-
445
- if not username or not password or not verify_user(username, password):
446
- await websocket.send_json({"error": "Invalid credentials"})
447
  await websocket.close()
448
  return
449
 
@@ -490,11 +515,10 @@ async def crash(websocket: WebSocket):
490
  try:
491
  # First message must be auth
492
  auth = await websocket.receive_json()
493
- username = auth.get("username")
494
- password = auth.get("password")
495
-
496
- if not username or not password or not verify_user(username, password):
497
- await websocket.send_json({"error": "Invalid credentials"})
498
  await websocket.close()
499
  return
500
 
@@ -583,11 +607,10 @@ async def mines(websocket: WebSocket):
583
  try:
584
  # First message must be auth
585
  auth = await websocket.receive_json()
586
- username = auth.get("username")
587
- password = auth.get("password")
588
-
589
- if not username or not password or not verify_user(username, password):
590
- await websocket.send_json({"error": "Invalid credentials"})
591
  await websocket.close()
592
  return
593
 
@@ -678,11 +701,10 @@ async def tower(websocket: WebSocket):
678
  try:
679
  # First message must be auth
680
  auth = await websocket.receive_json()
681
- username = auth.get("username")
682
- password = auth.get("password")
683
-
684
- if not username or not password or not verify_user(username, password):
685
- await websocket.send_json({"error": "Invalid credentials"})
686
  await websocket.close()
687
  return
688
 
@@ -727,16 +749,27 @@ async def tower(websocket: WebSocket):
727
  if position not in [0, 1, 2, 3]:
728
  await websocket.send_json({"error": "Invalid position"})
729
  continue
730
- if position in safe_positions:
731
- level += 1
732
- multiplier += 1 / 4 * 0.99
733
- safe_positions.remove(position)
734
- await websocket.send_json(
735
- {
736
- "level": level,
737
- "multiplier": round(multiplier, 2),
738
- }
739
- )
 
 
 
 
 
 
 
 
 
 
 
740
  else:
741
  multiplier = 0
742
  break
@@ -773,11 +806,10 @@ async def blackjack(websocket: WebSocket):
773
  try:
774
  # First message must be auth
775
  auth = await websocket.receive_json()
776
- username = auth.get("username")
777
- password = auth.get("password")
778
-
779
- if not username or not password or not verify_user(username, password):
780
- await websocket.send_json({"error": "Invalid credentials"})
781
  await websocket.close()
782
  return
783
 
@@ -883,11 +915,10 @@ async def hilo(websocket: WebSocket):
883
  try:
884
  # First message must be auth
885
  auth = await websocket.receive_json()
886
- username = auth.get("username")
887
- password = auth.get("password")
888
-
889
- if not username or not password or not verify_user(username, password):
890
- await websocket.send_json({"error": "Invalid credentials"})
891
  await websocket.close()
892
  return
893
 
 
1
  import asyncio
2
  import json
3
  import secrets
4
+ import uuid
5
  from datetime import datetime
6
  from pathlib import Path
7
 
 
95
  if username in users:
96
  raise HTTPException(status_code=400, detail="User already exists")
97
  hashed = ph.hash(password)
98
+ user_id = str(uuid.uuid4())
99
+ token = secrets.token_hex(32)
100
+ users[username] = {
101
+ "userId": user_id,
102
+ "password": hashed,
103
+ "token": token,
104
+ }
105
  save_json(USERS_FILE, users)
106
+ return token
107
 
108
 
109
+ def verify_token(token: str):
110
+ users = load_json(USERS_FILE)
111
+ for username, user in users.items():
112
+ if user.get("token") == token:
113
+ return username
114
+ return None
115
+
116
+
117
+ def verify_user_password(username: str, password: str):
118
  users = load_json(USERS_FILE)
119
  if username not in users:
120
  return False
121
  try:
122
+ ph.verify(users[username]["password"], password)
123
  return True
124
  except Exception as e:
125
  print(f"Verification error: {e}")
126
  return False
127
 
128
 
129
+ def get_user_token(username: str):
130
+ users = load_json(USERS_FILE)
131
+ user = users.get(username)
132
+ if user:
133
+ return user.get("token")
134
+ return None
135
+
136
+
137
  # ---------------------- Glares System ---------------------- #
138
 
139
 
 
174
 
175
  @app.post("/register")
176
  def register(username: str = Form(...), password: str = Form(...)):
177
+ token = register_user(username, password)
178
+ return JSONResponse(
179
+ content={"message": "User registered successfully", "token": token}
180
+ )
181
 
182
 
183
  @app.post("/login")
184
  def login(username: str = Form(...), password: str = Form(...)):
185
+ if verify_user_password(username, password):
186
+ token = get_user_token(username)
187
+ return JSONResponse(content={"message": "Login successful", "token": token})
188
  raise HTTPException(status_code=401, detail="Invalid credentials")
189
 
190
 
191
  @app.get("/glares")
192
+ def get_glares(token: str):
193
+ username = verify_token(token)
194
+ if not username:
195
+ raise HTTPException(status_code=401, detail="Invalid token")
196
  current = get_updated_glares(username)
197
  return {"username": username, "glares": current}
198
 
 
207
  try:
208
  # First message must be auth
209
  auth = await websocket.receive_json()
210
+ token = auth.get("token")
211
+ username = verify_token(token)
212
+ if not username:
213
+ await websocket.send_json({"error": "Invalid token"})
 
214
  await websocket.close()
215
  return
216
 
 
276
  try:
277
  # First message must be auth
278
  auth = await websocket.receive_json()
279
+ token = auth.get("token")
280
+ username = verify_token(token)
281
+ if not username:
282
+ await websocket.send_json({"error": "Invalid token"})
 
283
  await websocket.close()
284
  return
285
 
 
465
  try:
466
  # First message must be auth
467
  auth = await websocket.receive_json()
468
+ token = auth.get("token")
469
+ username = verify_token(token)
470
+ if not username:
471
+ await websocket.send_json({"error": "Invalid token"})
 
472
  await websocket.close()
473
  return
474
 
 
515
  try:
516
  # First message must be auth
517
  auth = await websocket.receive_json()
518
+ token = auth.get("token")
519
+ username = verify_token(token)
520
+ if not username:
521
+ await websocket.send_json({"error": "Invalid token"})
 
522
  await websocket.close()
523
  return
524
 
 
607
  try:
608
  # First message must be auth
609
  auth = await websocket.receive_json()
610
+ token = auth.get("token")
611
+ username = verify_token(token)
612
+ if not username:
613
+ await websocket.send_json({"error": "Invalid token"})
 
614
  await websocket.close()
615
  return
616
 
 
701
  try:
702
  # First message must be auth
703
  auth = await websocket.receive_json()
704
+ token = auth.get("token")
705
+ username = verify_token(token)
706
+ if not username:
707
+ await websocket.send_json({"error": "Invalid token"})
 
708
  await websocket.close()
709
  return
710
 
 
749
  if position not in [0, 1, 2, 3]:
750
  await websocket.send_json({"error": "Invalid position"})
751
  continue
752
+ if position == safe_positions[level]:
753
+ if level < 8:
754
+ level += 1
755
+ multiplier += 3 / 4 * 0.99
756
+ safe_positions.remove(position)
757
+ await websocket.send_json(
758
+ {
759
+ "level": level,
760
+ "multiplier": round(multiplier, 2),
761
+ }
762
+ )
763
+ else:
764
+ multiplier += 3 / 4 * 0.99
765
+ await websocket.send_json(
766
+ {
767
+ "level": level,
768
+ "multiplier": round(multiplier, 2),
769
+ "completed": True,
770
+ }
771
+ )
772
+ break
773
  else:
774
  multiplier = 0
775
  break
 
806
  try:
807
  # First message must be auth
808
  auth = await websocket.receive_json()
809
+ token = auth.get("token")
810
+ username = verify_token(token)
811
+ if not username:
812
+ await websocket.send_json({"error": "Invalid token"})
 
813
  await websocket.close()
814
  return
815
 
 
915
  try:
916
  # First message must be auth
917
  auth = await websocket.receive_json()
918
+ token = auth.get("token")
919
+ username = verify_token(token)
920
+ if not username:
921
+ await websocket.send_json({"error": "Invalid token"})
 
922
  await websocket.close()
923
  return
924
 
client.py CHANGED
@@ -24,9 +24,11 @@ else:
24
 
25
  USERNAME = "testuser"
26
  PASSWORD = "testpass"
 
27
 
28
 
29
  async def register_user():
 
30
  async with aiohttp.ClientSession() as session:
31
  data = {"username": USERNAME, "password": PASSWORD}
32
  async with session.post(f"{API_URL}/register", data=data) as resp:
@@ -34,15 +36,24 @@ async def register_user():
34
  if resp.status != 200:
35
  text = await resp.text()
36
  print(f"Register failed (maybe already registered): {text}")
 
 
 
 
 
 
 
 
37
  else:
38
  res = await resp.json()
 
39
  print(f"Register response: {res}")
40
 
41
 
42
  async def play_roulette():
43
  async with websockets.connect(WS_URL_ROULETTE) as websocket:
44
  # Send authentication
45
- auth_msg = {"username": USERNAME, "password": PASSWORD}
46
  await websocket.send(json.dumps(auth_msg))
47
  # Receive welcome message with balance
48
  welcome = await websocket.recv()
@@ -73,8 +84,11 @@ async def play_roulette():
73
  async def play_spinner():
74
  # First get current balance to bet all-in
75
  async with aiohttp.ClientSession() as session:
76
- params = {"username": USERNAME, "password": PASSWORD}
77
- async with session.get(f"{API_URL}/glares", params=params) as resp:
 
 
 
78
  balance_data = await resp.json()
79
  balance = balance_data.get("glares", 0)
80
  print(f"Current balance: {balance}")
@@ -82,7 +96,7 @@ async def play_spinner():
82
  # Now connect to spinner and bet all-in
83
  async with websockets.connect(WS_URL_SPINNER) as websocket:
84
  # Send authentication
85
- auth_msg = {"username": USERNAME, "password": PASSWORD}
86
  await websocket.send(json.dumps(auth_msg))
87
 
88
  # Receive welcome message
@@ -119,8 +133,9 @@ async def play_crash():
119
  """Play the crash game and cash out after 2 seconds"""
120
  # Get balance first
121
  async with aiohttp.ClientSession() as session:
122
- params = {"username": USERNAME, "password": PASSWORD}
123
- async with session.get(f"{API_URL}/glares", params=params) as resp:
 
124
  balance_data = await resp.json()
125
  balance = balance_data.get("glares", 0)
126
  print(f"Current balance before crash: {balance}")
@@ -128,7 +143,7 @@ async def play_crash():
128
  # Connect to crash game
129
  async with websockets.connect(WS_URL_CRASH) as websocket:
130
  # Send authentication
131
- auth_msg = {"username": USERNAME, "password": PASSWORD}
132
  await websocket.send(json.dumps(auth_msg))
133
 
134
  # Receive welcome message
@@ -190,8 +205,9 @@ async def play_mines():
190
  """Play the mines game with random placements and cash out after 5 reveals"""
191
  # Get balance first
192
  async with aiohttp.ClientSession() as session:
193
- params = {"username": USERNAME, "password": PASSWORD}
194
- async with session.get(f"{API_URL}/glares", params=params) as resp:
 
195
  balance_data = await resp.json()
196
  balance = balance_data.get("glares", 0)
197
  print(f"Current balance before mines: {balance}")
@@ -199,7 +215,7 @@ async def play_mines():
199
  # Connect to mines game
200
  async with websockets.connect(WS_URL_MINES) as websocket:
201
  # Send authentication
202
- auth_msg = {"username": USERNAME, "password": PASSWORD}
203
  await websocket.send(json.dumps(auth_msg))
204
 
205
  # Receive welcome message
@@ -270,8 +286,9 @@ async def play_tower():
270
  """Play the tower game with random tile selections and cash out after a random number of levels"""
271
  # Get balance first
272
  async with aiohttp.ClientSession() as session:
273
- params = {"username": USERNAME, "password": PASSWORD}
274
- async with session.get(f"{API_URL}/glares", params=params) as resp:
 
275
  balance_data = await resp.json()
276
  balance = balance_data.get("glares", 0)
277
  print(f"Current balance before tower: {balance}")
@@ -279,7 +296,7 @@ async def play_tower():
279
  # Connect to tower game
280
  async with websockets.connect(WS_URL_TOWER) as websocket:
281
  # Send authentication
282
- auth_msg = {"username": USERNAME, "password": PASSWORD}
283
  await websocket.send(json.dumps(auth_msg))
284
 
285
  # Receive welcome message
 
24
 
25
  USERNAME = "testuser"
26
  PASSWORD = "testpass"
27
+ TOKEN = None
28
 
29
 
30
  async def register_user():
31
+ global TOKEN
32
  async with aiohttp.ClientSession() as session:
33
  data = {"username": USERNAME, "password": PASSWORD}
34
  async with session.post(f"{API_URL}/register", data=data) as resp:
 
36
  if resp.status != 200:
37
  text = await resp.text()
38
  print(f"Register failed (maybe already registered): {text}")
39
+ # Try login if already registered
40
+ async with session.post(f"{API_URL}/login", data=data) as login_resp:
41
+ if login_resp.status == 200:
42
+ res = await login_resp.json()
43
+ TOKEN = res.get("token")
44
+ print(f"Login response: {res}")
45
+ else:
46
+ print(f"Login failed: {await login_resp.text()}")
47
  else:
48
  res = await resp.json()
49
+ TOKEN = res.get("token")
50
  print(f"Register response: {res}")
51
 
52
 
53
  async def play_roulette():
54
  async with websockets.connect(WS_URL_ROULETTE) as websocket:
55
  # Send authentication
56
+ auth_msg = {"token": TOKEN}
57
  await websocket.send(json.dumps(auth_msg))
58
  # Receive welcome message with balance
59
  welcome = await websocket.recv()
 
84
  async def play_spinner():
85
  # First get current balance to bet all-in
86
  async with aiohttp.ClientSession() as session:
87
+ params = {k: v for k, v in {"token": TOKEN}.items() if v is not None}
88
+ filtered_params = {
89
+ k: str(v) for k, v in params.items()
90
+ } # Ensure all values are strings
91
+ async with session.get(f"{API_URL}/glares", params=filtered_params) as resp:
92
  balance_data = await resp.json()
93
  balance = balance_data.get("glares", 0)
94
  print(f"Current balance: {balance}")
 
96
  # Now connect to spinner and bet all-in
97
  async with websockets.connect(WS_URL_SPINNER) as websocket:
98
  # Send authentication
99
+ auth_msg = {"token": TOKEN}
100
  await websocket.send(json.dumps(auth_msg))
101
 
102
  # Receive welcome message
 
133
  """Play the crash game and cash out after 2 seconds"""
134
  # Get balance first
135
  async with aiohttp.ClientSession() as session:
136
+ params = {k: v for k, v in {"token": TOKEN}.items() if v is not None}
137
+ filtered_params = {k: v for k, v in params.items() if v is not None}
138
+ async with session.get(f"{API_URL}/glares", params=filtered_params) as resp:
139
  balance_data = await resp.json()
140
  balance = balance_data.get("glares", 0)
141
  print(f"Current balance before crash: {balance}")
 
143
  # Connect to crash game
144
  async with websockets.connect(WS_URL_CRASH) as websocket:
145
  # Send authentication
146
+ auth_msg = {"token": TOKEN}
147
  await websocket.send(json.dumps(auth_msg))
148
 
149
  # Receive welcome message
 
205
  """Play the mines game with random placements and cash out after 5 reveals"""
206
  # Get balance first
207
  async with aiohttp.ClientSession() as session:
208
+ params = {"token": TOKEN}
209
+ filtered_params = {k: v for k, v in params.items() if v is not None}
210
+ async with session.get(f"{API_URL}/glares", params=filtered_params) as resp:
211
  balance_data = await resp.json()
212
  balance = balance_data.get("glares", 0)
213
  print(f"Current balance before mines: {balance}")
 
215
  # Connect to mines game
216
  async with websockets.connect(WS_URL_MINES) as websocket:
217
  # Send authentication
218
+ auth_msg = {"token": TOKEN}
219
  await websocket.send(json.dumps(auth_msg))
220
 
221
  # Receive welcome message
 
286
  """Play the tower game with random tile selections and cash out after a random number of levels"""
287
  # Get balance first
288
  async with aiohttp.ClientSession() as session:
289
+ params = {"token": TOKEN}
290
+ filtered_params = {k: v for k, v in params.items() if v is not None}
291
+ async with session.get(f"{API_URL}/glares", params=filtered_params) as resp:
292
  balance_data = await resp.json()
293
  balance = balance_data.get("glares", 0)
294
  print(f"Current balance before tower: {balance}")
 
296
  # Connect to tower game
297
  async with websockets.connect(WS_URL_TOWER) as websocket:
298
  # Send authentication
299
+ auth_msg = {"token": TOKEN}
300
  await websocket.send(json.dumps(auth_msg))
301
 
302
  # Receive welcome message