Backend Low Level Design 4
About Lesson
For the sign-in flow, start by creating a signIn method in the Controller. Annotate it with @PostMapping(“/login”). Its return type should be Token, and it should accept @RequestBody LoginRequestDto loginRequestDto. Call login method from UserService and password email and password to it.

UserController

@PostMapping(“/login”)
public Token signUp(@RequestBody LoginRequestDto loginRequestDto){
   String email = loginRequestDto.getEmail();
   String password = loginRequestDto.getPassword();
  return userService.login(email, password);
}

Next Create a ”LoginRequestDto” class in “dtos” package

@Setter
@Getter
public class LoginRequestDto {
   private String email;
   private String password;
}
Next, create a login method in the UserService class. In this method, we’ll first check if the user is not present or if the password doesn’t match, then throw an error but to get user from repository we have to write new custom method findByEmail() because it is not defalt method of repository which we will create below. If the user exists and the password matches, we’ll proceed to create a token. We’ll set the user’s expiry date by creating a new method called get30DaysLaterDate, using Calendar instance, and set the token value using UUID. Finally, we’ll save the token to the repository. For this, we’ll create a new repository in the next step.
public Token login(String email, String password) {
    Optional<User> optionalUser = userRepository.findByEmail(email);
    if(optionalUser.isEmpty()){
        // throw user is not valid
        return null;
    }
 
    User user = optionalUser.get();
    if (!bCryptPasswordEncoder.matches(password, user.getHashedPassword())) {
        // throw password is wrong
        return null;
    }
 
    Token token = new Token();
    token.setUser(user);
    token.setExpirydate(get30DaysLaterDate());
    token.setValue(UUID.randomUUID().toString());
    return tokenRepository.save(token);
 }
 
 private Date  get30DaysLaterDate() {
    LocalDate currentDate = LocalDate.now().plusDays(30);
     return Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
 }
 

Next create findByEmail method in UserRepository @Repository

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
   Optional<User> findByEmail(String email);
}

Next create tokenRepository in the repositories package

@Repository
public interface TokenRepository extends JpaRepository<Token, Long> {
 
}

Next now open postman

Now, open Postman and select the method as POST. Use the URL http://localhost:8080/login.
In the body section, select “raw” and then “JSON“.
Provide some data in the body like:

{
email“:”[email protected]“,
password“:”password123
}

Click on “Send“. If this works, it will return a “Token” as response.