diff --git a/src/main/java/com/MeetMate/company/CompanyService.java b/src/main/java/com/MeetMate/company/CompanyService.java index 49f53f7..b282145 100644 --- a/src/main/java/com/MeetMate/company/CompanyService.java +++ b/src/main/java/com/MeetMate/company/CompanyService.java @@ -49,7 +49,7 @@ public void createCompany(String companyName, String ownerEmail, String ownerNam ownerData.add("role", UserRole.COMPANY_OWNER.toString()); ownerData.add("associatedCompany", String.valueOf(companyId)); - userController.registerNewUser(ownerEmail, ownerPassword, ownerName); + userController.registerNewUser(ownerData); companyRepository.save(new Company(companyId, companyName, ownerEmail)); sequenceService.incrementId(); diff --git a/src/main/java/com/MeetMate/user/UserController.java b/src/main/java/com/MeetMate/user/UserController.java index 35da5cf..33ce42c 100644 --- a/src/main/java/com/MeetMate/user/UserController.java +++ b/src/main/java/com/MeetMate/user/UserController.java @@ -1,17 +1,17 @@ package com.MeetMate.user; import jakarta.persistence.EntityNotFoundException; -import javax.naming.NameAlreadyBoundException; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InternalAuthenticationServiceException; -import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; -import java.util.Arrays; +import javax.naming.NameAlreadyBoundException; + +//.body("message: " + t.getMessage() + "\nStack trace: " + Arrays.toString(t.getStackTrace())); @RestController @RequestMapping(path = "api/user") @@ -52,25 +52,23 @@ public ResponseEntity getAllUsers() { @PostMapping(path = "signup") @ResponseBody - public ResponseEntity registerNewUser( - @RequestParam String email, - @RequestParam String password, - @RequestParam String name) { - - System.out.println("Received signup request for email: " + email); - + public ResponseEntity registerNewUser(@RequestParam MultiValueMap data) { try { - MultiValueMap data = new LinkedMultiValueMap<>(); - data.add("email", email); - data.add("password", password); - data.add("name", name); - userService.registerNewUser(data); return ResponseEntity.ok().build(); + } catch (Throwable t) { - System.out.println("Error in registerNewUser " + t); + Class tc = t.getClass(); + + if (tc == IllegalArgumentException.class) + return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("message: " + t.getMessage()); + + if (tc == NameAlreadyBoundException.class) + return ResponseEntity.status(HttpStatus.CONFLICT) + .body("message: " + t.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("message: " + t.getMessage() + "\nStack trace: " + Arrays.toString(t.getStackTrace())); + .body("message: " + t.getMessage()); } } diff --git a/src/main/java/com/MeetMate/user/UserService.java b/src/main/java/com/MeetMate/user/UserService.java index 4d96c7a..a273e13 100644 --- a/src/main/java/com/MeetMate/user/UserService.java +++ b/src/main/java/com/MeetMate/user/UserService.java @@ -34,17 +34,17 @@ public GetResponse getUserByEmail(String token) { Optional userOptional = userRepository.findUserByEmail(email); User user = - userRepository - .findUserByEmail(email) - .orElseThrow(() -> new EntityNotFoundException("User does not exist")); + userRepository + .findUserByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("User does not exist")); return GetResponse.builder() - .id(user.getId()) - .name(user.getName()) - .created_at(user.getCreatedAt()) - .email(user.getEmail()) - .role(user.getRole()) - .build(); + .id(user.getId()) + .name(user.getName()) + .created_at(user.getCreatedAt()) + .email(user.getEmail()) + .role(user.getRole()) + .build(); } public List getAllUsers() { @@ -57,35 +57,39 @@ public void registerNewUser(MultiValueMap data) throws NameAlrea String name = data.getFirst("name"); String password = data.getFirst("password"); String role = data.getFirst("role"); - - // Make associatedCompany truly optional - Long associatedCompany = null; String associatedCompanyStr = data.getFirst("associatedCompany"); - if (associatedCompanyStr != null && !associatedCompanyStr.isEmpty()) { - try { - associatedCompany = Long.parseLong(associatedCompanyStr); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid associatedCompany value", e); - } - } + Long associatedCompany = null; // Validate required fields - if (email == null || email.isEmpty() || password == null || password.isEmpty() || name == null || name.isEmpty()) { + if (email == null || email.isEmpty() + || password == null || password.isEmpty() + || name == null || name.isEmpty()) { throw new IllegalArgumentException("Email, password, and name are required"); } + if (userRepository.findUserByEmail(email).isPresent()) + throw new NameAlreadyBoundException("Email already taken"); + // Set default role if not provided UserRole userRole = (role == null || role.isEmpty()) ? UserRole.CLIENT : UserRole.valueOf(role); User user = new User(name, email, passwordEncoder.encode(password), userRole); - // Only set associatedCompany if it's provided - if (associatedCompany != null) { - user.setAssociatedCompany(associatedCompany); - } else if (userRole == UserRole.CLIENT) { - user.setAssociatedCompany(-1L); - } else if (userRole == UserRole.COMPANY_OWNER || userRole == UserRole.COMPANY_MEMBER) { - throw new IllegalArgumentException("associatedCompany is required for COMPANY_OWNER and COMPANY_MEMBER roles"); + if (associatedCompanyStr != null && !associatedCompanyStr.isEmpty()) + try { + associatedCompany = Long.parseLong(associatedCompanyStr); + } catch (NumberFormatException nfe) { + throw new IllegalArgumentException("Invalid associatedCompany value", nfe); + } + + switch (userRole) { + case CLIENT -> user.setAssociatedCompany(-1L); + case COMPANY_OWNER, COMPANY_MEMBER -> { + if (associatedCompany != null) user.setAssociatedCompany(associatedCompany); + else + throw new IllegalArgumentException("associatedCompany is required for COMPANY_OWNER and COMPANY_MEMBER roles"); + } + default -> throw new IllegalStateException(role + " is invalid!"); } userRepository.save(user); @@ -98,9 +102,9 @@ public void updateUser(String token, MultiValueMap data) { String password = passwordEncoder.encode(data.getFirst("password")); User user = - userRepository - .findUserByEmail(email) - .orElseThrow(() -> new EntityNotFoundException("User does not exist.")); + userRepository + .findUserByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("User does not exist.")); if (password != null) user.setPassword(password); if (name != null) user.setName(name); @@ -114,39 +118,39 @@ public AuthenticationResponse authenticateUser(MultiValueMap dat authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password)); User user = - userRepository - .findUserByEmail(email) - .orElseThrow(() -> new EntityNotFoundException("User does not exist")); + userRepository + .findUserByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("User does not exist")); String token = jwtService.generateAccessToken(user); String refresh = jwtService.generateRefreshToken(user); user.setRefreshToken(refresh); long exp = - jwtService.extractClaim(token, Claims::getExpiration).getTime() - / 1000; // expiration time in seconds + jwtService.extractClaim(token, Claims::getExpiration).getTime() + / 1000; // expiration time in seconds return AuthenticationResponse.builder() - .access_Token(token) - .expires_at(exp) - .refresh_Token(refresh) - .build(); + .access_Token(token) + .expires_at(exp) + .refresh_Token(refresh) + .build(); } @Transactional public RefreshResponse refreshAccessToken(String refreshToken) { String email = jwtService.extractUserEmail(refreshToken); User user = - userRepository - .findUserByEmail(email) - .orElseThrow(() -> new EntityNotFoundException("User does not exist")); + userRepository + .findUserByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("User does not exist")); if (!refreshToken.equals(user.getRefreshToken())) throw new IllegalStateException("Refresh token is invalid"); String token = jwtService.generateAccessToken(user); long exp = - jwtService.extractClaim(token, Claims::getExpiration).getTime() - / 1000; // expiration time in seconds + jwtService.extractClaim(token, Claims::getExpiration).getTime() + / 1000; // expiration time in seconds return RefreshResponse.builder().access_Token(token).expires_at(exp).build(); } @@ -155,9 +159,9 @@ public RefreshResponse refreshAccessToken(String refreshToken) { public void deleteUser(String token) { String email = jwtService.extractUserEmail(token); User user = - userRepository - .findUserByEmail(email) - .orElseThrow(() -> new EntityNotFoundException("User does not exist.")); + userRepository + .findUserByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("User does not exist.")); userRepository.deleteByEmail(email); }