This repository has been archived by the owner on Nov 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
291 lines (247 loc) · 11 KB
/
server.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
from flask import Flask, request, jsonify, send_from_directory
import database_helper
import json
import random
import string
import sys
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
from flask_bcrypt import Bcrypt
import os
from werkzeug import secure_filename
sys.path.append(os.path.join(os.path.dirname(__file__)))
app = Flask(__name__)
bcrypt = Bcrypt(app)
app.debug = True
@app.route('/')
def root():
return send_from_directory('static', 'client.html')
def token_generator(n):
letters = string.ascii_letters + "0123456789"
return ''.join(random.choice(letters) for i in range(n))
@app.route('/users/upload_file/<email>,<email_wall>', methods=['POST'])
def upload_file(email=None, email_wall=None):
file = request.files['file']
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = 'static/uploaded/' + email_wall + '/'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if request.files:
f = request.files['file']
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
if not email_wall:
database_helper.upload_file(secure_filename(f.filename),email, email)
else:
database_helper.upload_file(secure_filename(f.filename),email, email_wall)
return "True"
else:
return "False"
@app.route('/users/upload_profile/<email>', methods=['POST'])
def upload_profile(email=None):
file = request.files['file']
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = 'static/uploaded/' + email + '/ProfilePicture/'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if request.files:
f = request.files['file']
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
database_helper.upload_profile(secure_filename(f.filename),email)
return "True"
else:
return "False"
@app.route('/users/load_profile_picture/<email>', methods=['GET'])
def load_profile_picture(email=None):
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = 'static/uploaded/' + email + '/ProfilePicture/'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
result = database_helper.load_profile_picture(email)
if result:
return json.dumps({"success": "true", "message": "Successfully signed in.", "data": result}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
@app.route('/find_user/<email>', methods=['GET'])
def find_user(email=None):
if email is not None:
result = database_helper.find_user(email)
else:
result = False
if not result:
return False
else:
return jsonify(result)
signed_in_users = dict()
@app.route('/users/sign_in/', methods=['POST'])
def sign_in():
data = request.get_json()
if data['email'] in signed_in_users:
msg = {
'message': 'Logged in from another device'
}
try:
signed_in_users[data['email']].send(json.dumps(msg))
del signed_in_users[data['email']]
database_helper.delete_loggedinuser(data['email'])
except:
pass
if 'email' in data and 'password' in data:
if find_user(data['email']):
user = find_user(data['email']).get_json()[0]
if user['email'] is not None and bcrypt.check_password_hash(user['password'], data['password']):
token = token_generator(35)
else:
return '', 400
result = database_helper.sign_in(token, user['email'])
if result:
return json.dumps({"success": "true", "message": "Successfully signed in.", "data": token}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
else:
return '', 400
@app.route('/users/check_old_password/<email>,<password>', methods=['GET'])
def check_old_password(email=None, password=None):
if email and password and find_user(email):
user_password = find_user(email).get_json()[0]['password']
if bcrypt.check_password_hash(user_password, password):
#result = database_helper.check_old_password(email, user_password)
result = True
if result:
return json.dumps({"success": "true", "message": "Password matching!"}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
@app.route('/users/sign_up/', methods=['POST'])
def sign_up():
data = request.get_json()
if 'email' in data and 'password' in data and 'firstname' in data and 'familyname' in data \
and 'gender' in data and 'city' in data and 'country' in data:
if len(data['email']) <= 30 and 5 <= len(data['password']) <= 30 \
and len(data['firstname']) <= 30 and len(data['familyname']) <= 30 and len(data['gender']) <= 30 \
and len(data['city']) <= 30 and len(data['country']) <= 30:
pw_hashed = bcrypt.generate_password_hash(data['password'])
result = database_helper.sign_up(data['email'], pw_hashed, data['firstname'], data['familyname'],
data['gender'], data['city'], data['country'])
if result:
path = os.getcwd() + "/static/uploaded/" + str(data['email'])
os.mkdir(path)
os.mkdir(path + "/ProfilePicture")
return json.dumps({"success": "true", "message": "User saved!"}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
else:
return '', 400
@app.route('/users/sign_out/', methods=['POST'])
def sign_out():
token = request.headers.get('Token')
if token is not None:
result = database_helper.sign_out(token)
if result:
return json.dumps({"success": "true", "message": "Token deleted!"}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
@app.route('/users/change_password/', methods=['PUT'])
def change_password():
token = request.headers.get('Token')
data = request.get_json()
if 'oldpassword' in data and 'newpassword' in data:
if 5 <= len(data['newpassword']) <= 30:
user_email = database_helper.get_user_data_by_token(token)[0]['email']
user = find_user(user_email).get_json()[0]
new_pw_hashed = bcrypt.generate_password_hash(data['newpassword'])
if bcrypt.check_password_hash(user['password'], data['oldpassword']):
result = database_helper.change_password(token, user['password'], new_pw_hashed)
print(result)
if result:
return json.dumps({"success": "true", "message": "Password changed!"}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
else:
return '', 400
@app.route('/users/get_user_data_by_token/', methods=['GET'])
def get_user_data_by_token():
token = request.headers.get('Token')
if token is not None:
result = database_helper.get_user_data_by_token(token)
if result:
return json.dumps({"success": "true", "message": "Requested user found!", "data": result[:]}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 400
@app.route('/users/get_user_data_by_email/<email>', methods=['GET'])
def get_user_data_by_email(email=None):
token = request.headers.get('Token')
if email is not None and token is not None:
result = database_helper.get_user_data_by_email(email, token)
if result:
return json.dumps({"success": "true", "message": "Requested user found!", "data": result[:]}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 400
@app.route('/users/get_user_messages_by_token/', methods=['GET'])
def get_user_messages_by_token():
token = request.headers.get('Token')
if token is not None:
result = database_helper.get_user_messages_by_token(token)
if result:
return json.dumps({"success": "true", "message": "Requested wall found!", "data": result[:]}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 400
@app.route('/users/get_user_messages_by_email/<email>', methods=['GET'])
def get_user_messages_by_email(email=None):
token = request.headers.get('Token')
if email is not None and token is not None:
result = database_helper.get_user_messages_by_email(email, token)
if result:
return json.dumps({"success": "true", "message": "Requested wall found!", "data": result[:]}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 400
@app.route('/users/post_message/', methods=['POST'])
def post_message():
token = request.headers.get('Token')
data = request.get_json()
if token is not None and "content" in data and "email" in data:
if len(data['email']) <= 30 and len(data['content']) <= 120:
result = database_helper.post_message(data['email'], data['content'], token)
if result:
return json.dumps({"success": "true", "message": "Message posted to the wall!"}), 200
else:
return json.dumps({"success": "false", "message": "Something went wrong!"}), 500
else:
return '', 400
else:
return '', 400
@app.route('/check_websocket')
def check_websocket():
if request.environ.get('wsgi.websocket'):
web_socket = request.environ['wsgi.websocket']
message = json.loads(web_socket.receive())
user = database_helper.get_user_data_by_token(message['token'])[0]['email']
signed_in_users[user] = web_socket
while not web_socket.closed:
message = web_socket.receive()
if message is not None:
message = json.loads(message)
message = {'message': 'Successfully logged in'}
web_socket.send(json.dumps(message))
try:
del signed_in_users[user]
except:
pass
return 'None'
@app.teardown_request
def after_request(exception):
database_helper.disconnect_db()
if __name__ == '__main__':
# print("Server: http://127.0.0.1:5000/")
# http_server = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
http_server = WSGIServer(('', int(os.environ.get('PORT'))), app, handler_class=WebSocketHandler)
http_server.serve_forever()
# app.run()