From 863c9e56e14a53299805d8855a7dc8196c0ecc63 Mon Sep 17 00:00:00 2001 From: Marc Vilanova Date: Mon, 18 Oct 2021 16:32:30 -0700 Subject: [PATCH] Improves user get or create to avoid db integrity errors --- src/dispatch/auth/service.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/dispatch/auth/service.py b/src/dispatch/auth/service.py index 28027b5276cf..ce30a9bfcde9 100644 --- a/src/dispatch/auth/service.py +++ b/src/dispatch/auth/service.py @@ -138,11 +138,16 @@ def create(*, db_session, organization: str, user_in: UserRegister) -> DispatchU def get_or_create(*, db_session, organization: str, user_in: UserRegister) -> DispatchUser: """Gets an existing user or creates a new one.""" - try: - return create(db_session=db_session, organization=organization, user_in=user_in) - except IntegrityError: - db_session.rollback() - return get_by_email(db_session=db_session, email=user_in.email) + user = get_by_email(db_session=db_session, email=user_in.email) + + if not user: + try: + user = create(db_session=db_session, organization=organization, user_in=user_in) + except IntegrityError: + db_session.rollback() + log.exception(f"Unable to create user with email address {user_in.email}.") + + return user def update(*, db_session, user: DispatchUser, user_in: UserUpdate) -> DispatchUser: