/
api.py
executable file
·261 lines (239 loc) · 8.7 KB
/
api.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
import os
import re
import json
import time
import util
import hashlib
import pymongo
from lib import mongo
from flask.ext.cors import CORS
from flask import Flask, request
from bson.objectid import ObjectId
from flask.ext.socketio import SocketIO, emit, send
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = "Hardcoded Temporary Key"
socketio = SocketIO(app)
util = util.Util()
@app.route('/')
def index():
return "index"
# Registers a new user and logs them in
@app.route("/register", methods=['POST'])
def register():
user = request.form['user']
passw = request.form['passw']
if "details" in request.form:
details = request.form['details']
details = json.loads(details)
else:
details = False
# get the users collection
users = util.get_collection('users')
# construct user model
userData = {
"user": user,
"passw": util.sha512(user + passw), # Effective permanent salt
"details": details,
"session_salt": False
}
# make sure user is not already registered
if users.find({"user": user}).count() > 0:
return "userTaken"
# validate the username and password
elif len(user) < 140 and len(passw) >= 6 and len(passw) < 140:
# insert the user into the database and return their id
users.insert(userData)
# log the user in
return login()
else:
# Only broken clients will recieve this error
return "error"
# Logs in a user. Returns their authentication information
@app.route('/login', methods=['POST'])
def login():
if request.method == "POST":
user = request.form['user']
passw = request.form['passw']
else:
return "False"
# get user collection
users = util.get_collection('users')
# find the user in the collection
user_data = users.find_one({"user": user})
# if the login details match up
if user_data and user_data['passw'] == util.sha512(user + passw):
# create a salt so the same session key is only valid once
session_salt = util.sha512(os.urandom(512))
# add the salt to the database so we can verify it later
util.update_user(user_data['_id'], {"session_salt": session_salt})
# construct a session key from the salt
session_key = util.sha512(session_salt + user_data['passw'])
userID = str(user_data['_id'])
del user_data['_id']# delete sensitive variables
del user_data['passw']# ^^^^^^^^^^^^^^^^^^^^^^^^
del user_data['session_salt']# ^^^^^^^^^^^^^^^^^
# User logged in. Gibbe (session) cookies
return json.dumps({
"session": session_key,
"userID": userID,
"details": user_data
})
else:
return "False"
### Here starts the auth-only functions. Make sure you check their session cookies!
# Changes a user's password
@app.route('/change_password', methods=['POST'])
def change_password():
if request.method == "POST":
userID = request.form['userID']
session = request.form['session']
passw = request.form['passw']
new_passw = request.form['new_passw']
else:
return False
# Make sure the user is legit
user = util.auth(userID, session)
if user:
# check if the old password matches the current password
# it should be, but just in case they're cookie stealing
if util.sha512(user['user'] + passw) == user['passw']:
return util.update_user(
userID,
{"passw": util.sha512(user['user'] + new_passw)}
)
else:
return "incorrect password"
else:
return "invalid user"
# Completely deletes a user's account
@app.route('/delete_account', methods=['POST'])
def delete_account():
user = util.auth_request(request)
if user:
users = get_collection('users')
users.remove({"_id": ObjectId(userID)}, 1)
else:
return False
# Takes authentication information and returns user info
@app.route('/authenticate', methods=['POST'])
def authenticate():
user = util.auth_request(request)
if user:
del user['passw']
del user['session_salt']
del user['_id']
return json.dumps(user)
# Updates users' details property.
@app.route('/update-user', methods=["POST"])
def update_user():
userID = request.form['userID']
session = request.form['session']
new_details = request.form['new_details']
user = util.auth(userID, session)
if user: # User is authed, do some stuff
new_details = json.loads(new_details)
update_query = {
"details": user['details'].update(new_details)
}
if util.update_user(user['_id'], update_query):
return "success"
else:
return "error"
# SocketIO handlers that allow limited database access to the front end
# Object that represents a socket connection
class Socket:
def __init__(self, sid, query):
self.sid = sid
self.query = query
self.connected = True
# Emits data to a socket's unique room
def emit(self, event, data):
emit(event, data, room=self.sid)
mongo = mongo.MongoConnection()
live_sockets = {'senders': {}, 'recipients': {}}
all_listeners = {}
@socketio.on('listen', namespace='/component')
def listen_handler(data):
request_data = json.loads(data)
# authenticate the request_data (and get a sneaky recipients list)
auth, recipients = util.auth_listen(request_data)
if not auth:
return False
# send the user backlogs if requested
if request_data['backlog']:
# get previously sent documents
senders_log, recipients_log = mongo.get_documents(
request_data['sender_pair'][0],
recipients,
request_data['collection']
)
for document in senders_log:
if document['visible']:
document_tidy = {
"sender": document['sender'],
"recipient": document['recipient'],
"data": document['data'],
"ts": document['ts']
}
emit('data_sent', document_tidy)
for document in recipients_log:
if document['visible']:
document_tidy = {
"sender": document['sender'],
"recipient": document['recipient'],
"data": document['data'],
"ts": document['ts']
}
emit('data_received', document_tidy)
# add socket to dict of sockets to keep updated
# (Choosing speed over memory here)
# create a socket object to represent us
socket = Socket(request.sid, request_data)
# add us to a list of all listener sockets
live_sockets[socket.sid] = socket
# make sure the list exists first
if not request_data['sender_pair'][0] in live_sockets['senders']:
live_sockets['senders'][request_data['sender_pair'][0]] = []
# append us to the list of senders subscribed to changes
live_sockets['senders'][request_data['sender_pair'][0]].append(socket)
# append us to a list of subscribers for each recipient we're following
for recipient in recipients:
if not recipient in live_sockets['recipients']:
live_sockets['recipients'][recipient] = []
live_sockets['recipients'][recipient].append(socket)
@socketio.on('send', namespace='/component')
def send_handler(data):
request = json.loads(data)
# validate request
if not "sender_pair" in request or not "recipient" in request or \
not "collection" in request or not "data" in request:
emit('error', "Invalid Arguments")
return False
sender_pair = request['sender_pair']
recipient = request['recipient']
collection = request['collection']
message = request['data']
# store document
document = mongo.send(message, sender_pair, recipient, collection)
# send Updates
document_tidy = {
"sender": document['sender'],
"recipient": document['recipient'],
"data": document['data'],
"ts": document['ts']
}
util.emit_to_relevant_sockets(request, document_tidy, live_sockets)
@socketio.on('disconnect')
def disconnect():
# if socket is listening
if request.sid in all_listeners:
# remove from listeners
all_listeners[request.sid].connected = False
del all_listeners[request.sid]
### Here starts the admin-only functions. Make sure you check user['isAdmin']!
### Here ends the admin-only functions. Make sure you check user['isAdmin']!
### Here ends the auth-only functions. Make sure you check their session cookies!
if __name__ == "__main__":
# app.run(debug=True)
socketio.run(app, debug=True)