|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# author: greyshell |
| 4 | + |
| 5 | +import os |
| 6 | + |
| 7 | +from flask import Flask, render_template, session, redirect, url_for, jsonify |
| 8 | +from flask import request |
| 9 | +from flask_wtf.csrf import CSRFProtect |
| 10 | +from web.login.models import * |
| 11 | + |
| 12 | +templates_path = os.path.abspath( |
| 13 | + './template/' |
| 14 | +) |
| 15 | +app = Flask(__name__, template_folder=templates_path) |
| 16 | +app.config.update(dict( |
| 17 | + SECRET_KEY="woopie" |
| 18 | +)) |
| 19 | +csrf = CSRFProtect(app) |
| 20 | + |
| 21 | + |
| 22 | +def get_logged_in_user(): |
| 23 | + if "userid" not in session: |
| 24 | + return None |
| 25 | + return User.logged_user(session['userid']) |
| 26 | + |
| 27 | + |
| 28 | +@app.before_request |
| 29 | +def before_request_func(): |
| 30 | + MySQLdb() # create database |
| 31 | + |
| 32 | + |
| 33 | +@app.after_request |
| 34 | +def after_request_func(response): |
| 35 | + MySQLdb.close() |
| 36 | + return response |
| 37 | + |
| 38 | + |
| 39 | +@app.route('/', methods=['GET', 'POST']) |
| 40 | +@csrf.exempt |
| 41 | +def index(): |
| 42 | + user = get_logged_in_user() |
| 43 | + if user is not None: |
| 44 | + return redirect(url_for('welcome')) |
| 45 | + if request.method == 'GET': |
| 46 | + return render_template("index.html") |
| 47 | + username = request.form.get('username') |
| 48 | + password = request.form.get('password') |
| 49 | + user = User.get_user(username, password) |
| 50 | + if not user: |
| 51 | + return render_template("index.html", error="User not found") |
| 52 | + session['userid'] = user.id |
| 53 | + return redirect(url_for('welcome')) |
| 54 | + |
| 55 | + |
| 56 | +@app.route('/welcome', methods=['GET']) |
| 57 | +def welcome(): |
| 58 | + user = get_logged_in_user() |
| 59 | + if user is None: |
| 60 | + return redirect(url_for("index")) |
| 61 | + return render_template('welcome.html', user=user) |
| 62 | + |
| 63 | + |
| 64 | +@app.route('/update_age', methods=['POST']) |
| 65 | +def update_age(): |
| 66 | + user = get_logged_in_user() |
| 67 | + if user is None: |
| 68 | + return jsonify(status="User not logged in") |
| 69 | + age = int(request.form.get('age')) |
| 70 | + user.age = age |
| 71 | + success = user.save() |
| 72 | + if success[0]: |
| 73 | + return jsonify(status="Age successfully changed") |
| 74 | + else: |
| 75 | + return jsonify(status="error " + success[1]) |
| 76 | + |
| 77 | + |
| 78 | +@app.route('/logout') |
| 79 | +@csrf.exempt |
| 80 | +def logout(): |
| 81 | + if 'userid' in session: |
| 82 | + session['userid'] = None |
| 83 | + return redirect(url_for('index')) |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == '__main__': |
| 87 | + app.run(port=5000, debug=True) |
0 commit comments