/
app.py
305 lines (232 loc) · 8.18 KB
/
app.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
from flask import Flask, render_template, request, g, redirect, url_for
from flask import make_response
from flask_sqlalchemy import SQLAlchemy
from uuid import uuid4
import random
from datetime import datetime
from flask_oidc import OpenIDConnect
from okta import UsersClient
from config import login_token, def_user, org_url
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/pda.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = "abcd"
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)
okta_client = UsersClient(org_url, login_token)
# Deletes the database. Mostly for testing
def delete_it():
db.reflect()
db.drop_all()
# Creates a couple entries in the database for testing.
def create_it():
db.create_all()
for i in range(5):
j = Journal(name=str(i),desc="My {} item".format(i),user=def_user)
for k in range(random.randint(0,10)):
p = Entry(title="Head {}".format(k+1), body="Oh man {}".format(k))
j.entries.append(p)
db.session.add(j)
db.session.commit()
# OIDC to get the user that is logged in
@app.before_request
def before_request():
if oidc.user_loggedin:
g.user = okta_client.get_user(oidc.user_getfield("sub"))
else:
g.user = None
# Catch 404 errors
@app.errorhandler(404)
@app.errorhandler(405)
def pnf(e):
return redirect(url_for(".page_not_found"))
# Model that represents a journal. A journal is comprised of entries
class Journal(db.Model):
# ID is uuid to be random
id = db.Column('id',db.Text(length=36), default=lambda: str(uuid4()), primary_key=True,unique=True)
# Name of Journal, A Brief description, owner of journal
name = db.Column(db.String(80), nullable=False)
desc = db.Column(db.String(280), nullable=True)
user = db.Column(db.String(280), nullable=False)
def __repr__(self):
return "<Journal {}>".format(self.name)
class Entry(db.Model):
id = db.Column('id',db.Text(length=36), default=lambda: str(uuid4()), primary_key=True,unique=True)
# Title of entry, body of text, date created
title = db.Column(db.String(80), nullable=True)
body = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime, nullable=True,default=datetime.utcnow)
# Link to corresponding journal. "Needed" for ownership check
journal_id = db.Column(db.Text, db.ForeignKey("journal.id"),
nullable=False)
journal = db.relationship("Journal",
backref=db.backref("entries",cascade="all, delete-orphan", lazy=True))
# Following is a ton of different getters for journals and entries. Basically,
# you can get journal(s), entry(s) or the objects that jinja needs
def get_journal(journal_id):
journal = Journal.query.filter_by(id=journal_id).first()
return journal
def get_journals(user_id):
journals = Journal.query.filter_by(user=user_id).all()
return journals
def get_journal_obj(js):
obj = [
{
"link":j.id, "name":j.name,
"desc":j.desc,"entries":j.entries
}
for j in js
]
return obj
def get_entries(journal_id):
journal = Journal.query.filter_by(id=journal_id).first()
return journal.entries
def get_entries_obj(es):
obj = []
for entry in es:
data = {
"title": entry.title,
"body": entry.body,
"date": entry.date.strftime("Created %B %d, %Y at %-I:%M %p"),
"link": entry.id
}
obj.append(data)
return obj
def get_entry(entry_id):
entry = Entry.query.filter_by(id=entry_id).first()
return entry
def get_entry_obj(entry_id):
entry = get_entry(entry_id)
if not entry: return None
obj = {
"title": entry.title,
"body": entry.body,
"date": entry.date.strftime("Created %B %d, %Y at %-I:%M %p"),
"link": entry.id,
"jid": entry.journal_id
}
return obj
# Url for 404 errors
@app.route("/404")
def page_not_found():
return render_template("error.html"), 404
@app.route("/")
def index():
return render_template("index.html")
@app.route("/dashboard")
@oidc.require_login
def dashboard():
return render_template("dashboard.html")
@app.route("/journals")
@oidc.require_login
def journals():
user_id = oidc.user_getfield("sub")
journals = get_journals( user_id )
journals = get_journal_obj( journals )
return render_template("journals.html",ls=journals)
def check_user(ident, is_j=True):
# Get unique user id
user_id = oidc.user_getfield("sub")
if not user_id: return True
# Check if using journal id or a entry id
if is_j:
journal = get_journal(ident)
else:
entry = get_entry(ident)
if not entry: return True
journal = get_journal(entry.journal_id)
if not journal: return True
if user_id == journal.user:
return False
return True
@app.route("/journal/<ident>")
@oidc.require_login
def journal(ident):
if check_user(ident): return redirect(url_for(".page_not_found"))
journal = get_journal(ident)
entries = get_entries(ident)
entries = get_entries_obj(entries)
return render_template("journal.html",es=entries,j=journal)
@app.route("/entry/<ident>")
@oidc.require_login
def entry(ident):
if check_user(ident, False): return redirect(url_for(".page_not_found"))
ent = get_entry_obj(ident)
return render_template("entry.html",entry=ent)
@app.route("/login")
@oidc.require_login
def login():
return redirect(url_for(".journals"))
@app.route("/logout")
def logout():
heads = dict(request.headers)
if check_csrf(heads): return redirect(url_for(".index"))
oidc.logout()
return redirect(url_for(".index"))
def check_csrf(heads):
# Checks to see if needed headers are availible. If not, throw error
if "Origin" not in heads and "Referer" not in heads:
print("CSRF attempt!!!")
return True
if "Host" not in heads:
print("CSRF attempt!!!")
return True
if "Origin" in heads:
attempt = heads["Origin"]
else:
attempt = heads["Referer"]
# If host != origin or referer, error
if attempt != heads["Host"]:
print("CSRF attempt!!!")
return True
return False
@app.route("/newjournal",methods=["GET","POST"])
@oidc.require_login
def newjournal():
if request.method == "GET":
return render_template("form.html",url="/newjournal",data_type="Journal")
heads = dict(request.headers)
if check_csrf(heads): return redirect(url_for(".index"))
user_id = oidc.user_getfield("sub")
values = request.form
j = Journal(name=values["title"],desc=values["body_text"],user=user_id)
db.session.add(j)
db.session.commit()
return redirect(url_for('.journal', ident=j.id))
@app.route("/newentry/<ident>",methods=["GET","POST"])
@oidc.require_login
def newentry(ident):
if check_user(ident): return redirect(url_for(".page_not_found"))
heads = dict(request.headers)
if check_csrf(heads): return redirect(url_for(".index"))
if request.method == "GET":
return render_template("form.html",url="/newentry/"+ident,data_type="Entry")
user_id = oidc.user_getfield("sub")
values = request.form
e = Entry(title=values["title"],body=values["body_text"], journal_id=ident)
db.session.add(e)
db.session.commit()
return redirect(url_for('.entry', ident=e.id))
@app.route("/deletejournal",methods=["POST"])
@oidc.require_login
def deletejournal():
heads = dict(request.headers)
if check_csrf(heads): return redirect(url_for(".index"))
user_id = oidc.user_getfield("sub")
js = Journal.query.filter_by(user=user_id).all()
for j in js:
j.entries.clear()
db.session.add(j)
db.session.commit()
Journal.query.filter_by(user=user_id).delete()
db.session.commit()
return redirect(url_for(".index"))
if __name__ == "__main__":
delete_it()
create_it()
app.run(debug=True)