-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
45 lines (34 loc) · 1.3 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
import flask
from flask_socketio import join_room, leave_room, send, emit
import flask_socketio as sio
from init import app, db, socketio
import models
def check_request():
token = flask.session['csrf_token']
if flask.request.form['_csrf_token'] != token:
app.logger.warn('invalid CSRF token')
flask.abort(400)
if flask.session.get('auth_user') != int(flask.request.form['creator_id']):
app.logger.warn('requesting user %s not logged in (%s)',
flask.request.form['creator_id'],
flask.session.get('auth_user'))
flask.abort(403)
@socketio.on('message')
def message(msg):
send(msg, broadcast=True)
@socketio.on('connect')
def on_connect():
# get the connecting user's user ID
# flask.session works in socket IO handlers :)
uid = flask.session.get('auth_user', None)
if uid is None:
app.logger.warn('received socket connection from unauthed user')
return
app.logger.info('new client connected for user %d', uid)
user = models.User.query.get_or_404(uid)
# add this connection to the user's 'room', so we can send to all
# the user's open browser tabs
join_room('user-{}'.format(uid))
@socketio.on('disconnect')
def on_disconnect():
app.logger.info('client disconnected')