From bf7d928823aed4838ccdb17154fd94b692a41dd4 Mon Sep 17 00:00:00 2001 From: guqing Date: Fri, 2 Aug 2024 15:25:33 +0800 Subject: [PATCH] refactor: enforce single OAuth2 account binding per platform --- .../halo/oauth/UserConnectionServiceImpl.java | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/main/java/run/halo/oauth/UserConnectionServiceImpl.java b/src/main/java/run/halo/oauth/UserConnectionServiceImpl.java index 4823bc9..b5c317e 100644 --- a/src/main/java/run/halo/oauth/UserConnectionServiceImpl.java +++ b/src/main/java/run/halo/oauth/UserConnectionServiceImpl.java @@ -40,14 +40,22 @@ public Mono createConnection(String username, UserConnection connection = convert(username, authentication); String providerUserId = authentication.getPrincipal().getName(); - return fetchUserConnection(connection.getSpec().getRegistrationId(), providerUserId) - .flatMap(persisted -> { - connection.getMetadata().setName(persisted.getMetadata().getName()); - connection.getMetadata() - .setVersion(persisted.getMetadata().getVersion()); - return client.update(connection); - }) - .switchIfEmpty(Mono.defer(() -> client.create(connection))); + return findByRegistrationId(connection.getSpec().getRegistrationId()) + .hasElement() + .flatMap(exists -> { + if (exists) { + return Mono.error(new ServerWebInputException( + "已经绑定过 " + connection.getSpec().getRegistrationId() + " 账号,请先解绑")); + } + return fetchUserConnection(connection.getSpec().getRegistrationId(), providerUserId) + .flatMap(persisted -> { + connection.getMetadata().setName(persisted.getMetadata().getName()); + connection.getMetadata() + .setVersion(persisted.getMetadata().getVersion()); + return client.update(connection); + }) + .switchIfEmpty(Mono.defer(() -> client.create(connection))); + }); } @Override @@ -82,6 +90,12 @@ Flux listByRegistrationIdAndUsername(String registrationId, Stri && persisted.getSpec().getUsername().equals(username), null); } + private Mono findByRegistrationId(String registrationId) { + return client.list(UserConnection.class, + persisted -> persisted.getSpec().getRegistrationId().equals(registrationId), null) + .next(); + } + private Mono fetchUserConnection(String registrationId, String providerUserId) { return client.list(UserConnection.class, persisted -> persisted.getSpec() .getProviderUserId().equals(providerUserId)