added database support

This commit is contained in:
iou1name 2018-06-15 18:13:59 -04:00
parent 4c526cb1e7
commit f2446bf0c4
5 changed files with 93 additions and 5 deletions

4
.gitignore vendored
View File

@ -1,3 +1,5 @@
__pycache__/
*.cfg
*.swp
__pycache__/
secret_key
db_key

View File

@ -3,7 +3,22 @@ By popular demand, I'm building a better anonkun. It doesn't do much right now t
## Requirements
Python 3.6+
Python packages: `flask flask_socketio`
MariaDB 10.2+
Python packages: `flask flask_socketio flask-paranoid passlib argon2_cffi`
## Install
```
$ mysql -u root -p
mysql> CREATE DATABASE `anonkun` DEFAULT CHARACTER SET `utf8mb4` COLLATE `utf8mb4_general_ci`;
mysql> CREATE USER `anonkun`@'localhost' IDENTIFIED BY 'password';
mysql> GRANT ALL PRIVILEGES ON `anonkun`.* TO `anonkun`@`localhost`;
mysql> \q
```
1. Get on the floor
2. Walk the dinosaur
## Usage
`gunicorn -b localhost:5050 --worker-class eventlet anonkun:app`
## Todo
Rename this project to something that doesn't mean "shit" in weebspeak.

View File

@ -8,6 +8,8 @@ import time
from flask import Flask, session, request, abort, redirect, url_for, g, \
render_template
from flask_socketio import SocketIO, emit, join_room
from flask_paranoid import Paranoid
import MySQLdb
class ReverseProxied(object):
"""
@ -46,9 +48,52 @@ class ReverseProxied(object):
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.config['SECRET_KEY'] = 'secret!'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
socketio = SocketIO(app)
paranoid = Paranoid(app)
paranoid.redirect_view = 'index'
def db_execute(*args, **kwargs):
"""
Opens a connection to the app's database and executes the SQL statements
passed to this function.
"""
passwd = app.config.get("DB_KEY")
with MySQLdb.connect(user="anonkun", passwd=passwd, db="anonkun") as cur:
cur.execute(*args, **kwargs)
return cur
def init():
"""
Initializes the application.
"""
# init secret key
if os.path.exists("secret_key"):
with open("secret_key", "rb") as file:
secret_key = file.read()
else:
secret_key = os.urandom(64)
with open("secret_key", "wb") as file:
file.write(secret_key)
app.secret_key = secret_key
# init db
with open("db_key", "r") as file:
passwd = file.read().strip() # TODO: encrypt this
app.config["DB_KEY"] = passwd
try:
db_execute("SELECT * FROM `users`").fetchone()
except MySQLdb.ProgrammingError: # database not initialized
with open("anonkun.sql", "r") as file:
commands = file.read().split(";")
for cmd in commands:
cmd = cmd.strip()
if not cmd:
continue
db_execute(cmd)
@socketio.on('joined', namespace="/chat")
def joined(data):
@ -57,7 +102,6 @@ def joined(data):
"""
room = data["room"]
join_room(room)
print("Client connected.")
@socketio.on('message', namespace="/chat")
@ -100,3 +144,8 @@ def index():
The index page.
"""
return render_template("index.html")
init()
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5050)

23
anonkun.sql Normal file
View File

@ -0,0 +1,23 @@
CREATE TABLE `users` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(20) NOT NULL,
`password_hash` CHAR(73) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET utf8mb4;
CREATE TABLE `quests` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`canon_title` VARCHAR(300) DEFAULT NULL,
`ident_title` VARCHAR(300) DEFAULT NULL,
`owner_id` SMALLINT UNSIGNED DEFAULT NULL,
`quest_data` MEDIUMTEXT DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET utf8mb4;
CREATE TABLE `chat_messages` (
`room_id` SMALLINT UNSIGNED NOT NULL,
`name` VARCHAR(20) NOT NULL,
`name_id` SMALLINT UNSIGNED DEFAULT NULL,
`date` INT UNSIGNED NOT NULL,
`message` TEXT NOT NULL
) ENGINE=InnoDB CHARSET utf8mb4;

View File

@ -46,7 +46,6 @@
<body>
<div id="questBody">
<h1>Unga Bunga Quest</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget ullamcorper orci. Proin feugiat nibh quam, ut cursus nulla varius et. Integer a massa magna. Pellentesque euismod luctus congue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin eu urna dapibus, accumsan diam nec, consectetur odio. Integer porta dignissim odio, non laoreet orci hendrerit et. Donec vitae egestas ligula, ut accumsan tortor.