-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
206 lines (174 loc) · 6.51 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
import os
import json
import aiomysql
from robyn import Robyn
os.environ["ROBYN_URL"] = "0.0.0.0"
app = Robyn(__file__)
pool = None
@app.startup_handler
async def startup_handler():
# Read configuration from environment variables
db_user = os.getenv("DB_USER", "username")
db_password = os.getenv("DB_PASSWORD", "password")
db_host = os.getenv("DB_HOST", "Configure me first, moron!")
db_name = os.getenv("DB_NAME", "license_db")
db_port = int(os.getenv("DB_PORT", "3306"))
if os.getenv("LOG_LEVEL") == "DEBUG":
debug = True
global pool
pool = await aiomysql.create_pool(
host=db_host, port=db_port,
user=db_user, password=db_password,
db=db_name
)
print("Database connected")
@app.shutdown_handler
async def shutdown_handler():
global pool
pool.close()
await pool.wait_closed()
@app.post("/")
async def check_license(request):
if os.getenv("LOG_LEVEL").lower() == "debug":
debug = True
else:
debug = False
try:
# Extract the license_key from the JSON payload
data = json.loads(request.body)
license_key = data.get("license_key")
headers_to_check = ["X-Forwarded-For", "Remote-Addr", "CF-Connecting-IP"]
ip_address = None
for header in headers_to_check:
ip_address = request.headers.get(header)
if ip_address:
# If X-Forwarded-For contains multiple IPs (due to multiple proxies), take the first one
if header == "X-Forwarded-For" and "," in ip_address:
ip_address = ip_address.split(",")[0].strip()
break
# If none of the headers provide the IP, use Robyn's method
if not ip_address:
ip_address = request.ip_addr
# Input validation
if not license_key or not ip_address:
return {"error": "Invalid input"}, 400
# Query to get the IP field for the given license_key
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT ip FROM license_check WHERE license=%s",
(license_key,)
)
result = await cur.fetchone()
# If there's a result and the extracted IP is in the list of IPs for that license
if result and ip_address in result[0].split(','):
valid = True
else:
valid = False
if debug:
print(f"IP Address: {ip_address}")
print(f"License Key: {license_key}")
print(f"Query Result: {valid}")
if valid:
if debug:
print("License verified")
response_data = {"status": "success", "message": "License verified."}
return json.dumps(response_data)
else:
if debug:
print("License not found or IP mismatch")
response_data = {"status": "failure", "message": "License not found or IP mismatch."}
return json.dumps(response_data)
except Exception as e:
import traceback
traceback.print_exc()
print(f"Error occurred: {e}")
return {"error": "Internal Server Error"}, 500
app.start(port=os.getenv("SERVER_PORT"))
import os
import json
import aiomysql
from robyn import Robyn
os.environ["ROBYN_URL"] = "0.0.0.0"
app = Robyn(__file__)
pool = None
@app.startup_handler
async def startup_handler():
# Read configuration from environment variables
db_user = os.getenv("DB_USER", "username")
db_password = os.getenv("DB_PASSWORD", "password")
db_host = os.getenv("DB_HOST", "Configure me first, moron!")
db_name = os.getenv("DB_NAME", "license_db")
db_port = int(os.getenv("DB_PORT", "3306"))
if os.getenv("LOG_LEVEL") == "DEBUG":
debug = True
global pool
pool = await aiomysql.create_pool(
host=db_host, port=db_port,
user=db_user, password=db_password,
db=db_name
)
print("Database connected")
@app.shutdown_handler
async def shutdown_handler():
global pool
pool.close()
await pool.wait_closed()
@app.post("/")
async def check_license(request):
if os.getenv("LOG_LEVEL").lower() == "debug":
debug = True
else:
debug = False
try:
# Extract the license_key from the JSON payload
data = json.loads(request.body)
license_key = data.get("license_key")
headers_to_check = ["X-Forwarded-For", "Remote-Addr", "cf-connecting-ip"]
ip_address = None
for header in headers_to_check:
ip_address = request.headers.get(header)
if ip_address:
# If X-Forwarded-For contains multiple IPs (due to multiple proxies), take the first one
if header == "X-Forwarded-For" and "," in ip_address:
ip_address = ip_address.split(",")[0].strip()
break
# If none of the headers provide the IP, use Robyn's method
if not ip_address:
ip_address = request.ip_addr
# Input validation
if not license_key or not ip_address:
return {"error": "Invalid input"}, 400
# Query to get the IP field for the given license_key
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT ip FROM license_check WHERE license=%s",
(license_key,)
)
result = await cur.fetchone()
# If there's a result and the extracted IP is in the list of IPs for that license
if result and ip_address in result[0].split(','):
valid = True
else:
valid = False
if debug:
print(f"IP Address: {ip_address}")
print(f"License Key: {license_key}")
print(f"Query Result: {valid}")
if valid:
if debug:
print("License verified")
response_data = {"status": "success", "message": "License verified."}
return json.dumps(response_data)
else:
if debug:
print("License not found or IP mismatch")
response_data = {"status": "failure", "message": "License not found or IP mismatch."}
return json.dumps(response_data)
except Exception as e:
import traceback
traceback.print_exc()
print(f"Error occurred: {e}")
return {"error": "Internal Server Error"}, 500
app.start(port=os.getenv("SERVER_PORT"))