Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reimplemented deleted checks #56

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/java/com/MeetMate/company/CompanyService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
32 changes: 15 additions & 17 deletions src/main/java/com/MeetMate/user/UserController.java
Original file line number Diff line number Diff line change
@@ -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")
Expand Down Expand Up @@ -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<String, String> data) {
try {
MultiValueMap<String, String> 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<? extends Throwable> 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());
}
}

Expand Down
98 changes: 51 additions & 47 deletions src/main/java/com/MeetMate/user/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ public GetResponse getUserByEmail(String token) {
Optional<User> 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<User> getAllUsers() {
Expand All @@ -57,35 +57,39 @@ public void registerNewUser(MultiValueMap<String, String> 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);
Expand All @@ -98,9 +102,9 @@ public void updateUser(String token, MultiValueMap<String, String> 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);
Expand All @@ -114,39 +118,39 @@ public AuthenticationResponse authenticateUser(MultiValueMap<String, String> 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();
}
Expand All @@ -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);
}
Expand Down
Loading