I have already done connect MongoDB using application.properties. But I want to connect MongoDB through mongoose.
This is my current configuration
This is DB Connection url setting in application.properties;
spring.data.mongodb.uri =mongodb srv://hans123:[email protected]/?retryWrites=true&w=majority
spring.data.mongodb.database=test
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
CodePudding user response:
Model Class
@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
@Id
@Indexed
private String id;
@Indexed
private String address;
@Indexed
private String name;
@Indexed
private String email;
@Indexed
private String password;
@Indexed
private String role;
}
Repository Class
public interface userReporsitory extends MongoRepository<User,String> {
Optional<User> findByEmail(String email);
List<User> findAllByRole(String role);
}
Service Class
@AllArgsConstructor
@Service
public class userService {
private userReporsitory userReporsitory;
public User saveUser(User user){
return userReporsitory.save(user);
}
public User login(User user){
User response = userReporsitory.findByEmail(user.getEmail()).orElseThrow(()->new RuntimeException("User Not Found"));
if(!response.getPassword().equals(user.getPassword())){
throw new RuntimeException("Bad Credincials");
}
return response;
}
public List<User> findAllUsers(){
return userReporsitory.findAllByRole("user");
}
}
Controller Class
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("api/v1/user")
public class userController {
private userService userService;
@PostMapping("/create")
public ResponseEntity<User> save(@RequestBody User user){
HttpStatus status = HttpStatus.EXPECTATION_FAILED;
User response = userService.saveUser(user);
if(response != null){
status = HttpStatus.CREATED;
}
return new ResponseEntity<>(response, status);
}
@PostMapping("/login")
public ResponseEntity<User> login(@RequestBody User user){
return new ResponseEntity<>(userService.login(user),HttpStatus.ACCEPTED);
}
@GetMapping("/userList")
public ResponseEntity<List<User>> userList(){
return new ResponseEntity<>(userService.findAllUsers(),HttpStatus.ACCEPTED);
}
}
CodePudding user response:
In above answer you can encrypt the password as well (Additional Thing) AuthRequest Class:
@Data
@AllArgsConstructor
public class AuthRequestDto {
private String userName;
private String password;
}
RegisterRequest Class:
@Data
@AllArgsConstructor
public class RegisterRequestDto {
private String userName;
private String password;
private String firstName;
private String email;
private String phone;
private String address;
}
UserService Class:
@AllArgsConstructor
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final JWTUtility jwtUtility;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByUsername(username).orElseThrow(()-> new UsernameNotFoundException("user name not found"));
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userEntity.getRole());
return new User(userEntity.getUsername() , userEntity.getPassword() , new ArrayList<>(Arrays.asList(authority)));
}
public UserEntity registerUser(RegisterRequestDto request){
//check user is already in
if(userRepository.existsByUsernameIgnoreCase(request.getUserName())){
throw new FieldValidationFaild("user name already exist in the system");
}
if(userRepository.existsByEmailIgnoreCase(request.getEmail())){
throw new FieldValidationFaild("email already exist in the system");
}
UserEntity saveToBe = UserEntity.builder()
.username(request.getUserName())
.password(new BCryptPasswordEncoder().encode(request.getPassword()))
.firstName(request.getFirstName())
.email(request.getEmail())
.phone((request.getPhone()))
.address(request.getAddress())
.role(Role.BUYER)
.build();
return userRepository.save(saveToBe);
}
public AuthRespondDto loginUser(AuthRequestDto authRequestDto){
final UserDetails userDetails = loadUserByUsername(authRequestDto.getUserName());
final String token = jwtUtility.generateToken(userDetails);
return new AuthRespondDto(token , authRequestDto.getUserName() , userDetails.getAuthorities().stream().findFirst().get().getAuthority());
}
public long getAuthUserId(String username){
UserEntity userEntity = userRepository.findByUsername(username).get();
return userEntity.getId();
}
public String getUserAddressByName(String username){
UserEntity userEntity = userRepository.findByUsername(username).get();
return userEntity.getAddress();
}
public String getUserPhoneByName(String username){
UserEntity userEntity = userRepository.findByUsername(username).get();
return userEntity.getPhone();
}
public String getUserEmailByName(String username){
UserEntity userEntity = userRepository.findByUsername(username).get();
return userEntity.getEmail();
}
public UserEntity getUserById(long id){
return userRepository.findById(id).orElseThrow(()-> new NotFoundException("user not found"));
}
}
AuthController Class (Controller Class):
public class AuthController {
private final AuthenticationManager authenticationManager;
private final UserService userService;
@PostMapping("/signin")
public ResponseEntity<AuthRespondDto> login(@RequestBody AuthRequestDto authRequestDto) throws BadCredentialsException {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authRequestDto.getUserName(),
authRequestDto.getPassword()
)
);
}catch (BadCredentialsException e){
//TODO add proper exception
throw new BadCredentialsException("INVALID_USERNAME_OR_PASSWORD" , e);
}
return new ResponseEntity<>(userService.loginUser(authRequestDto) , HttpStatus.ACCEPTED);
}
@PostMapping("/signup")
public ResponseEntity<UserEntity> register(@RequestBody RegisterRequestDto request){
// basic controller level validations
if(request.getUserName().isEmpty()){
throw new FieldValidationFaild("user name is required");
}
if(request.getPassword().isEmpty()){
throw new FieldValidationFaild("password is required");
}
if(request.getFirstName().isEmpty()){
throw new FieldValidationFaild("first name is required");
}
if(request.getEmail().isEmpty()){
throw new FieldValidationFaild("email is required");
}
if(request.getPhone().isEmpty()){
throw new FieldValidationFaild("phone is required");
}
if(request.getPhone().length() != 10){
throw new FieldValidationFaild("phone number length must be 10");
}
if(request.getAddress().isEmpty()){
throw new FieldValidationFaild("address is required");
}
return new ResponseEntity<>(userService.registerUser(request) , HttpStatus.CREATED);
}
}