summaryrefslogtreecommitdiff
path: root/app.py
blob: 6b3e4dadb344bd38a07fc0d6a94f0d1d553a0228 (plain)
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import hashlib
import os
from functools import wraps
from typing import List

from flask import Flask, render_template, abort, url_for, request, redirect, session, jsonify
from tinydb import TinyDB, Query
from tinydb.database import Table, Document

from json_serializable import JsonSerializable, from_json

app = Flask(__name__)

db: Table = TinyDB('projects.json').table()


class Project(JsonSerializable):
    name: str
    description: str
    link: str
    summary: str
    id: str

    def __init__(self, *, name: str = '', description: str = '', link: str = '', summary: str = '', id: str = ''):
        self.name = name
        self.id = id
        self.summary = summary
        self.liink = link
        self.description = description


def check_password(password) -> bool:
    return hashlib.sha256(bytes(os.environ['pepper'] + password, 'utf-8')).hexdigest() == os.environ['password_hash']


@app.context_processor
def inject():
    return {
        'projects': from_json(db.all(), List[Project]),
        'empty_project': Project(),
        'admin': session.get('logged_in', False),
        'no_login': False,
    }


@app.route('/admin/login/', methods=['GET'])
def login():
    return render_template('login.html', return_url=request.args.get('return_url', '/'), no_login=True)


@app.route('/admin/login', methods=['POST'])
def check_login():
    if not check_password(request.form.get('pass')):
        return redirect(url_for('login'))
    session['logged_in'] = True
    return redirect(request.args.get('return_url', '/'))


@app.route('/admin/logout')
def logout():
    session['logged_in'] = False
    return redirect('/')


def require_admin(status: int = 401):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if not session.get('logged_in'):
                abort(status)
            return func(*args, **kwargs)

        return wrapper

    return decorator


def find_project(name) -> Document:
    Q = Query()
    matches = db.search(Q.id == name.lower())
    if len(matches) == 0:
        abort(404)
    return matches[0]


@app.route('/projects/new/')
@require_admin()
def new_project_form():
    return render_template('new.html')


@app.route('/projects/new/', methods=['POST'])
@require_admin()
def new_project():
    id = request.form.get('id')
    Q = Query()
    matches = db.search(Q.id == id.lower())
    if len(matches) != 0:
        abort(400)
    name = request.form.get('name')
    summary = request.form.get('summary')
    description = request.form.get('description')
    link = request.form.get('link')
    db.insert({
        'name': name,
        'id': id,
        'summary': summary,
        'description': description,
        'link': link,
    })
    return redirect(url_for('projects', project_name=id))


@app.route('/projects/<project_name>/edit/', methods=['GET'])
@require_admin()
def edit_project(project_name):
    return render_template('edit_project.html', project=find_project(project_name))


@app.route('/projects/<project_name>/edit/', methods=['POST'])
@require_admin()
def edit_project_data(project_name):
    project: Document = find_project(project_name)
    summary = request.form.get('summary')
    description = request.form.get('description')
    link = request.form.get('link')
    name = request.form.get('name')
    project['name'] = name
    project['link'] = link
    project['description'] = description
    project['summary'] = summary
    db.write_back([project])
    return jsonify({})


@app.route('/projects/<project_name>/')
def projects(project_name):
    return render_template('project.html', project=find_project(project_name))


@app.route('/projects/<project_name>/delete/', methods=['GET'])
@require_admin()
def delete_project(project_name):
    return render_template('delete.html', project=find_project(project_name))


@app.route('/projects/<project_name>/delete/', methods=['POST'])
@require_admin()
def delete_project_confirm(project_name):
    Q = Query()
    db.remove(Q.id == project_name.lower())
    return redirect('/')


@app.route('/')
def index():
    return render_template('index.html')


app.secret_key = os.environ.get('app_secret', '')

if __name__ == '__main__':
    app.run(port=80)