Skip to content

Commit 7ebde5c

Browse files
committed
Add facebook account delete option.
1 parent 8341675 commit 7ebde5c

6 files changed

Lines changed: 145 additions & 15 deletions

File tree

‎wise-api/src/main/java/com/wisemapping/dao/UserManager.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,14 @@ public interface UserManager {
152152
List<Account> getUsersWithFilters(String search, Boolean filterActive, Boolean filterSuspended,
153153
String filterAuthType, int offset, int limit);
154154

155+
/**
156+
* Find a Facebook OAuth2 user by their Facebook user ID (stored in oauth_token).
157+
* @param facebookId the Facebook user ID from a data deletion request
158+
* @return the matching account, or null if not found
159+
*/
160+
@Nullable
161+
Account getUserByFacebookId(@NotNull String facebookId);
162+
155163
/**
156164
* Count users matching advanced filtering criteria
157165
* @param search optional search term for email, firstname, or lastname

‎wise-api/src/main/java/com/wisemapping/dao/UserManagerImpl.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,18 @@ public Account getUserByActivationCode(long code) {
240240
return user;
241241
}
242242

243+
@Override
244+
@Nullable
245+
public Account getUserByFacebookId(@NotNull String facebookId) {
246+
final TypedQuery<Account> query = entityManager.createQuery(
247+
"SELECT a FROM Account a WHERE a.authenticationTypeCode = :authType AND a.oauthToken = :facebookId",
248+
Account.class);
249+
query.setParameter("authType", AuthenticationType.FACEBOOK_OAUTH2.getCode());
250+
query.setParameter("facebookId", facebookId);
251+
final List<Account> results = query.getResultList();
252+
return results.isEmpty() ? null : results.get(0);
253+
}
254+
243255
@Override
244256
public List<Account> getAllUsers(int offset, int limit) {
245257
final TypedQuery<Account> query = entityManager.createNamedQuery("Account.getAllUsers", Account.class);

‎wise-api/src/main/java/com/wisemapping/rest/AdminController.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
import org.springframework.beans.factory.annotation.Qualifier;
4747
import org.springframework.beans.factory.annotation.Value;
4848
import org.springframework.http.HttpStatus;
49+
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
4950
import org.springframework.security.access.prepost.PreAuthorize;
5051
import org.springframework.util.StopWatch;
5152
import org.springframework.web.bind.annotation.*;
@@ -93,6 +94,9 @@ public class AdminController {
9394
@Autowired
9495
private EntityManagerFactory entityManagerFactory;
9596

97+
@Autowired(required = false)
98+
private ClientRegistrationRepository clientRegistrationRepository;
99+
96100
@Value("${app.admin.user:}")
97101
private String adminUser;
98102

@@ -103,6 +107,11 @@ private boolean isAdmin(String email) {
103107
return email != null && adminUser != null && email.trim().equals(adminUser);
104108
}
105109

110+
private boolean isFacebookEnabled() {
111+
return clientRegistrationRepository != null
112+
&& clientRegistrationRepository.findByRegistrationId("facebook") != null;
113+
}
114+
106115
@Value("${spring.datasource.driver-class-name:}")
107116
private String datasourceDriver;
108117

@@ -537,6 +546,38 @@ public void deleteUserByEmail(@PathVariable int id) throws WiseMappingException
537546
userService.removeUser(user);
538547
}
539548

549+
@RequestMapping(method = RequestMethod.GET, value = "/users/facebook/{facebookId}", produces = {"application/json"})
550+
@ResponseBody
551+
public RestUser getUserByFacebookId(@PathVariable String facebookId) {
552+
if (!isFacebookEnabled()) {
553+
throw new IllegalStateException("Facebook OAuth2 is not enabled");
554+
}
555+
556+
final com.wisemapping.model.Account user = userService.getUserByFacebookId(facebookId);
557+
if (user == null) {
558+
throw new IllegalArgumentException("No account found for Facebook ID '" + facebookId + "'");
559+
}
560+
return new RestUser(user);
561+
}
562+
563+
@RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}/facebook")
564+
@ResponseStatus(value = HttpStatus.NO_CONTENT)
565+
public void removeFacebookAccount(@PathVariable int id) throws WiseMappingException {
566+
if (!isFacebookEnabled()) {
567+
throw new IllegalStateException("Facebook OAuth2 is not enabled");
568+
}
569+
570+
final Account user = userService.getUserBy(id);
571+
if (user == null) {
572+
throw new IllegalArgumentException("User '" + id + "' could not be found");
573+
}
574+
if (user.getAuthenticationType() != com.wisemapping.model.AuthenticationType.FACEBOOK_OAUTH2) {
575+
throw new IllegalArgumentException("User '" + id + "' is not a Facebook account");
576+
}
577+
578+
userService.removeFacebookAccount(user);
579+
}
580+
540581
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}/maps", produces = {"application/json"})
541582
@ResponseBody
542583
public List<com.wisemapping.rest.model.AdminRestMap> getUserMaps(@PathVariable int id) {

‎wise-api/src/main/java/com/wisemapping/security/OAuth2AuthenticationSuccessHandler.java‎

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,11 @@ public void onAuthenticationSuccess(HttpServletRequest request,
8484
String firstName = extractFirstName(oauth2User);
8585
String lastName = extractLastName(oauth2User);
8686
String provider = extractProvider(request);
87-
87+
String providerId = extractProviderId(oauth2User);
88+
8889
try {
8990
// Find or create WiseMapping account
90-
Account account = findOrCreateOAuthUser(email, firstName, lastName, provider);
91+
Account account = findOrCreateOAuthUser(email, firstName, lastName, provider, providerId);
9192

9293
// Generate JWT token using UserDetails
9394
String jwt = jwtTokenUtil.generateJwtToken(userDetailsService.loadUserByUsername(account.getEmail()));
@@ -203,6 +204,18 @@ private String extractLastName(OAuth2User oauth2User) {
203204
return lastName;
204205
}
205206

207+
private String extractProviderId(OAuth2User oauth2User) {
208+
// Facebook and most OAuth2 providers expose the user's unique ID as "id" or "sub"
209+
Object id = oauth2User.getAttributes().get("id");
210+
if (id != null) {
211+
return id.toString();
212+
}
213+
if (oauth2User instanceof OidcUser) {
214+
return ((OidcUser) oauth2User).getSubject();
215+
}
216+
return null;
217+
}
218+
206219
private String extractProvider(HttpServletRequest request) {
207220
// Extract provider from the callback URL path
208221
String uri = request.getRequestURI();
@@ -213,35 +226,35 @@ private String extractProvider(HttpServletRequest request) {
213226
return "unknown";
214227
}
215228

216-
private Account findOrCreateOAuthUser(String email, String firstName, String lastName, String provider) throws Exception {
229+
private Account findOrCreateOAuthUser(String email, String firstName, String lastName, String provider, String providerId) throws Exception {
217230
AuthenticationType authType = mapProviderToAuthType(provider);
218-
231+
219232
// Check if user exists
220233
Account existingUser = userService.getUserBy(email);
221-
234+
222235
if (existingUser == null) {
223236
// Create new OAuth user
224-
return createNewOAuthUser(email, firstName, lastName, authType);
237+
return createNewOAuthUser(email, firstName, lastName, authType, providerId);
225238
} else {
226-
// Handle existing user
227-
return handleExistingUser(existingUser, authType);
239+
// Handle existing user — also refresh stored provider ID
240+
return handleExistingUser(existingUser, authType, providerId);
228241
}
229242
}
230-
231-
private Account createNewOAuthUser(String email, String firstName, String lastName, AuthenticationType authType) throws Exception {
243+
244+
private Account createNewOAuthUser(String email, String firstName, String lastName, AuthenticationType authType, String providerId) throws Exception {
232245
Account newUser = new Account();
233246
newUser.setEmail(email);
234247
newUser.setFirstname(firstName);
235248
newUser.setLastname(lastName);
236249
newUser.setAuthenticationType(authType);
237-
newUser.setOauthToken("");
250+
newUser.setOauthToken(providerId); // store provider user ID for data deletion lookups
238251
newUser.setPassword("");
239252
newUser.setOauthSync(true);
240-
253+
241254
return userService.createUser(newUser, false, true);
242255
}
243-
244-
private Account handleExistingUser(Account existingUser, AuthenticationType authType) throws Exception {
256+
257+
private Account handleExistingUser(Account existingUser, AuthenticationType authType, String providerId) throws Exception {
245258
AuthenticationType existingAuthType = existingUser.getAuthenticationType();
246259

247260
if (existingAuthType != AuthenticationType.DATABASE && existingAuthType != authType) {
@@ -252,7 +265,13 @@ private Account handleExistingUser(Account existingUser, AuthenticationType auth
252265

253266
// For existing OAuth users with same auth type, update if needed
254267
if (existingAuthType == authType) {
255-
if (existingUser.getOauthSync() == null || !existingUser.getOauthSync()) {
268+
boolean needsUpdate = (existingUser.getOauthSync() == null || !existingUser.getOauthSync());
269+
// Refresh provider ID if it was never stored or has changed
270+
if (providerId != null && !providerId.equals(existingUser.getOauthToken())) {
271+
existingUser.setOauthToken(providerId);
272+
needsUpdate = true;
273+
}
274+
if (needsUpdate) {
256275
existingUser.setOauthSync(true);
257276
existingUser.setSyncCode(null);
258277
userService.updateUser(existingUser);

‎wise-api/src/main/java/com/wisemapping/service/UserService.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,24 @@ Account confirmAccountSync(@NotNull String email,
9191
@NotNull String code,
9292
@org.jetbrains.annotations.Nullable String provider) throws WiseMappingException;
9393

94+
/**
95+
* Remove the Facebook OAuth2 association from a user account.
96+
* Clears stored OAuth token and sync data, reverts authentication type to DATABASE,
97+
* and sends a password-reset email so the user can regain access.
98+
*
99+
* @param user the account whose Facebook association should be removed
100+
* @throws WiseMappingException if the account is not a Facebook OAuth2 account
101+
*/
102+
void removeFacebookAccount(@NotNull Account user) throws WiseMappingException;
103+
104+
/**
105+
* Find a Facebook OAuth2 user by the Facebook user ID received in a data deletion request.
106+
* @param facebookId the Facebook user ID (as sent by Facebook in the deletion callback)
107+
* @return the matching account, or null if not found
108+
*/
109+
@org.jetbrains.annotations.Nullable
110+
Account getUserByFacebookId(@NotNull String facebookId);
111+
94112
/**
95113
* Unsuspend a user and restore their mindmaps if they were suspended for inactivity
96114
* @param user the user to unsuspend

‎wise-api/src/main/java/com/wisemapping/service/UserServiceImpl.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,38 @@ private int rand(int lo, int hi) {
127127
return lo + i;
128128
}
129129

130+
@Override
131+
@Nullable
132+
public Account getUserByFacebookId(@NotNull String facebookId) {
133+
return userManager.getUserByFacebookId(facebookId);
134+
}
135+
136+
@Override
137+
public void removeFacebookAccount(@NotNull Account user) throws WiseMappingException {
138+
if (user.getAuthenticationType() != AuthenticationType.FACEBOOK_OAUTH2) {
139+
throw new WiseMappingException("Account is not a Facebook OAuth2 account");
140+
}
141+
142+
// Reload fresh copy from DB before mutating
143+
final Account managed = userManager.getUserBy(user.getEmail());
144+
145+
// Clear all Facebook-specific OAuth data
146+
managed.setOauthToken(null);
147+
managed.setOauthSync(false);
148+
managed.setSyncCode(null);
149+
150+
// Revert to DATABASE authentication so the account can be accessed via email/password
151+
managed.setAuthenticationType(AuthenticationType.DATABASE);
152+
153+
// Assign a temporary password and send a reset email so the user can regain access
154+
final String tempPassword = randomstring(8, 10);
155+
managed.setPassword(tempPassword);
156+
userManager.updateUser(managed);
157+
notificationService.resetPassword(managed, tempPassword);
158+
159+
logger.info("Facebook account association removed for user {}", managed.getEmail());
160+
}
161+
130162
@Override
131163
public void removeUser(@NotNull Account user) {
132164
// Force object reload before removing....

0 commit comments

Comments
 (0)