Merge branch 'Be/user' into 'backend'

[Back-End] refactor : user 서비스 리펙토링

See merge request s11-webmobile1-sub2/S11P12A701!37
This commit is contained in:
박정민 2024-08-05 10:23:53 +09:00
commit a140ce8192
34 changed files with 171 additions and 176 deletions

View File

@ -129,7 +129,7 @@ public class BoardController {
@ExceptionHandler() @ExceptionHandler()
public ResponseEntity<?> NoContentException(Exception exception){ public ResponseEntity<?> NoContentException(Exception e){
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
} }

View File

@ -4,7 +4,7 @@ package com.edufocus.edufocus.board.entity.vo;
import com.edufocus.edufocus.board.entity.dto.ResponseBoardDetailDto; import com.edufocus.edufocus.board.entity.dto.ResponseBoardDetailDto;
import com.edufocus.edufocus.board.entity.dto.ResponseBoardSummaryDto; import com.edufocus.edufocus.board.entity.dto.ResponseBoardSummaryDto;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
@ -13,7 +13,6 @@ import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List; import java.util.List;
@Entity @Entity

View File

@ -2,7 +2,7 @@ package com.edufocus.edufocus.board.entity.vo;
import com.edufocus.edufocus.board.entity.dto.ResponseCommentDto; import com.edufocus.edufocus.board.entity.dto.ResponseCommentDto;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;

View File

@ -8,7 +8,7 @@ import com.edufocus.edufocus.board.repository.BoardRepository;
import com.edufocus.edufocus.board.repository.CommentRepository; import com.edufocus.edufocus.board.repository.CommentRepository;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.repository.LectureRepository; import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
@ -72,7 +72,7 @@ public class BoardServiceImpl implements BoardService {
@Transactional @Transactional
public void updateBoard(long boardId, RequestBoardUpdateDto requestBoardUpdateDto) { public void updateBoard(long boardId, RequestBoardUpdateDto requestBoardUpdateDto) {
Board board = boardRepository.findById(boardId).orElseThrow(IllegalArgumentException::new); Board board = boardRepository.getReferenceById(boardId);
board.setTitle(requestBoardUpdateDto.getTitle()); board.setTitle(requestBoardUpdateDto.getTitle());
board.setContent(requestBoardUpdateDto.getContent()); board.setContent(requestBoardUpdateDto.getContent());
@ -113,7 +113,7 @@ public class BoardServiceImpl implements BoardService {
@Transactional @Transactional
public void updateComment(long commentId, RequestCommentDto requestCommentDto) { public void updateComment(long commentId, RequestCommentDto requestCommentDto) {
Comment comment = commentRepository.findById(commentId).orElseThrow(IllegalArgumentException::new); Comment comment = commentRepository.getReferenceById(commentId);
comment.setContent(requestCommentDto.getContent()); comment.setContent(requestCommentDto.getContent());

View File

@ -1,7 +1,7 @@
package com.edufocus.edufocus.lecture.entity; package com.edufocus.edufocus.lecture.entity;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;

View File

@ -6,8 +6,8 @@ import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.registration.entity.Registration; import com.edufocus.edufocus.registration.entity.Registration;
import com.edufocus.edufocus.registration.entity.RegistrationStatus; import com.edufocus.edufocus.registration.entity.RegistrationStatus;
import com.edufocus.edufocus.registration.repository.RegistrationRepository; import com.edufocus.edufocus.registration.repository.RegistrationRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.entity.UserRole; import com.edufocus.edufocus.user.model.entity.vo.UserRole;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View File

@ -1,10 +1,9 @@
package com.edufocus.edufocus.qna.entity; package com.edufocus.edufocus.qna.entity;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
import org.checkerframework.checker.units.qual.C;
import java.util.Date; import java.util.Date;

View File

@ -6,19 +6,16 @@ import com.edufocus.edufocus.qna.entity.Qna;
import com.edufocus.edufocus.qna.entity.QnaRequestDto; import com.edufocus.edufocus.qna.entity.QnaRequestDto;
import com.edufocus.edufocus.qna.entity.QnaResponseDto; import com.edufocus.edufocus.qna.entity.QnaResponseDto;
import com.edufocus.edufocus.qna.repository.QnaRepository; import com.edufocus.edufocus.qna.repository.QnaRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;

View File

@ -1,12 +1,11 @@
package com.edufocus.edufocus.quiz.entity; package com.edufocus.edufocus.quiz.entity;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Entity @Entity

View File

@ -2,7 +2,7 @@ package com.edufocus.edufocus.quiz.service;
import com.edufocus.edufocus.quiz.entity.*; import com.edufocus.edufocus.quiz.entity.*;
import com.edufocus.edufocus.quiz.repository.QuizSetRepository; import com.edufocus.edufocus.quiz.repository.QuizSetRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View File

@ -1,7 +1,7 @@
package com.edufocus.edufocus.registration.entity; package com.edufocus.edufocus.registration.entity;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;

View File

@ -1,13 +1,12 @@
package com.edufocus.edufocus.registration.service; package com.edufocus.edufocus.registration.service;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.repository.LectureRepository; import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.registration.entity.Registration; import com.edufocus.edufocus.registration.entity.Registration;
import com.edufocus.edufocus.registration.entity.RegistrationSearchResponse; import com.edufocus.edufocus.registration.entity.RegistrationSearchResponse;
import com.edufocus.edufocus.registration.entity.RegistrationStatus; import com.edufocus.edufocus.registration.entity.RegistrationStatus;
import com.edufocus.edufocus.registration.repository.RegistrationRepository; import com.edufocus.edufocus.registration.repository.RegistrationRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.entity.UserRole; import com.edufocus.edufocus.user.model.entity.vo.UserRole;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View File

@ -1,7 +1,7 @@
package com.edufocus.edufocus.report.entity.vo; package com.edufocus.edufocus.report.entity.vo;
import com.edufocus.edufocus.quiz.entity.QuizSet; import com.edufocus.edufocus.quiz.entity.QuizSet;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;

View File

@ -11,7 +11,7 @@ import com.edufocus.edufocus.report.entity.dto.AnswerInput;
import com.edufocus.edufocus.report.entity.vo.Report; import com.edufocus.edufocus.report.entity.vo.Report;
import com.edufocus.edufocus.report.entity.dto.ReportRequset; import com.edufocus.edufocus.report.entity.dto.ReportRequset;
import com.edufocus.edufocus.report.repository.ReportRepository; import com.edufocus.edufocus.report.repository.ReportRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View File

@ -1,12 +1,10 @@
package com.edufocus.edufocus.user.controller; package com.edufocus.edufocus.user.controller;
import com.edufocus.edufocus.user.model.entity.InfoDto; import com.edufocus.edufocus.user.model.entity.dto.InfoDto;
import com.edufocus.edufocus.user.model.entity.PasswordDto; import com.edufocus.edufocus.user.model.entity.dto.PasswordDto;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.dto.RequestJoinDto;
import com.edufocus.edufocus.user.model.exception.ExpriedTokenException; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.exception.InvalidTokenException; import com.edufocus.edufocus.user.model.exception.InvalidTokenException;
import com.edufocus.edufocus.user.model.exception.RefreshTokenExpiredException;
import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.model.service.UserService;
import com.edufocus.edufocus.user.util.JWTUtil; import com.edufocus.edufocus.user.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@ -16,7 +14,6 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -35,34 +32,30 @@ public class UserController {
private final JWTUtil jwtUtil; private final JWTUtil jwtUtil;
@PostMapping("/join") @PostMapping("/join")
public ResponseEntity<String> join(@RequestBody User user) throws Exception { public ResponseEntity<String> join(@RequestBody RequestJoinDto requestJoinDto){
userService.join(user);
if(userService.isUserIdExist(requestJoinDto.getUserId()))
return new ResponseEntity<>("아이디가 중복 됐습니다.", HttpStatus.CONFLICT);
userService.join(requestJoinDto);
return ResponseEntity.ok("User registered successfully"); return ResponseEntity.ok("User registered successfully");
} }
// @PostMapping("/findpassword/{user_id}")
// public ResponseEntity<String> findpassword(@PathVariable("user_id") Long user_id) throws Exception {
// userService.userCheck(user_id);
// return ResponseEntity.ok("임시 비밀번호가 이메일로 전송되었습니다.");
// }
@PutMapping("/updateinfo") @PutMapping("/updateinfo")
public ResponseEntity<String> updateUserInfo( public ResponseEntity<String> updateUserInfo(@RequestBody InfoDto infoDto, HttpServletRequest request) {
@RequestBody InfoDto infoDto, HttpServletRequest request) {
try {
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
Long userId = Long.parseLong(jwtUtil.getUserId(token)); Long userId = Long.parseLong(jwtUtil.getUserId(token));
userService.changeUserInfo(infoDto, userId); userService.changeUserInfo(infoDto, userId);
return ResponseEntity.ok("User info updated successfully");
} catch (Exception e) { return new ResponseEntity<>(HttpStatus.OK);
return ResponseEntity.badRequest().body(e.getMessage());
}
} }
// 비밀번호 변경 // 비밀번호 변경
@PutMapping("/updatepassword") @PutMapping("/updatepassword")
public ResponseEntity<String> updatePassword(@RequestBody PasswordDto passwordDto, HttpServletRequest request) { public ResponseEntity<String> updatePassword(@RequestBody PasswordDto passwordDto, HttpServletRequest request) {
try try {
{
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
Long userId = Long.parseLong(jwtUtil.getUserId(token)); Long userId = Long.parseLong(jwtUtil.getUserId(token));
@ -72,20 +65,18 @@ public class UserController {
return ResponseEntity.badRequest().body(e.getMessage()); return ResponseEntity.badRequest().body(e.getMessage());
} }
} }
@Operation(summary = "로그인", description = "아이디와 비밀번호를 이용하여 로그인 처리.") @Operation(summary = "로그인", description = "아이디와 비밀번호를 이용하여 로그인 처리.")
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<Map<String, Object>> login( public ResponseEntity<Map<String, Object>> login(
@RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user, HttpServletRequest request, HttpServletResponse response) { @RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user, HttpServletRequest request, HttpServletResponse response) {
String token = request.getHeader("Authorization");
Map<String, Object> resultMap = new HashMap<>(); Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED; HttpStatus status = HttpStatus.ACCEPTED;
try {
User loginUser = userService.login(user); User loginUser = userService.login(user);
if (loginUser != null) { if (loginUser == null)
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
String accessToken = jwtUtil.createAccessToken(String.valueOf(loginUser.getId())); String accessToken = jwtUtil.createAccessToken(String.valueOf(loginUser.getId()));
String refreshToken = jwtUtil.createRefreshToken(String.valueOf(loginUser.getId())); String refreshToken = jwtUtil.createRefreshToken(String.valueOf(loginUser.getId()));
@ -96,55 +87,28 @@ public class UserController {
resultMap.put("role",loginUser.getRole()); resultMap.put("role",loginUser.getRole());
resultMap.put("access-token", accessToken); resultMap.put("access-token", accessToken);
Cookie refreshCookie = new Cookie("refresh-token", refreshToken); setCookies(response, refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true); // HTTPS에서만 전송되도록 설정
//refreshCookie.setSameSite(Cookie.SameSite.NONE); // Cross-Origin 요청에 대해 모두 전송
//refreshCookie.setSameSite("None"); // Cross-Origin 요청에 대해 모두 전송
String cookieHeader = String.format("refresh-token=%s; Path=/; HttpOnly; Secure; SameSite=None", refreshToken);
response.setHeader("Set-Cookie", cookieHeader);
// refreshCookie.setSameSite("None"); // Cross-Origin 요청에 대해 모두 전송
response.addCookie(refreshCookie);
status = HttpStatus.CREATED; status = HttpStatus.CREATED;
} else {
resultMap.put("message", "아이디 또는 패스워드를 확인해 주세요.");
status = HttpStatus.UNAUTHORIZED;
}
} catch (Exception e) {
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
return new ResponseEntity<>(resultMap, status); return new ResponseEntity<>(resultMap, status);
} }
@PostMapping("/logout") @PostMapping("/logout")
public ResponseEntity<?> removeToken(HttpServletRequest request) { public ResponseEntity<?> removeToken(HttpServletRequest request) {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
try {
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
Long userId = Long.parseLong(jwtUtil.getUserId(token)); Long userId = Long.parseLong(jwtUtil.getUserId(token));
userService.deleteRefreshToken(userId); userService.deleteRefreshToken(userId);
status = HttpStatus.OK;
} catch (Exception e) { return new ResponseEntity<Map<String, Object>>(HttpStatus.ACCEPTED);
log.error("로그아웃 실패 : {}", e);
resultMap.put("message", e.getMessage());
status = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
} }
@Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.") @Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.")
@PostMapping("/refresh") @PostMapping("/refresh")
public ResponseEntity<?> refreshToken(HttpServletRequest request,HttpServletResponse response) public ResponseEntity<?> refreshToken(HttpServletRequest request,HttpServletResponse response) {
throws Exception {
Cookie[] cookies = request.getCookies(); Cookie[] cookies = request.getCookies();
String token = null; String token = null;
if (cookies != null) { if (cookies != null) {
@ -178,11 +142,7 @@ public class UserController {
userService.saveRefreshToken(userId,refreshToken); userService.saveRefreshToken(userId,refreshToken);
Cookie refreshCookie = new Cookie("refresh-token", refreshToken); setCookies(response, refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true);
response.addCookie(refreshCookie);
return new ResponseEntity<Map<String, Object>>(resultMap, HttpStatus.CREATED); return new ResponseEntity<Map<String, Object>>(resultMap, HttpStatus.CREATED);
} }
@ -215,7 +175,13 @@ public class UserController {
} }
private void setCookies(HttpServletResponse response, String refreshToken){
Cookie refreshCookie = new Cookie("refresh-token", refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true);
response.addCookie(refreshCookie);
}
} }

View File

@ -26,9 +26,7 @@ public class JWTInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
final String token = request.getHeader(HEADER_AUTH); final String token = request.getHeader(HEADER_AUTH);
jwtUtil.checkToken(token); jwtUtil.checkToken(token);
return true; return true;
} }
} }

View File

@ -1,5 +0,0 @@
package com.edufocus.edufocus.user.model.entity;
public enum UserRole {
STUDENT,ADMIN
}

View File

@ -1,4 +1,4 @@
package com.edufocus.edufocus.user.model.entity; package com.edufocus.edufocus.user.model.entity.dto;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;

View File

@ -1,4 +1,4 @@
package com.edufocus.edufocus.user.model.entity; package com.edufocus.edufocus.user.model.entity.dto;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,13 +1,11 @@
package com.edufocus.edufocus.user.model.entity; package com.edufocus.edufocus.user.model.entity.dto;
import lombok.Generated;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@Setter @Setter
@Getter @Getter
public class PasswordDto { public class PasswordDto {
String currentPassword; String currentPassword;
String newPassword; String newPassword;
String newPasswordCheck; String newPasswordCheck;

View File

@ -0,0 +1,11 @@
package com.edufocus.edufocus.user.model.entity.dto;
import lombok.AllArgsConstructor;
import lombok.Setter;
@Setter
@AllArgsConstructor
public class RefreshTokenDto {
private String Token;
}

View File

@ -0,0 +1,17 @@
package com.edufocus.edufocus.user.model.entity.dto;
import com.edufocus.edufocus.user.model.entity.vo.UserRole;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
public class RequestJoinDto {
private String userId;
private String email;
private String password;
private UserRole role;
private String name;
}

View File

@ -1,21 +1,14 @@
package com.edufocus.edufocus.user.model.entity; package com.edufocus.edufocus.user.model.entity.vo;
import com.edufocus.edufocus.qna.entity.Qna;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor; import lombok.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.checkerframework.checker.units.qual.A;
import java.util.ArrayList;
import java.util.List;
@Entity @Entity
@Getter @Getter
@Setter @Setter
@Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class User { public class User {

View File

@ -0,0 +1,5 @@
package com.edufocus.edufocus.user.model.entity.vo;
public enum UserRole {
STUDENT,ADMIN
}

View File

@ -19,4 +19,8 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
} }
@ExceptionHandler(UserException.class)
public ResponseEntity<String> handleUserException(UserException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);//수정해야함
}
} }

View File

@ -1,6 +1,6 @@
package com.edufocus.edufocus.user.model.repository; package com.edufocus.edufocus.user.model.repository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;

View File

@ -1,18 +1,28 @@
package com.edufocus.edufocus.user.model.service; package com.edufocus.edufocus.user.model.service;
import com.edufocus.edufocus.user.model.entity.InfoDto; import com.edufocus.edufocus.user.model.entity.dto.InfoDto;
import com.edufocus.edufocus.user.model.entity.PasswordDto; import com.edufocus.edufocus.user.model.entity.dto.PasswordDto;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.dto.RequestJoinDto;
import com.edufocus.edufocus.user.model.entity.vo.User;
public interface UserService { public interface UserService {
void join(User user) throws Exception; void join(RequestJoinDto requestJoinDto);
User login(User user) throws Exception;
void saveRefreshToken(Long id, String refreshToken) throws Exception;
String getRefreshToken(Long id) throws Exception;
void deleteRefreshToken(Long id) throws Exception;
User userInfo(Long id) throws Exception;
String getUserName(Long id) throws Exception;
void changeUserInfo(InfoDto infoDto,Long id) throws Exception;
void changePassword(PasswordDto passwordDto,Long id) throws Exception;
User login(User user);
void saveRefreshToken(Long id, String refreshToken);
String getRefreshToken(Long id);
void deleteRefreshToken(Long id);
User userInfo(Long id);
String getUserName(Long id);
void changeUserInfo(InfoDto infoDto,Long id);
void changePassword(PasswordDto passwordDto,Long id);
boolean isUserIdExist(String userId);
} }

View File

@ -1,19 +1,17 @@
package com.edufocus.edufocus.user.model.service; package com.edufocus.edufocus.user.model.service;
import com.edufocus.edufocus.user.model.entity.*; import com.edufocus.edufocus.user.model.entity.dto.InfoDto;
import com.edufocus.edufocus.user.model.entity.dto.PasswordDto;
import com.edufocus.edufocus.user.util.PasswordUtils;
import com.edufocus.edufocus.user.model.entity.dto.RequestJoinDto;
import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.exception.UserException; import com.edufocus.edufocus.user.model.exception.UserException;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
@Service @Service
@ -25,16 +23,20 @@ public class UserServiceImpl implements UserService {
private final UserRepository userRepository; private final UserRepository userRepository;
public void join(User user) public void join(RequestJoinDto requestJoinDto)
{ {
System.out.println(user.getRole().getClass()); User user = User.builder()
user.setPassword(PasswordUtils.hashPassword(user.getPassword())); .userId(requestJoinDto.getUserId())
.email(requestJoinDto.getEmail())
.password(PasswordUtils.hashPassword(requestJoinDto.getPassword()))
.role(requestJoinDto.getRole())
.name(requestJoinDto.getName())
.build();
userRepository.save(user); userRepository.save(user);
} }
public User login(User user) throws SQLException { public User login(User user){
Optional<User> findUser = userRepository.findByUserId(user.getUserId()); Optional<User> findUser = userRepository.findByUserId(user.getUserId());
if (findUser.isEmpty()) { if (findUser.isEmpty()) {
@ -65,14 +67,13 @@ public class UserServiceImpl implements UserService {
@Override @Override
public String getUserName(Long id) throws Exception { public String getUserName(Long id){
return userRepository.findById(id).get().getName(); return userRepository.findById(id).get().getName();
} }
@Override @Override
public void changeUserInfo(InfoDto infoDto, Long id) throws Exception { public void changeUserInfo(InfoDto infoDto, Long id){
User user = userRepository.findById(id).orElseThrow(IllegalArgumentException::new); User user = userRepository.findById(id).orElseThrow(IllegalArgumentException::new);
@ -87,18 +88,18 @@ public class UserServiceImpl implements UserService {
@Override @Override
public void changePassword(PasswordDto passwordDto, Long id) throws Exception { public void changePassword(PasswordDto passwordDto, Long id){
User user = userRepository.findById(id).orElse(null); User user = userRepository.findById(id).orElse(null);
if (user == null) { if (user == null) {
throw new Exception("User not found"); throw new UserException("User not found");
} }
if (!PasswordUtils.checkPassword(passwordDto.getCurrentPassword(), user.getPassword())) { if (!PasswordUtils.checkPassword(passwordDto.getCurrentPassword(), user.getPassword())) {
throw new Exception("Current password is incorrect"); throw new UserException("Current password is incorrect");
} else { } else {
if (!passwordDto.getNewPassword().equals(passwordDto.getNewPasswordCheck())) { if (!passwordDto.getNewPassword().equals(passwordDto.getNewPasswordCheck())) {
throw new Exception("New password confirmation does not match"); throw new UserException("New password confirmation does not match");
} }
} }
@ -106,6 +107,12 @@ public class UserServiceImpl implements UserService {
user.setPassword(PasswordUtils.hashPassword(passwordDto.getNewPassword())); user.setPassword(PasswordUtils.hashPassword(passwordDto.getNewPassword()));
userRepository.save(user); userRepository.save(user);
} }
@Override
public boolean isUserIdExist(String userId) {
return userRepository.findByUserId(userId).isPresent();
}
public String getTempPassword() { public String getTempPassword() {
char[] charSet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', char[] charSet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
@ -119,17 +126,17 @@ public class UserServiceImpl implements UserService {
return str; return str;
} }
@Override @Override
public void saveRefreshToken(Long id, String refreshToken) throws Exception { public void saveRefreshToken(Long id, String refreshToken){
userRepository.saveRefreshToken(id, refreshToken); userRepository.saveRefreshToken(id, refreshToken);
} }
@Override @Override
public String getRefreshToken(Long id) throws Exception { public String getRefreshToken(Long id){
return userRepository.getRefreshToken(id); return userRepository.getRefreshToken(id);
} }
@Override @Override
public void deleteRefreshToken(Long id) throws Exception { public void deleteRefreshToken(Long id){
userRepository.deleteRefreshToken(id); userRepository.deleteRefreshToken(id);
} }

View File

@ -79,7 +79,7 @@ public class JWTUtil {
Map<String, Object> value = claims.getBody(); Map<String, Object> value = claims.getBody();
log.info("value : {}", value); log.info("value : {}", value);
return (String) value.get("id"); return (String) value.get("id");
}catch ( ExpiredJwtException e) }catch (ExpiredJwtException e)
{ {
System.out.println("expired token"); System.out.println("expired token");
throw new ExpriedTokenException(); throw new ExpriedTokenException();

View File

@ -1,4 +1,4 @@
package com.edufocus.edufocus.user.model.entity; package com.edufocus.edufocus.user.util;
import org.mindrot.jbcrypt.BCrypt; import org.mindrot.jbcrypt.BCrypt;
public class PasswordUtils { public class PasswordUtils {

View File

@ -4,13 +4,11 @@ import java.util.Map;
import java.util.Random; import java.util.Random;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.entity.LectureDetailResponse;
import com.edufocus.edufocus.lecture.repository.LectureRepository; import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.lecture.service.LectureService; import com.edufocus.edufocus.lecture.service.LectureService;
import com.edufocus.edufocus.registration.entity.RegistrationStatus;
import com.edufocus.edufocus.registration.service.RegistrationService; import com.edufocus.edufocus.registration.service.RegistrationService;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.entity.UserRole; import com.edufocus.edufocus.user.model.entity.vo.UserRole;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.model.service.UserService;
import com.edufocus.edufocus.user.util.JWTUtil; import com.edufocus.edufocus.user.util.JWTUtil;

View File

@ -1,7 +1,7 @@
package com.edufocus.edufocus.ws.entity.vo; package com.edufocus.edufocus.ws.entity.vo;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.ws.entity.dto.ChatUserDto; import com.edufocus.edufocus.ws.entity.dto.ChatUserDto;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;

View File

@ -3,7 +3,7 @@ package com.edufocus.edufocus.ws.service;
import com.edufocus.edufocus.lecture.entity.Lecture; import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.repository.LectureRepository; import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.vo.User;
import com.edufocus.edufocus.user.model.repository.UserRepository; import com.edufocus.edufocus.user.model.repository.UserRepository;
import com.edufocus.edufocus.ws.entity.dto.ChatUserDto; import com.edufocus.edufocus.ws.entity.dto.ChatUserDto;
import com.edufocus.edufocus.ws.entity.vo.ChatUser; import com.edufocus.edufocus.ws.entity.vo.ChatUser;

View File

@ -1,8 +1,8 @@
//package com.edufocus.edufocus.user.model.service; //package com.edufocus.edufocus.user.model.service;
// //
//import com.edufocus.edufocus.user.model.entity.PasswordDto; //import com.edufocus.edufocus.user.model.entity.dto.PasswordDto;
//import com.edufocus.edufocus.user.model.entity.User; //import com.edufocus.edufocus.user.model.entity.vo.User;
//import com.edufocus.edufocus.user.model.entity.UserRole; //import com.edufocus.edufocus.user.model.entity.vo.UserRole;
//import com.edufocus.edufocus.user.model.exception.UserException; //import com.edufocus.edufocus.user.model.exception.UserException;
//import com.edufocus.edufocus.user.model.repository.UserRepository; //import com.edufocus.edufocus.user.model.repository.UserRepository;
//import org.junit.jupiter.api.BeforeEach; //import org.junit.jupiter.api.BeforeEach;