File size: 1,138 Bytes
594481c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse

from app.auth import hash_api_key
from app.db import SessionLocal, engine
from app.models import ApiClient, Base


def main() -> None:
    p = argparse.ArgumentParser(description="Insert an API client with a hashed x-api-key.")
    p.add_argument("--name", required=True)
    p.add_argument("--api-key", required=True)
    p.add_argument("--create-all", action="store_true", help="Create tables via SQLAlchemy create_all first.")
    args = p.parse_args()

    if args.create_all:
        Base.metadata.create_all(bind=engine)

    key_hash = hash_api_key(args.api_key)
    with SessionLocal() as db:
        existing = db.query(ApiClient).filter(ApiClient.api_key_hash == key_hash).one_or_none()
        if existing:
            existing.is_active = True
            existing.name = args.name
            db.commit()
            print("API client already existed; updated to active.")
            return
        db.add(ApiClient(name=args.name, api_key_hash=key_hash, is_active=True))
        db.commit()
        print("Inserted API client.")


if __name__ == "__main__":
    main()