realms-wiki/realms/__init__.py

218 lines
6.1 KiB
Python
Raw Normal View History

2013-09-26 16:51:15 +03:00
import logging
2013-09-30 17:34:16 +03:00
import os
2013-10-02 04:50:48 +03:00
import time
2013-10-02 07:32:53 +03:00
import redis
import rethinkdb as rdb
2013-10-03 17:58:07 +03:00
from flask import Flask, request, render_template, url_for, redirect, flash, session
2013-09-26 16:51:15 +03:00
from flask.ext.bcrypt import Bcrypt
2013-10-03 17:58:07 +03:00
from flask.ext.login import LoginManager, login_user, logout_user
2013-09-26 16:51:15 +03:00
from flask.ext.assets import Environment
2013-10-02 07:32:53 +03:00
from recaptcha.client import captcha
2013-10-03 17:58:07 +03:00
from werkzeug.routing import BaseConverter
2013-10-02 07:32:53 +03:00
import config
2013-09-26 16:51:15 +03:00
from session import RedisSessionInterface
from wiki import Wiki
2013-10-01 07:10:10 +03:00
from util import to_canonical, remove_ext
2013-10-02 07:32:53 +03:00
2013-09-26 16:51:15 +03:00
2013-10-03 17:58:07 +03:00
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
2013-09-26 16:51:15 +03:00
app = Flask(__name__)
app.config.update(config.flask)
app.debug = (config.ENV is not 'PROD')
app.secret_key = config.secret_key
2013-09-30 17:34:16 +03:00
app.static_path = os.sep + 'static'
2013-09-26 16:51:15 +03:00
app.session_interface = RedisSessionInterface()
2013-10-03 17:58:07 +03:00
app.url_map.converters['regex'] = RegexConverter
2013-09-26 16:51:15 +03:00
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
assets = Environment(app)
assets.url = app.static_url_path
assets.directory = app.static_folder
cache = redis.StrictRedis(host=config.cache['host'], port=config.cache['port'])
2013-09-30 17:34:16 +03:00
conn = rdb.connect(config.db['host'], config.db['port'], db=config.db['dbname'])
2013-09-30 17:34:16 +03:00
if not config.db['dbname'] in rdb.db_list().run(conn) and config.ENV is not 'PROD':
# Create default db and repo
print "Creating DB %s" % config.db['dbname']
rdb.db_create(config.db['dbname']).run(conn)
for tbl in ['sites', 'users', 'pages']:
rdb.table_create(tbl).run(conn)
2013-10-01 07:10:10 +03:00
repo_dir = config.repo['dir']
2013-09-30 17:34:16 +03:00
2013-10-03 17:58:07 +03:00
# This is down here because of dependencies above
from models import Site, User, CurrentUser
@login_manager.user_loader
def load_user(user_id):
return CurrentUser(user_id)
2013-09-30 17:34:16 +03:00
w = Wiki(repo_dir)
2013-09-26 16:51:15 +03:00
def redirect_url():
return request.args.get('next') or request.referrer or url_for('index')
2013-10-03 17:58:07 +03:00
def validate_captcha():
response = captcha.submit(
request.form['recaptcha_challenge_field'],
request.form['recaptcha_response_field'],
app.config['RECAPTCHA_PRIVATE_KEY'],
request.remote_addr)
return response.is_valid
2013-10-02 04:50:48 +03:00
@app.template_filter('datetime')
def _jinja2_filter_datetime(ts):
return time.strftime('%b %d, %Y %I:%M %p', time.localtime(ts))
2013-09-26 16:51:15 +03:00
@app.errorhandler(404)
def page_not_found(e):
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def page_error(e):
logging.exception(e)
return render_template('errors/500.html'), 500
2013-09-26 16:51:15 +03:00
@app.route("/")
def root():
2013-10-03 17:58:07 +03:00
return render('home')
#return redirect('/home')
@app.route("/account/")
def account():
return render_template('account/index.html')
@app.route("/logout/")
def logout():
logout_user()
del session['user']
return redirect(url_for('root'))
2013-10-02 04:50:48 +03:00
@app.route("/commit/<sha>/<name>")
def commit_sha(name, sha):
cname = to_canonical(name)
data = w.get_page(cname, sha=sha)
if data:
return render_template('page/page.html', page=data)
else:
return redirect('/create/'+cname)
2013-10-03 17:58:07 +03:00
@app.route("/compare/<name>/<regex('[^.]+'):fsha><regex('\.{2,3}'):dots><regex('.+'):lsha>")
def compare(name, fsha, dots, lsha):
diff = w.compare(name, fsha, lsha)
return render_template('page/compare.html', name=name, diff=diff)
2013-10-02 04:50:48 +03:00
@app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == 'POST':
2013-10-03 17:58:07 +03:00
user = User()
if user.get_by_email(request.form['email']):
flash('Email is already taken')
return redirect('/register')
if user.get_by_username(request.form['username']):
flash('Username is already taken')
return redirect('/register')
# Create user and login
u = User.create(email=request.form['email'].lower(),
username=request.form['username'],
password=bcrypt.generate_password_hash(request.form['password']))
login_user(u)
return redirect("/")
2013-10-02 04:50:48 +03:00
else:
return render_template('account/register.html')
@app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
2013-10-03 17:58:07 +03:00
if User.auth(request.form['email'], request.form['password']):
return redirect("/")
else:
flash("Email or Password invalid")
return redirect("/login")
2013-10-02 04:50:48 +03:00
else:
return render_template('account/login.html')
@app.route("/history/<name>")
def history(name):
history = w.get_history(name)
return render_template('page/history.html', name=name, history=history)
2013-10-01 07:10:10 +03:00
@app.route("/edit/<name>", methods=['GET', 'POST'])
def edit(name):
data = w.get_page(name)
cname = to_canonical(name)
if request.method == 'POST':
edit_cname = to_canonical(request.form['name'])
if edit_cname != cname:
w.rename_page(cname, edit_cname)
2013-10-02 04:50:48 +03:00
w.write_page(edit_cname, request.form['content'], message=request.form['message'])
2013-10-01 07:10:10 +03:00
return redirect("/" + edit_cname)
2013-09-29 00:33:00 +03:00
else:
2013-10-01 07:10:10 +03:00
if data:
name = remove_ext(data['name'])
content = data['data']
return render_template('page/edit.html', name=name, content=content)
else:
return redirect('/create/'+cname)
2013-10-01 07:10:10 +03:00
@app.route("/delete/<name>", methods=['POST'])
def delete(name):
pass
2013-10-02 04:50:48 +03:00
@app.route("/create/", methods=['GET', 'POST'])
2013-10-01 07:10:10 +03:00
@app.route("/create/<name>", methods=['GET', 'POST'])
2013-10-02 04:50:48 +03:00
def create(name=None):
cname = ""
if name:
cname = to_canonical(name)
if w.get_page(cname):
# Page exists, edit instead
return redirect("/edit/" + cname)
2013-10-01 07:10:10 +03:00
if request.method == 'POST':
2013-10-02 04:50:48 +03:00
w.write_page(request.form['name'], request.form['content'], message=request.form['message'], create=True)
2013-10-01 07:10:10 +03:00
return redirect("/" + cname)
else:
2013-10-02 04:50:48 +03:00
return render_template('page/edit.html', name=cname, content="")
2013-10-01 07:10:10 +03:00
2013-09-26 16:51:15 +03:00
2013-10-01 07:10:10 +03:00
@app.route("/<name>")
def render(name):
cname = to_canonical(name)
if cname != name:
return redirect('/' + cname)
2013-10-01 07:10:10 +03:00
data = w.get_page(cname)
2013-09-29 00:33:00 +03:00
if data:
2013-10-02 04:50:48 +03:00
return render_template('page/page.html', name=cname, page=data)
else:
2013-10-01 07:10:10 +03:00
return redirect('/create/'+cname)
2013-09-26 16:51:15 +03:00
import ratelimit