Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authz -> authz
.requestMatchers(org.springframework.http.HttpMethod.POST, "/api/login/users").permitAll()
.requestMatchers("/api/login/auth").permitAll()
.requestMatchers("/api/login/register").permitAll()
.requestMatchers("/actuator/**").permitAll()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.microservices.login.controller;

import com.microservices.login.dto.ApiResponse;
import com.microservices.login.dto.RegisterRequest;
import com.microservices.login.dto.UpdateUserRequest;
import com.microservices.login.dto.UserResponse;
import com.microservices.login.exception.EmailAlreadyExistsException;
import com.microservices.login.model.User;
import com.microservices.login.service.UserService;
import com.microservices.login.security.JwtAuthenticationToken;
Expand Down Expand Up @@ -45,7 +47,23 @@ public ResponseEntity<?> getUserProfile(Authentication authentication) {
.body(new ApiResponse(false, "Error retrieving user profile"));
}
}
@PostMapping("/users")
public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest)
{
try {
User user = userService.createUser(registerRequest);
UserResponse userResponse = new UserResponse(user);
logger.info("New user registered: {}", user.getUsername());
return ResponseEntity.status(201).body(userResponse);
}
catch (EmailAlreadyExistsException e) {
logger.warn("Registration failed, email already exists: {}",
registerRequest.getEmail());

return ResponseEntity.status(409)
.body(new ApiResponse(false, e.getMessage()));
}
}
@PutMapping("/users/profile")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> updateUserProfile(@Valid @RequestBody UpdateUserRequest updateRequest,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.microservices.login.exception;

public class EmailAlreadyExistsException extends RuntimeException{
public EmailAlreadyExistsException(String message)
{
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.microservices.login.exception;

import com.microservices.login.dto.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(EmailAlreadyExistsException.class)
public ResponseEntity<?> handleEmailExists(EmailAlreadyExistsException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(new ApiResponse(false, ex.getMessage()));
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.microservices.login.service;

import com.microservices.login.dto.RegisterRequest;
import com.microservices.login.dto.UpdateUserRequest;
import com.microservices.login.exception.EmailAlreadyExistsException;
import com.microservices.login.model.User;
import com.microservices.login.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -20,7 +23,8 @@ public class UserService {

@Autowired
private UserRepository userRepository;

@Autowired
private PasswordEncoder passwordEncoder;
public User findByUsername(String username) {
return userRepository.findByUsername(username)
.orElseThrow(() -> new RuntimeException("User not found with username: " + username));
Expand All @@ -35,6 +39,22 @@ public List<User> findAllActiveUsers() {
return userRepository.findAllActiveUsers();
}


public User createUser(RegisterRequest registerRequest) {
if(userRepository.existsByEmail(registerRequest.getEmail())) {
logger.warn("Attempt to register with existing email: {}", registerRequest.getEmail());
throw new EmailAlreadyExistsException("A User is already registered with current mail");
}
User user=new User();
user.setUsername(registerRequest.getUsername());
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
user.setFirstName(registerRequest.getFirstName());
user.setLastName(registerRequest.getLastName());
user.setEmail(registerRequest.getEmail());
user.setIsActive(true);
logger.info("New user registered: {}", user.getUsername());
return userRepository.save(user);
}
public User updateUserProfile(String username, UpdateUserRequest updateRequest) {
User user = findByUsername(username);

Expand Down Expand Up @@ -74,22 +94,22 @@ public void deactivateUser(Long userId, String currentUsername) {
logger.info("User {} deactivated by user {}", userId, currentUsername);
}

public User createUser(User user) {
// Check if username already exists
if (userRepository.existsByUsername(user.getUsername())) {
throw new RuntimeException("Username is already taken");
}

// Check if email already exists
if (userRepository.existsByEmail(user.getEmail())) {
throw new RuntimeException("Email is already taken");
}

User savedUser = userRepository.save(user);
logger.info("New user created: {}", savedUser.getUsername());

return savedUser;
}
// public User createUser(User user) {
// // Check if username already exists
// if (userRepository.existsByUsername(user.getUsername())) {
// throw new RuntimeException("Username is already taken");
// }
//
// // Check if email already exists
// if (userRepository.existsByEmail(user.getEmail())) {
// throw new RuntimeException("Email is already taken");
// }
//
// User savedUser = userRepository.save(user);
// logger.info("New user created: {}", savedUser.getUsername());
//
// return savedUser;
// }

public boolean existsByUsername(String username) {
return userRepository.existsByUsername(username);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,4 @@

@SpringBootTest(classes = LoginServiceApplication.class)
class EmpdirApplicationTests {



}
Loading