forked from WorldViews/Spirals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flaskAuthServer80.py
369 lines (326 loc) · 10.6 KB
/
flaskAuthServer80.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
"""
This is a version of the flask server with users and
authentication, and also it is registerable or trackable.
"""
import json, time, traceback
import flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
from flask import Flask, render_template, send_file, redirect, \
jsonify, send_from_directory, request
from flask_socketio import SocketIO, emit
from flask_mail import Mail
TABLE_NAMES = ["chat", "notes", "periscope"]
DB_REQUEST_TIMES = {}
rdb = None
try:
import rethinkdb as rdb
#rdb.connect('localhost', 28015).repl()
conn = rdb.connect(db='test')
except:
print "*** Running without DB ***"
rdb = None
app = Flask(__name__, static_url_path='')
app.debug = True
#app.debug = False
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///wv.db'
app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_EMAIL_SENDER'] = 'no-reply@pollywss.paldeploy.com'
app.config['MAIL_SERVER'] = '192.168.20.18'
app.config['MAIL_PORT'] = 25
#app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = 'flycam'
app.config['MAIL_PASSWORD'] = 'flyspec'
mail = Mail(app)
socketio = SocketIO(app)
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
name = db.Column(db.String(255))
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
last_login_at = db.Column(db.DateTime())
current_login_at = db.Column(db.DateTime())
# Why 45 characters for IP Address ?
# See http://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address/166157#166157
last_login_ip = db.Column(db.String(45))
current_login_ip = db.Column(db.String(45))
login_count = db.Column(db.Integer)
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
print "------------------------------------------"
print "Creating tables and user entries"
db.create_all()
if User.query.count() > 0:
print ">>>>>>>>>> Tables already initialized.... <<<<<<<<<<<"
return
user_datastore.create_user(email='donkimber@gmail.com',
password='xxx',
name="Don")
user_datastore.create_user(email='enockglidden@hotmail.com',
password='xxx',
name="Enock")
user_datastore.create_user(email='sinasareth@yahoo.com',
password='xxx',
name="Sina")
user_datastore.create_user(email='doczeno@yahoo.com',
password='xxx',
name="doczeno")
user_datastore.create_user(email='vaughan@fxpal.com',
password='xxx',
name="Jim")
db.session.commit()
print "------------------------------------------"
def getObj(id, tname):
print "getObj", id, tname
recs = rdb.table(tname).filter({'id': id}).run(conn)
return recs.next()
def getNote(id):
return getObj(id, 'notes')
@app.route('/')
def index():
print "index ****"
return send_file('index.html')
"""
This is used by SharedCam to register itself with us.
"""
@app.route('/regp/', methods=['POST','GET'])
def reg():
print "reg path:", request.path
print "reg args", request.args
t = time.time()
name = request.args.get('name')
tagStr = request.args.get('tagStr')
clientType = request.args.get('clientType')
lon = float(request.args.get('longitude'))
lat = float(request.args.get('latitude'))
room = request.args.get('room')
numUsers = int(request.args.get('numUsers'))
sessionId = request.args.get('sessionId')
sessionId = sessionId.replace(':', '_')
sessionId = sessionId.replace('-', '_')
obj = {'t': t, 'name': name, 'tagStr': tagStr,
'lon': lon, 'lat': lat, 'room': room,
'sessionId': sessionId,
'numUsers': numUsers, 'clientType': clientType}
print obj
jstr = json.dumps(obj)
print "jstr:", jstr
if socketio:
print "send to socketio"
emit('sharecam', jstr, broadcast=True, namespace='/')
return "Ok"
# return flask.jsonify({'val': 'ok'})
@app.route("/WV/<path:path>")
def getPage(path):
return render_template(path+".html")
@app.route('/Viewer/TV')
def viewerTV():
print "viewerTV"
# return send_from_directory('Viewer', "TV.html")
return render_template("TV.html")
@app.route('/Viewer/<path:path>')
def send(path):
print "send_page", path
return send_from_directory('Viewer', path)
@app.route('/images/<path:path>')
def send_image(path):
print "send_image", path
return send_from_directory('images', path)
@app.route('/Cesium/<path:path>')
def send_page(path):
print "send_page", path
return send_from_directory('Cesium', path)
@app.route('/log')
@login_required
def log_on():
print "log_on"
return redirect('/Viewer/TV')
# render_template('TV.html')
"""
This URL is a gateway for posting to SIO
"""
@app.route('/sioput/<path:etype>', methods=['POST','GET'])
def sioput(etype):
req = {}
args = request.args
if request.data:
req = json.loads(request.data)
for key in args:
req[key] = args[key][0]
print "req:", req
etype0 = req['etype']
if etype0 != etype:
print "mismatch etype:", etype
obj = req['obj']
jObj = json.dumps(obj)
print "etype:", etype
print "jObj:", jObj
if socketio:
print "send to socketio"
emit(etype, jObj, broadcast=True, namespace='/')
print "**** addToDB"
addObjToDB(obj, etype)
print
return "OK"
@app.route('/comment/<path:etype>', methods=['POST','GET'])
def addComment(etype):
print "addComment", etype
req = {}
args = request.args
print "args:", args
if request.data:
req = json.loads(request.data)
for key in args:
#req[key] = args[key][0]
req[key] = args[key]
print "req:", req
parentId = req['parent']
comment = req['comment']
print "parentId:", parentId
print "comment:", comment
note = getNote(parentId)
print "note:", note
comments = note.get("comments", [])
comments.append(comment)
print "comments:", comments
note['comments'] = comments
#q = rdb.table("notes").filter({"id":id})
#q = q.update({"comments": comments})
#q.run(conn)
jObj = json.dumps(note)
print "etype:", etype
print "jObj:", jObj
if socketio:
print "send to socketio"
emit(etype, jObj, broadcast=True, namespace='/')
print "**** addToDB"
replaceObjToDB(note, etype)
print
return "OK"
@app.route('/db/<path:etype>')
def query(etype):
global DB_REQUEST_TIMES
print "query", etype
t = time.time()
DB_REQUEST_TIMES[etype] = t
if rdb == None:
return flask.jsonify({'error': 'No DB', 't': t, 'records': []})
args = request.args
id = args.get("id", None)
#if id != None:
# recs = rdb.table(etype).filter({'id': id}).run(conn)
# obj = recs.next()
# return flask.jsonify(obj)
tMin = args.get("tMin", None)
limit = args.get("limit", None)
if limit != None:
limit = int(limit)
if tMin != None:
tMin = float(tMin)
try:
q = rdb.table(etype)
if id != None:
q = q.filter({'id': id})
if tMin != None:
q = q.filter(rdb.row["t"].gt(tMin))
q = q.order_by(rdb.desc('t'))
if limit != None:
q = q.limit(limit)
print q
recs = q.run(conn)
except:
traceback.print_exc()
return
items = list(recs)
obj = {'type': etype,
't' : t,
'records': items}
return flask.jsonify(obj)
"""
This returns an object that gives the most recent request
for a table by type of table. It is intended as a mechanism
for event Watcher streams to know when their kinds of events
are requested.
"""
@app.route('/dbstats/')
def dbstats():
return flask.jsonify(DB_REQUEST_TIMES)
###################################################################
#
# SocketIO bindings
#
@socketio.on('my event')
def test_message(message):
emit('my response', {'data': 'got it!'})
@socketio.on('chat')
def handle_chat(msg):
print "handle_chat:", msg
emit('chat', msg, broadcast=True)
addMsgStrToDB(msg, 'chat')
@socketio.on('notes')
def handle_notes(msg):
print "handle_notes:", msg
emit('notes', msg, broadcast=True)
addMsgStrToDB(msg, 'notes')
@socketio.on('people')
def handle_people(msg):
#print "handle_people:", msg
emit('people', msg, broadcast=True)
@socketio.on('sharecam')
def handle_sharecam(msg):
#print "handle_people:", msg
emit('sharecam', msg, broadcast=True)
def addMsgStrToDB(msgStr, etype):
print "add Msg to DB:", etype
if etype not in TABLE_NAMES:
print "**** addMsgStrToDB unknown table:", etype
return
obj = json.loads(msgStr)
if rdb == None:
print "*** not connected to DB ***"
rdb.table(etype).insert(obj).run(conn)
def addObjToDB(obj, etype):
print "add Obj to DB:", etype
print "obj:", obj
if etype not in TABLE_NAMES:
print "**** addObjToDB: unknown table:", etype
return
rc = rdb.table(etype).insert(obj).run(conn)
print "Completed insert", rc
def replaceObjToDB(obj, etype):
print "add Obj to DB:", etype
print "obj:", obj
if etype not in TABLE_NAMES:
print "**** addObjToDB: unknown table:", etype
return
rc = rdb.table(etype).replace(obj).run(conn)
print "Completed insert", rc
def run():
print "Running flask server"
socketio.run(app, host="0.0.0.0", port=80)
#socketio.run(app, port=80)
if __name__ == '__main__':
run()