Skip to content

Commit

Permalink
fix: authentication exception resolved
Browse files Browse the repository at this point in the history
  • Loading branch information
bencodes07 committed Sep 6, 2024
1 parent de4abe1 commit e588a2f
Showing 1 changed file with 54 additions and 49 deletions.
103 changes: 54 additions & 49 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,31 +57,36 @@ public void registerNewUser(MultiValueMap<String, String> data) throws NameAlrea
String name = data.getFirst("name");
String password = data.getFirst("password");
String role = data.getFirst("role");
long associatedCompany = Long.parseLong(data.getFirst("associatedCompany"));
UserRole userRole;

if (role == null
|| role.isEmpty())
userRole = UserRole.CLIENT;
else
userRole = UserRole.valueOf(role);

if (email == null
|| email.isEmpty()
|| password == null
|| password.isEmpty()
|| name == null
|| name.isEmpty()) throw new IllegalArgumentException("Required argument is missing");

if (userRepository.findUserByEmail(email).isPresent())
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);
}
}
UserRole userRole = (role == null || role.isEmpty()) ? UserRole.CLIENT : UserRole.valueOf(role);

if (email == null || email.isEmpty() || password == null || password.isEmpty() || name == null || name.isEmpty()) {
throw new IllegalArgumentException("Required argument is missing");
}

if (userRepository.findUserByEmail(email).isPresent()) {
throw new NameAlreadyBoundException("Email already taken");
}

User user = new User(name, email, passwordEncoder.encode(password), userRole);

switch (userRole) {
case COMPANY_OWNER, COMPANY_MEMBER -> user.setAssociatedCompany(associatedCompany);
case CLIENT -> user.setAssociatedCompany(-1);
default -> throw new IllegalStateException(role + "is invalid!");
case COMPANY_OWNER, COMPANY_MEMBER -> {
if (associatedCompany == null) {
throw new IllegalArgumentException("associatedCompany is required for COMPANY_OWNER and COMPANY_MEMBER roles");
}
user.setAssociatedCompany(associatedCompany);
}
case CLIENT -> user.setAssociatedCompany(-1L);
default -> throw new IllegalStateException(role + " is invalid!");
}

userRepository.save(user);
Expand All @@ -94,9 +99,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 @@ -110,39 +115,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 @@ -151,9 +156,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

0 comments on commit e588a2f

Please sign in to comment.