-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviews.py
More file actions
391 lines (342 loc) · 13.3 KB
/
views.py
File metadata and controls
391 lines (342 loc) · 13.3 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
from datasette import Forbidden, Response, NotFound
from datasette.resources import DatabaseResource, TableResource
from datasette.tokens import TokenRestrictions
from datasette.utils import (
tilde_encode,
tilde_decode,
display_actor,
)
from .utils import ago_difference, format_permissions
import datetime
import json
import time
TOKEN_PAGE_SIZE = 30
async def create_api_token(request, datasette):
await check_permission(datasette, request.actor)
if request.method == "GET":
return Response.html(
await datasette.render_template(
"create_api_token.html",
await _shared(datasette, request),
request=request,
)
)
elif request.method == "POST":
post = await request.post_vars()
errors = []
expires_after = None
if post.get("expire_type"):
duration_string = post.get("expire_duration")
if (
not duration_string
or not duration_string.isdigit()
or not int(duration_string) > 0
):
errors.append("Invalid expire duration")
else:
unit = post["expire_type"]
if unit == "minutes":
expires_after = int(duration_string) * 60
elif unit == "hours":
expires_after = int(duration_string) * 60 * 60
elif unit == "days":
expires_after = int(duration_string) * 60 * 60 * 24
else:
errors.append("Invalid expire duration unit")
# Are there any restrictions?
restrictions = TokenRestrictions()
for key in post:
if key.startswith("all:") and key.count(":") == 1:
restrictions.allow_all(key.split(":")[1])
elif key.startswith("database:") and key.count(":") == 2:
bits = key.split(":")
database = tilde_decode(bits[1])
action = bits[2]
restrictions.allow_database(database, action)
elif key.startswith("resource:") and key.count(":") == 3:
bits = key.split(":")
database = tilde_decode(bits[1])
resource = tilde_decode(bits[2])
action = bits[3]
restrictions.allow_resource(database, resource, action)
# Reuse Datasette signed tokens mechanism to create parts of the token
throwaway_signed_token = await datasette.create_token(
request.actor["id"],
expires_after=expires_after,
restrictions=restrictions,
)
token_bits = datasette.unsign(
throwaway_signed_token[len("dstok_") :], namespace="token"
)
permissions = token_bits.get("_r") or None
config = Config(datasette)
db = config.db
cursor = await db.execute_write(
"""
insert into _datasette_auth_tokens
(secret_version, description, permissions, actor_id, created_timestamp, expires_after_seconds)
values
(:secret_version, :description, :permissions, :actor_id, :created_timestamp, :expires_after_seconds)
""",
{
"secret_version": 0,
"permissions": json.dumps(permissions),
"description": post.get("description") or None,
"actor_id": request.actor["id"],
"created_timestamp": int(time.time()),
"expires_after_seconds": expires_after,
},
)
token = "dsatok_{}".format(datasette.sign(cursor.lastrowid, "dsatok"))
context = await _shared(datasette, request)
context.update({"errors": errors, "token": token, "token_bits": token_bits})
return Response.html(
await datasette.render_template(
"create_api_token.html", context, request=request
)
)
else:
raise Forbidden("Invalid method")
async def check_permission(datasette, actor):
if not actor or not actor.get("id"):
raise Forbidden(
"You must be logged in as an actor with an ID to create a token"
)
if not await datasette.allowed(action="auth-tokens-create", actor=actor):
raise Forbidden("You do not have permission to create a token")
async def _shared(datasette, request):
await check_permission(datasette, request.actor)
db = Config(datasette).db
tokens_exist = bool(
(await db.execute("select 1 from _datasette_auth_tokens limit 1")).first()
)
# Build list of databases and tables the user has permission to view
database_with_tables = []
databases_with_at_least_one_table = []
for database in datasette.databases.values():
if database.name in ("_internal", "_memory"):
continue
db_resource = DatabaseResource(database=database.name)
if not await datasette.allowed(
action="view-database",
resource=db_resource,
actor=request.actor,
):
continue
hidden_tables = await database.hidden_table_names()
tables = []
for table in await database.table_names():
if table in hidden_tables:
continue
table_resource = TableResource(database=database.name, table=table)
if not await datasette.allowed(
action="view-table",
resource=table_resource,
actor=request.actor,
):
continue
tables.append({"name": table, "encoded": tilde_encode(table)})
db_info = {
"name": database.name,
"encoded": tilde_encode(database.name),
"tables": tables,
}
database_with_tables.append(db_info)
if tables:
databases_with_at_least_one_table.append(db_info)
return {
"actor": request.actor,
"all_permissions": [
{"name": key, "description": value.description}
for key, value in datasette.actions.items()
if key
not in (
"auth-tokens-create",
"auth-tokens-revoke-all",
"debug-menu",
"permissions-debug",
)
],
"database_permissions": [
{"name": key, "description": value.description}
for key, value in datasette.actions.items()
if value.takes_parent and not value.takes_child
],
"resource_permissions": [
{"name": key, "description": value.description}
for key, value in datasette.actions.items()
if value.takes_child
],
"database_with_tables": database_with_tables,
"databases_with_at_least_one_table": databases_with_at_least_one_table,
"tokens_exist": tokens_exist,
}
async def tokens_index(datasette, request):
from . import TOKEN_STATUSES, make_expire_function
db = Config(datasette).db
# Expire any tokens that are due for expiring
await db.execute_write_fn(make_expire_function())
next = request.args.get("next")
where_bits = []
params = {}
if next:
where_bits.append("id <= :next")
params["next"] = next
where = " and ".join(where_bits)
# Users can only see their own tokens, unless they have the
# auth-tokens-view-all permission
if not await datasette.allowed(action="auth-tokens-view-all", actor=request.actor):
where_bits.append("actor_id = :actor_id")
params["actor_id"] = request.actor["id"] if request.actor else None
tokens = [
dict(row)
for row in (
await db.execute(
"""
select * from _datasette_auth_tokens
{where} order by id desc limit {limit}
""".format(
where="where {}".format(where) if where else "",
limit=TOKEN_PAGE_SIZE + 1,
),
params,
)
).rows
]
next = None
if len(tokens) == TOKEN_PAGE_SIZE + 1:
next = tokens[-1]["id"]
tokens = tokens[:-1]
for token in tokens:
token["status"] = TOKEN_STATUSES.get(
token["token_status"], token["token_status"]
)
# Resolve actors
actor_ids = set([token["actor_id"] for token in tokens])
actors = await datasette.actors_from_ids(list(actor_ids))
for token in tokens:
actor = actors.get(token["actor_id"])
token["actor"] = actor
token["actor_display"] = display_actor(actor) if actor else None
def _format_permissions(json_string):
return format_permissions(datasette, json.loads(json_string))
return Response.html(
await datasette.render_template(
"tokens_index.html",
{
"tokens": tokens,
"next": next,
"is_first_page": not bool(request.args.get("next")),
"timestamp": _timestamp,
"ago_difference": ago_difference,
"format_permissions": _format_permissions,
"can_create_tokens": await datasette.allowed(
action="auth-tokens-create",
actor=request.actor,
),
},
request=request,
)
)
async def token_details(request, datasette):
from . import TOKEN_STATUSES
config = Config(datasette)
db = config.db
id = request.url_vars["id"]
async def fetch_row():
return (
await db.execute("select * from _datasette_auth_tokens where id = ?", (id,))
).first()
row = await fetch_row()
if row is None:
raise NotFound("Token not found")
# User can manage if they own the token or they have auth-tokens-revoke-all
if not await actor_can_view(datasette, request.actor, row["actor_id"]):
raise Forbidden("You do not have permission to manage this token")
can_revoke = await actor_can_revoke(datasette, request.actor, row["actor_id"])
if (
row["expires_after_seconds"]
and (row["created_timestamp"] + row["expires_after_seconds"]) < time.time()
):
await db.execute_write(
"update _datasette_auth_tokens set token_status='E' where id=:token_id",
{"token_id": id},
)
row = await fetch_row()
if request.method == "POST":
post_vars = await request.post_vars()
if post_vars.get("revoke"):
if not can_revoke:
raise Forbidden("You do not have permission to revoke this token")
else:
await db.execute_write(
"""
update _datasette_auth_tokens
set
token_status = 'R',
ended_timestamp = :now
where id = :id
""",
{"id": id, "now": int(time.time())},
)
return Response.redirect(request.path)
restrictions = "None"
permissions = json.loads(row["permissions"])
if permissions:
restrictions = format_permissions(datasette, permissions)
actors = await datasette.actors_from_ids([row["actor_id"]])
actor_display = None
if actors and actors.get(row["actor_id"]):
actor_display = display_actor(actors[row["actor_id"]])
return Response.html(
await datasette.render_template(
"token_details.html",
{
"token": row,
"actor_display": actor_display,
"token_status": TOKEN_STATUSES.get(
row["token_status"], row["token_status"]
),
"timestamp": _timestamp,
"ago_difference": ago_difference,
"restrictions": restrictions,
"can_revoke": can_revoke,
},
request=request,
)
)
def _timestamp(ts):
if ts:
return datetime.datetime.fromtimestamp(ts).isoformat()
else:
return ""
async def actor_can_view(datasette, actor, token_actor_id):
if not actor or not actor.get("id"):
# Only works for actors that have an ID set
return False
if token_actor_id and str(token_actor_id) == str(actor.get("id")):
return True
# User with auth-tokens-view-all can view any token
return await datasette.allowed(action="auth-tokens-view-all", actor=actor)
async def actor_can_revoke(datasette, actor, token_actor_id):
if not actor or not actor.get("id"):
# Only works for actors that have an ID set
return False
if token_actor_id and str(token_actor_id) == str(actor.get("id")):
return True
# User with auth-tokens-revoke-all can revoke any token
return await datasette.allowed(action="auth-tokens-revoke-all", actor=actor)
class Config:
def __init__(self, datasette):
self._plugin_config = datasette.plugin_config("datasette-auth-tokens") or {}
self._datasette = datasette
self.enabled = self._plugin_config.get("manage_tokens")
def get(self, key):
return self._plugin_config.get(key)
@property
def db(self):
db_name = self._plugin_config.get("manage_tokens_database") or None
if db_name is None:
return self._datasette.get_internal_database()
else:
return self._datasette.get_database(db_name)