-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
131 lines (91 loc) · 3.33 KB
/
application.py
File metadata and controls
131 lines (91 loc) · 3.33 KB
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
import os
import time
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, login_user, current_user, logout_user
from flask_socketio import SocketIO, join_room, leave_room, send
from wtform_fields import *
from models import *
# Configure app
app = Flask(__name__)
app.secret_key=os.environ.get('SECRET')
app.config['WTF_CSRF_SECRET_KEY'] = "b'f\xfa\x8b{X\x8b\x9eM\x83l\x19\xad\x84\x08\xaa"
# Configure database
app.config['SQLALCHEMY_DATABASE_URI']=os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Initialize login manager
login = LoginManager(app)
login.init_app(app)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
socketio = SocketIO(app, manage_session=False)
# Predefined rooms for chat
ROOMS = ["lounge", "news", "games", "coding"]
@app.route("/", methods=['GET', 'POST'])
def index():
reg_form = RegistrationForm()
# Update database if validation success
if reg_form.validate_on_submit():
username = reg_form.username.data
password = reg_form.password.data
# Hash password
hashed_pswd = pbkdf2_sha256.hash(password)
# Add username & hashed password to DB
user = User(username=username, hashed_pswd=hashed_pswd)
db.session.add(user)
db.session.commit()
flash('Registered successfully. Please login.', 'success')
return redirect(url_for('login'))
return render_template("index.html", form=reg_form)
@app.route("/login", methods=['GET', 'POST'])
def login():
login_form = LoginForm()
# Allow login if validation success
if login_form.validate_on_submit():
user_object = User.query.filter_by(username=login_form.username.data).first()
login_user(user_object)
return redirect(url_for('chat'))
return render_template("login.html", form=login_form)
@app.route("/logout", methods=['GET'])
def logout():
# Logout user
logout_user()
flash('You have logged out successfully', 'success')
return redirect(url_for('login'))
@app.route("/chat", methods=['GET', 'POST'])
def chat():
if not current_user.is_authenticated:
flash('Please login', 'danger')
return redirect(url_for('login'))
return render_template("chat.html", username=current_user.username, rooms=ROOMS)
@app.errorhandler(404)
def page_not_found(e):
# note that we set the 404 status explicitly
return render_template('404.html'), 404
@socketio.on('incoming-msg')
def on_message(data):
"""Broadcast messages"""
msg = data["msg"]
username = data["username"]
room = data["room"]
# Set timestamp
time_stamp = time.strftime('%b-%d %I:%M%p', time.localtime())
send({"username": username, "msg": msg, "time_stamp": time_stamp}, room=room)
@socketio.on('join')
def on_join(data):
"""User joins a room"""
username = data["username"]
room = data["room"]
join_room(room)
# Broadcast that new user has joined
send({"msg": username + " has joined the " + room + " room."}, room=room)
@socketio.on('leave')
def on_leave(data):
"""User leaves a room"""
username = data['username']
room = data['room']
leave_room(room)
send({"msg": username + " has left the room"}, room=room)
if __name__ == "__main__":
app.run(debug=True)