Skip to content

Commit f0099b4

Browse files
committed
add data migration to convert authtoken to APIToken
Signed-off-by: tdruez <tdruez@aboutcode.org>
1 parent 286ea11 commit f0099b4

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Generated by Django 6.0.3 on 2026-03-10 22:09
2+
3+
from django.db import migrations
4+
from django.contrib.auth.hashers import make_password
5+
6+
7+
def migrate_api_tokens(apps, schema_editor):
8+
"""Migrate existing plain-text DRF tokens to the new hashed APIToken model."""
9+
APIToken = apps.get_model("scanpipe", "APIToken")
10+
PREFIX_LENGTH = 8
11+
12+
with schema_editor.connection.cursor() as cursor:
13+
cursor.execute(
14+
"SELECT EXISTS (SELECT 1 FROM information_schema.tables "
15+
"WHERE table_name = 'authtoken_token')"
16+
)
17+
table_exists = cursor.fetchone()[0]
18+
19+
if not table_exists:
20+
return
21+
22+
cursor.execute("SELECT user_id, key, created FROM authtoken_token")
23+
rows = cursor.fetchall()
24+
if not rows:
25+
return
26+
27+
tokens_to_create = [
28+
APIToken(
29+
user_id=user_id,
30+
prefix=key[:PREFIX_LENGTH],
31+
key_hash=make_password(key),
32+
created=created,
33+
)
34+
for user_id, key, created in rows
35+
]
36+
migrated_tokens = APIToken.objects.bulk_create(tokens_to_create, ignore_conflicts=True)
37+
if migrated_tokens:
38+
print(f" -> {len(migrated_tokens)} tokens migrated.")
39+
40+
41+
def reverse_migrate_api_tokens(apps, schema_editor):
42+
"""Reverse migration: remove all migrated tokens."""
43+
APIToken = apps.get_model("scanpipe", "APIToken")
44+
APIToken.objects.all().delete()
45+
46+
47+
class Migration(migrations.Migration):
48+
49+
dependencies = [
50+
('scanpipe', '0078_apitoken'),
51+
]
52+
53+
operations = [
54+
migrations.RunPython(migrate_api_tokens, reverse_migrate_api_tokens),
55+
migrations.RunSQL(
56+
sql="DROP TABLE IF EXISTS authtoken_token",
57+
reverse_sql=migrations.RunSQL.noop,
58+
),
59+
]
60+

0 commit comments

Comments
 (0)