diff --git a/server/mongo/migrations/0.14.0.py b/server/mongo/migrations/0.14.0.py new file mode 100644 index 0000000..4d478f3 --- /dev/null +++ b/server/mongo/migrations/0.14.0.py @@ -0,0 +1,46 @@ +import hashlib + +from pymongo.database import Database, Collection + +from service_repo.auth.fixed_user import FixedUser + + +def _get_ids(): + if not FixedUser.enabled(): + return + + return { + hashlib.md5(f"{user.username}:{user.password}".encode()).hexdigest(): user.user_id + for user in FixedUser.from_config() + } + + +def _switch_uuid(collection: Collection, uuid_field: str, uuids: dict): + docs = list(collection.find({uuid_field: {"$in": [uuids]}})) + if not docs: + return + replaced_uuids = [doc[uuid_field] for doc in docs] + for doc in docs: + doc[uuid_field] = uuids[doc[uuid_field]] + collection.insert_many(docs) + collection.delete_many({uuid_field: {"$in": replaced_uuids}}) + + +def migrate_auth(db: Database): + uuids = _get_ids() + if not uuids: + return + + collection = db["user"] + collection.drop_index("name_1_company_1") + + _switch_uuid(collection=collection, uuid_field="_id", uuids=uuids) + + +def migrate_backend(db: Database): + uuids = _get_ids() + if not uuids: + return + + for name in ("project", "task", "model"): + _switch_uuid(collection=db[name], uuid_field="user", uuids=uuids)