새소식

TIL

[TIL] 230603 <Spring> 회원가입, 로그인 기능이 있는 투두앱 백엔드 서버 만들기 (3)

  • -

 

controller>CommentController

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class CommentController {

	private final CommentService commentService;
	private final JwtUtil jwtUtil;

	// 댓글 작성
	@PostMapping("/schedule/{scheduleId}/comment")
	public ResponseEntity<Response> createComment(@PathVariable Long scheduleId, @Valid @RequestBody CommentRequestDto requestDto, HttpServletRequest req) {
		String username = getUsernameFromRequest(req);
		commentService.createComment(scheduleId, username, requestDto);

		Response response = new Response(HttpStatus.OK.value(), "댓글이 성공적으로 등록되었습니다.");
		return ResponseEntity.ok(response);
	}

	// 댓글 수정
	@PutMapping("/schedule/{scheduleId}/comment/{commentId}")
	public ResponseEntity<Response> updateComment(@PathVariable Long scheduleId, @PathVariable Long commentId, @Valid @RequestBody CommentRequestDto requestDto, HttpServletRequest req) {
		String username = getUsernameFromRequest(req);
		commentService.updateComment(scheduleId, commentId, username, requestDto);

		Response response = new Response(HttpStatus.OK.value(), "댓글이 성공적으로 수정되었습니다.");
		return ResponseEntity.ok(response);
	}

	// 댓글 삭제
	@DeleteMapping("/schedule/{scheduleId}/comment/{commentId}")
	public ResponseEntity<Response> deleteComment(@PathVariable Long scheduleId, @PathVariable Long commentId, @RequestBody CommentRequestDto requestDto, HttpServletRequest req) {
		String username = getUsernameFromRequest(req);
		commentService.deleteComment(scheduleId, commentId, username, requestDto);

		Response response = new Response(HttpStatus.OK.value(), "댓글이 성공적으로 삭제되었습니다.");
		return ResponseEntity.ok(response);
	}

	private String getUsernameFromRequest(HttpServletRequest req) {
		// Access Token과 Refresh Token을 각각의 헤더에서 가져옴
		String accessToken = jwtUtil.getAccessTokenFromHeader(req);
		String refreshToken = jwtUtil.getRefreshTokenFromHeader(req);
		String newAccessToken = jwtUtil.checkToken(accessToken, refreshToken);
		Claims claims = jwtUtil.getUserInfoFromToken(newAccessToken);
		return claims.getSubject();
	}
}

 

 


 

▼ 환경변수 설정 방법

 

Intellij 상에서 환경변수를 할당하는 방법

1. Edit Configuration (구성 편집) 2. Modify options (옵션 수정) 3. Enviornment variables (환경 변수) 4. 노트 모양 클릭 5. + 클릭     > Name에는 application.properties의 대상 Key 값(UPPER_CASE와 _언더바를 이용), Value

enjoydev.tistory.com

 

application.properties

spring.application.name=schedule
spring.datasource.url=${SPRING_DATASOURCE_URL}
spring.datasource.username=${SPRING_DATASOURCE_USERNAME}
spring.datasource.password=${SPRING_DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true

jwt.secret.key=${JWT_SECRET_KEY}
admin.token=${ADMIN_TOKEN}

 

service>UserService

왼쪽에서 오른쪽과 같이 변경

 

 


 

config>JwtConfiguration 

@Configuration
public class JwtConfiguration {

	@Value("${jwt.secret.key}") // application.properties에서 설정한 비밀키 값
	private String secretKey;

	@Bean
	public Key jwtKey() {
		byte[] bytes = Base64.getDecoder().decode(secretKey);
		return Keys.hmacShaKeyFor(bytes);
	}
}

 

jwt>JwtUtil

왼쪽에서 오른쪽과 같이 변경

 

 


 

service>CommentService

기존에는 이중참조를 통해 댓글 작성자의 이름을 가져왔는데 코드를 변경하여 getUser에 데이터가 있는지 먼저 확인한 다음에 사용자 이름을 가져올 수 있게 하였음

 

 


 

service>UserService

	public ResponseEntity<Response> signup(SignupRequestDto requestDto) {
		String username = requestDto.getUsername();
		String nickname = requestDto.getNickname();
		String password = requestDto.getPassword();

		// 사용자 ROLE 확인
		UserRoleEnum role = UserRoleEnum.USER;
		if (requestDto.isAdmin()) {
			if (!ADMIN_TOKEN.equals(requestDto.getAdminToken())) {
				throw new InvalidPasswordException("관리자 암호가 틀려 등록이 불가능합니다.");
			}
			role = UserRoleEnum.ADMIN;
		}

		// 사용자 등록
		User user = new User(username, nickname, password, role);
		try {
			userRepository.save(user);
		} catch (DataIntegrityViolationException e) {
			if (e.getMessage().contains("constraint [uk_username]")) {
				// 사용자 이름이 중복될 경우
				throw new IllegalArgumentException("중복된 사용자가 존재합니다.");
			} else if (e.getMessage().contains("constraint [uk_nickname]")) {
				// 별명이 중복될 경우
				throw new IllegalArgumentException("중복된 별명입니다.");
			} else {
				// 기타 데이터베이스 제약 조건 위반
				throw e;
			}
		}

		Response response = new Response(HttpStatus.OK.value(), "회원가입이 성공적으로 완료되었습니다.");
		return ResponseEntity.ok(response);  // 성공 메시지와 상태 코드 반환
	}
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.