diff --git a/data/model/service_keys.py b/data/model/service_keys.py index ac165c9cf..0d27fec4f 100644 --- a/data/model/service_keys.py +++ b/data/model/service_keys.py @@ -1,7 +1,7 @@ from datetime import datetime -from data.model import ServiceKeyDoesNotExist -from data.database import ServiceKey +from data.model import ServiceKeyDoesNotExist, db_transaction +from data.database import db_for_update, ServiceKey, ServiceKeyApproval def _gc_expired(service): ServiceKey.delete().where(ServiceKey.service == service, @@ -12,11 +12,12 @@ def upsert_service_key(kid, service, jwk, expiration_date): _gc_expired(service) try: - key = ServiceKey.select().where(ServiceKey.kid == kid).get() - key.service = service - key.jwk = jwk - key.expiration_date = expiration_date - key.save() + with db_transaction(): + key = db_for_update(ServiceKey.select().where(ServiceKey.kid == kid)).get() + key.service = service + key.jwk = jwk + key.expiration_date = expiration_date + key.save() except ServiceKey.DoesNotExist: ServiceKey.create(kid=kid, service=service, jwk=jwk, expiration_date=expiration_date) @@ -24,14 +25,11 @@ def upsert_service_key(kid, service, jwk, expiration_date): def get_service_keys(service, kid=None): _gc_expired(service) - try: - query = ServiceKey.select().where(ServiceKey.service == service, - ~(ServiceKey.approval >> None)) - if kid: - query.where(ServiceKey.kid == kid) - return query - except ServiceKey.DoesNotExist: - raise ServiceKeyDoesNotExist() + query = ServiceKey.select().where(ServiceKey.service == service, + ~(ServiceKey.approval >> None)) + if kid: + query.where(ServiceKey.kid == kid) + return query def delete_service_key(service, kid): @@ -42,3 +40,15 @@ def delete_service_key(service, kid): ServiceKey.kid == kid).execute() except ServiceKey.DoesNotExist: raise ServiceKeyDoesNotExist() + + +def approve_service_key(service, kid, approver, approval_type): + try: + with db_transaction(): + approval = ServiceKeyApproval.create(approver=approver, approval_type=approval_type) + key = db_for_update(ServiceKey.select().where(ServiceKey.service == service, + ServiceKey.kid == kid)).get() + key.approval = approval + key.save() + except ServiceKey.DoesNotExist: + raise ServiceKeyDoesNotExist