-
-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy path0079_apitoken_data.py
More file actions
60 lines (46 loc) · 1.78 KB
/
0079_apitoken_data.py
File metadata and controls
60 lines (46 loc) · 1.78 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
# Generated by Django 6.0.3 on 2026-03-10 22:09
from django.db import migrations
from django.contrib.auth.hashers import make_password
def migrate_api_tokens(apps, schema_editor):
"""Migrate existing plain-text DRF tokens to the new hashed APIToken model."""
APIToken = apps.get_model("scanpipe", "APIToken")
PREFIX_LENGTH = 8
with schema_editor.connection.cursor() as cursor:
cursor.execute(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables "
"WHERE table_name = 'authtoken_token')"
)
table_exists = cursor.fetchone()[0]
if not table_exists:
return
cursor.execute("SELECT user_id, key, created FROM authtoken_token")
rows = cursor.fetchall()
if not rows:
return
tokens_to_create = [
APIToken(
user_id=user_id,
prefix=key[:PREFIX_LENGTH],
key_hash=make_password(key),
created=created,
)
for user_id, key, created in rows
]
migrated_tokens = APIToken.objects.bulk_create(tokens_to_create, ignore_conflicts=True)
if migrated_tokens:
print(f" -> {len(migrated_tokens)} tokens migrated.")
def reverse_migrate_api_tokens(apps, schema_editor):
"""Reverse migration: remove all migrated tokens."""
APIToken = apps.get_model("scanpipe", "APIToken")
APIToken.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
('scanpipe', '0078_apitoken'),
]
operations = [
migrations.RunPython(migrate_api_tokens, reverse_migrate_api_tokens),
migrations.RunSQL(
sql="DROP TABLE IF EXISTS authtoken_token",
reverse_sql=migrations.RunSQL.noop,
),
]