-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
419 lines (392 loc) · 15.3 KB
/
main.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import os
from flask import Flask, request, jsonify, make_response, request, render_template, session, flash, redirect
import jwt
from pymongo import MongoClient
import mysql.connector
from mysql.connector import errorcode
from datetime import datetime, timedelta
from functools import wraps
import time
from dotenv import load_dotenv
load_dotenv()
import bcrypt
def hash_password(password):
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed_password.decode('utf-8')
def verify_password(password, hashed_password):
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv("JWT_SECRET")
# try:
# MONGO_URI = os.getenv("MONGODB_URI")
# client = MongoClient(MONGO_URI)
# client.admin.command('ping')
# print("Connection to Mongo DB successful")
# except:
# print("ERROR CONNECTING TO MONGODB")
# time.sleep(5)
# exit()
try:
mysql_endpoint = os.getenv("MYSQL_ENDPOINT")
mysql_username = os.getenv("MYSQL_ROOT_USERNAME")
mysql_password = os.getenv("MYSQL_ROOT_PASSWORD")
mysql_db = os.getenv("MYSQL_DB")
connection = mysql.connector.connect(
host=mysql_endpoint,
user=mysql_username,
passwd=mysql_password,
# database=mysql_db
)
connection.autocommit=False
cursor = connection.cursor()
try:
cursor.execute("create database "+mysql_db)
except:
print("DB already exists")
try:
cursor.execute("use "+mysql_db)
cursor.execute("create table if not exists users (username varchar(20) unique not null, password varchar(60) not null, account_number char(10) primary key not null, balance int not null)")
cursor.execute("create table if not exists transactions (transaction_number int primary key not null, date datetime not null, _from char(20) not null, _to char(20) not null, amount int not null, FOREIGN KEY (_from) REFERENCES users(account_number),FOREIGN KEY (_to) REFERENCES users(account_number))")
try:
cursor.execute("insert into users values (\"{}\", \"{}\", \"{}\", \"{}\")".format("dummy_user", os.getenv("dummy_user_pass"), "0000000001", 0))
except:
print("dummy user already exists")
except Exception as e:
print(e)
connection.commit()
print("Connection to MySQL DB successful")
except Exception as e:
print("ERROR CONNECTIONG TO MySQL"+str(e))
time.sleep(5)
exit()
def token_required(func):
@wraps(func)
def decorated(*args, **kwargs):
token = request.args.get('token')
if not token:
return jsonify({'Alert!': 'Token is missing!'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
# You can use the JWT errors in exception
# except jwt.InvalidTokenError:
# return 'Invalid token. Please log in again.'
except:
return jsonify({'Message': 'Invalid token'}), 403
return func(*args, **kwargs)
return decorated
@app.get('/')
def home():
return make_response({
"message": "ReliaBank API is working",
"for documentation": "visit /docs"
}, 200)
@app.route('/docs', methods=["GET"])
def docs():
return make_response({
"/": {
"info": "health check endpoint",
"request type": "GET"
},
"/docs": {
"info": "view this documentation",
"request type": "GET"
},
"/register": {
"info": "register as a new user",
"request type": "POST",
"payload": {
"username": "your_username",
"password": "your_password",
"balance": "your_initial_balance"
}
},
"/login": {
"info": "login as an existing user",
"request type": "POST",
"payload": {
"username": "your_username",
"password": "your_password"
}
},
"/logout": {
"info": "logout",
"request type": "GET"
},
"/dashboard": {
"info": "get stats for your account",
"request type": "GET"
},
"/view_transactions": {
"info": "view all transaction of the current user",
"request type": "GET"
},
"/transfer": {
"info": "transfer money to another account",
"request type": "POST",
"payload": {
"receiver": "receiver account number",
"amount": "amount"
}
}
}, 200)
@app.route('/login', methods=['POST'])
def login():
try:
req_body = request.json
login_creds = {
"username": req_body['username'],
"password": req_body['password']
}
except:
return make_response({
"message": "login failed",
"error": "not all required parameters are passed",
"code": "0"
}, 404)
try:
cursor.execute("select password from users where username=\""+login_creds["username"]+"\"")
login_creds["hashed_password"] = cursor.fetchall()[0][0]
except:
return make_response({
"message": "login failed",
"error": "User Not Found",
"code": "0"
}, 400)
# return login_creds
if login_creds["username"]:
if verify_password(login_creds["password"], login_creds["hashed_password"]): #hash_password(request.form['password']) == login_creds["hashed_password"]:
token = jwt.encode({
'username': login_creds['username'],
'expiration': str(datetime.utcnow() + timedelta(minutes=10))
},app.config['SECRET_KEY'])
session["token"] = token
return make_response({
"message": "login success",
"error": "",
"code": "1"
}, 200)
else:
return make_response({
"message": "login failed",
"error": "Wrong Password",
"code": "0"
}, 400)
else:
return make_response({
"message": "login failed",
"error": "User Not Found",
"code": "0"
}, 400)
@app.route('/logout', methods=['GET'])
def logout():
try:
session.pop('token')
except:
pass
return make_response({
"message": "logout success",
"error": "",
"code": "1"
}, 200)
@app.route('/register', methods=['POST'])
def register():
try:
req_body = request.json
login_creds = {
"username": req_body['username'],
"password": req_body['password'],
"balance": 0
}
except:
return make_response({
"message": "registration failed",
"error": "all required parameters arent passed",
"code": "0"
}, 400)
try:
login_creds["balance"] = int(req_body["balance"])
except:
return make_response({
"message": "registration failed",
"error": "\"balance\" needs to be an integer",
"code": "0"
}, 400)
login_creds["password"] = hash_password(login_creds["password"])
cursor.execute("select max(account_number) from users where account_number <> \"None\"")
account_number = cursor.fetchall()
if account_number==[[]]:
account_number = "00000001"
else:
account_number = str(int(account_number[0][0]) + 1)
account_number = "0"*(10-len(account_number)) + account_number
try:
cursor.execute("insert into users values (\"{}\", \"{}\", \"{}\", \"{}\")".format(login_creds["username"], login_creds["password"], account_number, login_creds["balance"]))
except mysql.connector.Error as err:
if err.errno == errorcode.ER_DUP_ENTRY:
return make_response({
"message": "registration failed",
"error": "username already used",
"code": "0"
}, 400)
elif err.errno == errorcode.ER_DATA_TOO_LONG:
return make_response({
"message": "registration failed",
"error": "data too long",
"code": "0"
}, 400)
else:
return make_response({
"message": "registration failed",
"error": str(e),
"code": "0"
}, 400)
connection.commit()
token = jwt.encode({
'username': login_creds['username'],
'expiration': str(datetime.utcnow() + timedelta(minutes=10))
},app.config['SECRET_KEY'])
session["token"] = token
return make_response({
"message": "registration success",
"error": "",
"code": "1"
}, 200)
@app.get("/dashboard")
# @token_required
def dashboard():
cookies = str(session)
try:
token = session["token"]
username, jwt_exp = str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["username"]), str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["expiration"])
# if expiration<datetime.now():
# return redirect("/logout")
cursor.execute("select * from users where username=\""+username+"\"")
data = cursor.fetchone()
username, account_number, balance = str(data[0]), str(data[2]), str(data[3])
return make_response({
"message": "success",
"error": "",
"username": username,
"balance": balance,
"account_number": account_number,
"code": "1"
}, 200)
except Exception as e:
# return str(e)
return make_response({
"message": "failed",
"error": "not authenticated",
"more info": str(e),
"code": "0"
}, 401)
@app.route("/view_transactions", methods=["GET"])
def view_transactions():
try:
token = session["token"]
username, jwt_exp = str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["username"]), str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["expiration"])
# if expiration<datetime.now():
# return redirect("/logout")
cursor.execute("select account_number from users where username=\""+username+"\"")
account_number = cursor.fetchone()[0]
cursor.execute("select * from transactions where _from=\""+account_number+"\""+" or _to=\""+account_number+"\" ORDER BY date DESC")
transactions = cursor.fetchall()
return make_response({
"message": "success",
"error": "",
"transactions": transactions,
"code": "1"
}, 200)
except Exception as e:
return make_response({
"message": "failed",
"error": "not authenticated",
"code": "0"
}, 401)
@app.route("/transfer", methods=["POST"])
def transfer():
try:
token = session["token"]
username, jwt_exp = str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["username"]), str(dict(jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']))["expiration"])
# if expiration<datetime.now():
# return redirect("/logout")
try:
req_body = request.json
post_data = {
"receiver": req_body["receiver"],
"amount": int(req_body["amount"])
}
if post_data["amount"]<=0:
return make_response({
"message": "transaction failed",
"error": "amount needs to be > 0",
"code": "0"
}, 400)
cursor.execute("select account_number from users")
all_account_numbers = [item for sublist in cursor.fetchall() for item in sublist]
if post_data["receiver"] not in all_account_numbers:
return make_response({
"message": "transaction failed",
"error": "Receiver account not found",
"code": "0"
}, 400)
cursor.execute("select username from users where account_number=\""+post_data["receiver"]+"\"")
receiver_name = cursor.fetchone()[0]
cursor.execute("select account_number from users where username=\""+username+"\"")
user_account_number = cursor.fetchone()[0]
if post_data["receiver"] == user_account_number:
return make_response({
"message": "transaction failed",
"error": "you cannot send money to yourself",
"code": "0"
}, 400)
cursor.execute("select balance from users where username=\""+username+"\"")
current_balance = cursor.fetchone()[0]
if post_data["amount"]<=current_balance:
# cursor.execute("SET AUTOCOMMIT=0")
connection.autocommit=False
try:
# connection.start_transaction()
# actual transaction
cursor.execute("select balance from users where account_number=\""+post_data["receiver"]+"\"")
current_balance2 = cursor.fetchone()[0]
cursor.execute("update users set balance={} where account_number=\"{}\"".format(current_balance2+post_data["amount"], post_data["receiver"]))
cursor.execute("update users set balance={} where username=\"{}\"".format(current_balance-post_data["amount"], username))
cursor.execute("select count(*) from transactions")
transaction_number = 1+int(cursor.fetchone()[0])
cursor.execute("select account_number from users where username=\""+username+"\"")
sender_account = cursor.fetchone()[0]
cursor.execute("insert into transactions values({}, \"{}\", \"{}\", \"{}\", {})".format(transaction_number, str(datetime.now()), sender_account, post_data["receiver"], post_data["amount"]))
connection.commit()
return make_response({
"message": "transaction success: ${} sent to {}".format(post_data["amount"], receiver_name),
"error": "",
"code": "1"
}, 200)
except Exception as e:
connection.rollback()
return make_response({
"message": "transaction failed",
"error": str(e),
"code": "0"
}, 400)
cursor.execute("SET AUTOCOMMIT=1")
else:
return make_response({
"message": "transaction failed",
"error": "insufficied balance",
"code": "0"
}, 400)
except Exception as e:
return make_response({
"message": "transaction failed",
"error": str(e),
"code": "0"
}, 400)
except:
return make_response({
"message": "transaction failed",
"error": "not authenticated",
"code": "0"
}, 401)
if __name__ == "__main__":
app.run(host="0.0.0.0", port="5000", debug=True)