forked from doctorn/graphed
/
__init__.py
375 lines (336 loc) · 12.4 KB
/
__init__.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
from flask import request, Flask, render_template, Markup, redirect, jsonify, redirect
from .database import engine, User, Token, Workspace, Note, Connection
from .error import MissingInformation, InvalidInformation
import sqlalchemy as db
from sqlalchemy import sql, update
from binascii import b2a_hex, a2b_hex
from hashlib import sha256
from os import urandom, path
import re
app = Flask(__name__)
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
def check_credentials(username, password):
hasher = sha256()
hasher.update(password.encode("utf8"))
passhash = hasher.digest()
conn = engine.connect()
query = sql.select([User.__table__]).where(
(User.username == username.lower())
& (User.passhash == passhash)
)
for row in conn.execute(query).fetchall():
return row
else:
return None
def authenticate():
token = request.cookies.get("token")
if token is None:
raise MissingInformation("token")
token_bin = a2b_hex(token)
conn = engine.connect()
query = sql.select([Token.__table__])\
.limit(1)\
.where(Token.token == token_bin)
row = conn.execute(query).fetchone()
if row is not None:
return row.user
else:
raise MissingInformation("valid credentials")
# Return a list of all users workspaces
@app.route("/api/workspaces")
def get_workspaces():
try:
owner = authenticate()
conn = engine.connect()
# define query for db request to get workspaces
workspace_query = sql.select([Workspace.__table__])\
.where(Workspace.owner == owner)
workspaces = conn.execute(workspace_query).fetchall()
workspace_list = []
for workspace in workspaces:
workspace_list.append({
"id": workspace.id,
"name": workspace.name
})
return jsonify({
"status" : "ok",
"workspaces" : workspace_list
})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Create new workspace and return id
@app.route("/api/workspace/create/<name>")
def create_workspace(name):
try:
owner = authenticate()
conn = engine.connect()
query = sql.insert(Workspace.__table__,
values={
Workspace.name: name,
Workspace.owner: owner
}
)
result = conn.execute(query)
return jsonify({
"status": "ok",
"id": result.lastrowid,
})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Return all notes and connections in workspace (list of notes)
@app.route("/api/workspace/<int:id>")
def get_workspace(id):
try:
owner = authenticate()
conn = engine.connect()
# define query for db request to get all nodes for workspace id
notes_query = sql.select([Note.__table__])\
.where(Note.workspace == id)
# define query for db request to get all nodes for workspace id
connections_query = sql.select([Connection.__table__])\
.where(Connection.workspace == id)
notes = conn.execute(notes_query).fetchall()
connections = conn.execute(connections_query).fetchall()
workspace_notes = []
for note in notes:
workspace_notes.append({
"id": note.id,
"name": note.name
})
workspace_connections = []
for connection in connections:
workspace_connections.append({
"id" : connection.id,
"origin" : connection.origin,
"target" : connection.target,
})
return jsonify({
"status" : "ok",
"notes" : workspace_notes,
"connections" : workspace_connections,
})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Delete workspace and return id
@app.route("/api/workspace/delete/<int:id>")
def delete_workspace(id):
try:
owner = authenticate()
conn = engine.connect()
query = sql.delete(Note.__table__, Note.workspace == id)
result = conn.execute(query)
query = sql.delete(Connection.__table__, Connection.workspace == id)
result = conn.execute(query)
query = sql.delete(Workspace.__table__, Workspace.id == id)
result = conn.execute(query)
return jsonify({"status" : "ok", "message": "deleted"})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Issue login token
@app.route("/api/token", methods=['POST'])
def get_token():
try:
username = request.form["username"]
password = request.form["password"]
if username is None:
raise MissingInformation("username")
if password is None:
raise MissingInformation("password")
except MissingInformation as e:
return jsonify({ "status": "error", "message": e.message })
username = username.lower()
user = check_credentials(username, password)
if user is None:
return jsonify({"status": "error", "message": "Invalid login"})
conn = engine.connect()
query = sql.select([Token.__table__])\
.limit(1)\
.where(Token.id == user.id)
res = conn.execute(query)
row = res.fetchone()
if row is None:
hasher = sha256()
hasher.update(urandom(16))
token = hasher.digest()
query = sql.insert(Token.__table__, values={
Token.user: user.id,
Token.token: token,
})
res = conn.execute(query)
token_hex = b2a_hex(token).decode('ascii')
return jsonify({"status": "ok", "token": token_hex});
else:
token_hex = b2a_hex(row.token).decode('ascii')
return jsonify({"status": "ok", "token": token_hex});
# Create user
@app.route("/api/register", methods=['POST'])
def create_user():
conn = engine.connect()
try:
username = request.form["username"]
password = request.form["password"]
if username is None:
raise MissingInformation("username")
if password is None:
raise MissingInformation("password")
except MissingInformation as e:
return jsonify({ "status": "error", "message": e.message })
try:
username = username.lower()
if len(username) < 3:
raise InvalidInformation("username", "Must be at lest 3 characters.")
if len(username) > 32:
raise InvalidInformation("username", "Must be at most 32 characters.")
if re.match("[^a-z0-9]", username):
raise InvalidInformation("username", "Can only contain alphanumeric characters")
query = sql.select([User.id]).where(User.username == username)
res = conn.execute(query)
if bool(len(res.fetchall())):
raise InvalidInformation("username", "A user with that name already exists")
if len(password) < 8:
raise InvalidInformation("password", "Must be at least 8 characters")
if len(password) > 32:
raise InvalidInformation("password", "Must be at most 32 characters")
except InvalidInformation as e:
return jsonify({ "status": "error", "message": e.message })
hasher = sha256()
hasher.update(password.encode("utf8"))
passhash = hasher.digest()
query = sql.insert(User.__table__,
values={
User.username: username,
User.passhash: passhash,
}
)
res = conn.execute(query)
return jsonify({ "status": "ok" })
@app.route("/api/workspace/<int:id>/note/<int:note>")
def get_note(id, note):
try:
owner = authenticate()
filename = "notes/" + str(note) + ".txt"
if path.isfile(filename):
with open(filename, 'r') as content_file:
content = content_file.read()
return jsonify({
"status" : "ok",
"content" : content,
})
else:
return jsonify({"status": "error", "message": "No such note file"})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Create note in workspace
@app.route("/api/workspace/<int:id>/create/<name>")
def create_note(id, name):
try:
owner = authenticate()
conn = engine.connect()
query = sql.insert(Note.__table__,
values={
Note.name: name,
Note.workspace: id
}
)
result = conn.execute(query)
with open("notes/" + str(result.lastrowid) + ".txt", "w") as f:
pass
return jsonify({
"status": "ok",
"note": {
"id": result.lastrowid,
"name": name
}
})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Connect two nodes
@app.route("/api/workspace/<int:id>/connect/<int:origin>/<int:target>")
def connect_notes(id, origin, target):
try:
owner = authenticate()
conn = engine.connect()
if origin < target:
origin_insert = origin
target_insert = target
elif origin > target:
origin_insert = target
target_insert = origin
else:
raise InvalidInformation("Note cannot reference to itself.")
query = sql.insert(Connection.__table__,
values={
Connection.workspace: id,
Connection.origin: origin_insert,
Connection.target: target_insert,
}
)
result = conn.execute(query)
return jsonify({
"status": "ok",
"connection": {
"id": result.lastrowid,
"origin": origin_insert,
"target": target_insert,
}
})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Update note
@app.route("/api/workspace/<int:id>/update/<int:note>", methods=['POST'])
def update_note(id, note):
try:
owner = authenticate()
content = request.form["content"]
filename = "notes/" + str(note) + ".txt"
if path.isfile(filename):
with open(filename, "w") as f:
f.write(content)
return jsonify({"status": "ok"})
else:
return jsonify({"status": "error", "message": "No such note"})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Remove note from workspace
@app.route("/api/workspace/<int:id>/remove/<int:note>")
def remove_note(id, note):
try:
owner = authenticate()
conn = engine.connect()
query = sql.delete(Note.__table__, Note.id == note)
result = conn.execute(query)
query = sql.delete(Connection.__table__, Connection.origin == note)
result = conn.execute(query)
query = sql.delete(Connection.__table__, Connection.target == note)
result = conn.execute(query)
return jsonify({"status" : "ok", "message": "deleted"})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
# Remove connection from workspace
@app.route("/api/workspace/<int:id>/disconnect/<int:connection>")
def remove_connection(id, connection):
try:
owner = authenticate()
conn = engine.connect()
query = sql.delete(Connection.__table__, Connection.id == connection)
result = conn.execute(query)
return jsonify({"status" : "ok", "message": "deleted"})
except MissingInformation as e:
return jsonify({"status": "error", "message": e.message})
@app.route("/register")
def register():
try:
owner = authenticate()
return redirect("/")
except MissingInformation as e:
return render_template('register.html')
@app.route("/")
def index():
authenticated = False
try:
owner = authenticate()
authenticated = True
except MissingInformation as e:
pass
return render_template('index.html', authenticated=authenticated)