Login 기능 구현

Controller/AuthController

@PostMapping("/login")
public ResponseDto<LoginResponseDto> login(@RequestBody LoginDto requestBody) {
	return null;
}

AuthController에 login 메서드를 추가해준다

LoginDto와 LoginResponseDto를 구현해보자

Dto/LoginDto

package com.hyeonjoonpark.board_crud.Dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginDto {
    private String userEmail;
    private String userPassword;
}

Dto/LoginResponseDto

package com.hyeonjoonpark.board_crud.Dto;

import com.hyeonjoonpark.board_crud.Entity.UserEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginResponseDto {
    private String token;
    private int exprTime;
    private UserEntity user;
}

Service/AuthService

public ResponseDto<LoginResponseDto> login(LoginDto dto) {
        
}

Service를 구현하기 전에 LoginDto는 필수로 아이디와 비밀번호를 받아야 하기 때문에

build.gradle에 들어가서 dependencies를 추가하겠다

implementation 'org.springframework.boot:spring-boot-starter-validation'

를 추가해준다

validation을 추가했다면

package com.hyeonjoonpark.board_crud.Dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginDto {
    @NotBlank
    private String userEmail;
    @NotBlank
    private String userPassword;
}

LoginDto의 userEmail, userPassword 값을 @NotBlank로 지정해서 필수 값으로 지정해준다


package com.hyeonjoonpark.board_crud.Repository;

import com.hyeonjoonpark.board_crud.Entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<UserEntity, String> {
    public boolean existsByUserEmailAndUserPassword(String userEmail, String userPassword);
}

UserRepository에 id와 password로 값을 찾는 메소드를 구현해보자

public ResponseDto<LoginResponseDto> login(LoginDto dto) {
	String userEmail = dto.getUserEmail();
	String userPassword = dto.getUserPassword();
	boolean existed =  userRepository.existsByUserEmailAndUserPassword(userEmail, userPassword);
}

존재한다면 true, 존재하지 않으면 false를 반환 할 것이다

public ResponseDto<LoginResponseDto> login(LoginDto dto) {
	String userEmail = dto.getUserEmail();
	String userPassword = dto.getUserPassword();
    boolean existed = userRepository.existsByUserEmailAndUserPassword(userEmail, userPassword);

	if(!existed) {
    	return ResponseDto.setFailed("Login Info is Wrong");
    }
        
    // 값이 존재하면
    UserEntity userEntity = userRepository.findById(userEmail).get(); // 사용자 이메일을 가져옴
        
    userEntity.setUserPassword("");
        
    String token = "";
    int exprTime = 3600000; // 한 시간
        
    LoginResponseDto loginResponseDto = new LoginResponseDto(token, exprTime, userEntity);
    return ResponseDto.setSuccess("Login Success", loginResponseDto);
}

Login에 성공하면 token, exprTime, UserEntity를 반환한다.

AuthService 전체코드

package com.hyeonjoonpark.board_crud.Service;

import com.hyeonjoonpark.board_crud.Dto.LoginResponseDto;
import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.LoginDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import com.hyeonjoonpark.board_crud.Entity.UserEntity;
import com.hyeonjoonpark.board_crud.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    @Autowired UserRepository userRepository;
    public ResponseDto<?> signUp(SignupDto dto) {
        String userEmail = dto.getUserEmail();
        String userPassword = dto.getUserPassword();
        String userPasswordCheck = dto.getUserPasswordCheck();

        // email 중복 확인
        try {
            if(userRepository.existsById(userEmail)) { // userEmail이 존재하는지 확인 -> 존재 시 true 존재하지 않으면 false 반환
                return ResponseDto.setFailed("Existed Email!");
            }
        } catch (Exception e) {
            return ResponseDto.setFailed("Database Error");
        }

        if(!userPassword.equals(userPasswordCheck)) {
            return ResponseDto.setFailed("Password is Wrong!");
        } // userPassword와 userPasswordCheck가 일치하지 않으면

        UserEntity userEntity = new UserEntity(dto); // UserEntity 생성

        try {
            // UserRepository를 이용해서 DB에 Entity 저쟝
            userRepository.save(userEntity);
        } catch (Exception e) {
            ResponseDto.setFailed("Database Error");
        }

        return ResponseDto.setSuccess("SignUp Success!", null);
    }

    public ResponseDto<LoginResponseDto> login(LoginDto dto) {
        String userEmail = dto.getUserEmail();
        String userPassword = dto.getUserPassword();
        boolean existed =  userRepository.existsByUserEmailAndUserPassword(userEmail, userPassword);

        if(!existed) {
            return ResponseDto.setFailed("Login Info is Wrong");
        }

        // 값이 존재하면
        UserEntity userEntity = userRepository.findById(userEmail).get(); // 사용자 이메일을 가져옴

        userEntity.setUserPassword("");

        String token = "";
        int exprTime = 3600000; // 한 시간

        LoginResponseDto loginResponseDto = new LoginResponseDto(token, exprTime, userEntity);
        return ResponseDto.setSuccess("Login Success", loginResponseDto);
    }
}

포스트맨으로 확인하면 정상 작동한다


다음편에 계속

profile
Backend Developer

0개의 댓글