Merge branch 'backend' of github.com:TeamBNBN/edufocus into be/Board

This commit is contained in:
yulmam 2024-07-18 14:39:50 +09:00
commit 91a5a53a72
37 changed files with 1028 additions and 46 deletions

View File

@ -25,8 +25,12 @@ dependencies {
implementation group: 'io.livekit', name: 'livekit-server', version: '0.6.1'
implementation 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.4.0'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5'
implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5'
implementation group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '4.0.5'
}

View File

@ -1,6 +1,7 @@
package com.edufocus.edufocus.lecture.controller;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.entity.LectureRegist;
import com.edufocus.edufocus.lecture.service.LectureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -19,26 +20,29 @@ public class LectureController {
private final LectureService lectureService;
@PostMapping
public ResponseEntity<?> createLecture (@RequestBody Lecture lecture) {
lectureService.createLecture(lecture);
public ResponseEntity<?> createLecture (@RequestBody long userId, LectureRegist lectureRegist) {
System.out.println("@@@@@@@@@@@@@@@@@@>>>>>>>>>>>>>>>>>>>>>> "+userId);
lectureService.createLecture(userId, lectureRegist);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@DeleteMapping("/{lectureId}")
public ResponseEntity<?> deleteLecture (@PathVariable long lectureId) {
lectureService.deleteLecture(lectureId);
public ResponseEntity<?> deleteLecture (@RequestBody long userId, @PathVariable long lectureId) {
if (!lectureService.deleteLecture(userId, lectureId)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@GetMapping
public ResponseEntity<?> findAllLecture () {
List<Lecture> lectures = lectureService.findAllLecture();
return new ResponseEntity<>(lectures, HttpStatus.OK);
}
@GetMapping("/teacherId/{teacherId}")
public ResponseEntity<?> findByTeacherId (@PathVariable String teacherId) {
List<Lecture> lectures = lectureService.findLectureByTeacherId(teacherId);
if (lectures.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(lectures, HttpStatus.OK);
}
@ -53,4 +57,6 @@ public class LectureController {
return new ResponseEntity<>(lecture, HttpStatus.OK);
}
}

View File

@ -1,10 +1,14 @@
package com.edufocus.edufocus.lecture.entity;
import com.edufocus.edufocus.user.model.entity.User;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Getter
@ -12,11 +16,13 @@ import java.util.Date;
public class Lecture {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
@Column(name="lecture_id")
private Long id;
@Column(name = "teacher_id")
private String teacherId;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Column
private String title;
@ -35,6 +41,9 @@ public class Lecture {
@Lob
private String plan;
@Column
private boolean online;
}

View File

@ -0,0 +1,29 @@
package com.edufocus.edufocus.lecture.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Date;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LectureRegist {
private Long userId;
private String title;
private String description;
@Temporal(TemporalType.DATE)
private Date startDate;
@Temporal(TemporalType.DATE)
private Date endDate;
private String plan;
}

View File

@ -2,6 +2,7 @@ package com.edufocus.edufocus.lecture.repository;
import com.edufocus.edufocus.lecture.entity.Lecture;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@ -11,5 +12,4 @@ import java.util.List;
public interface LectureRepository extends JpaRepository<Lecture, Long> {
Lecture findByTitle(@Param("title") String title);
List<Lecture> findByTeacherId(@Param("teacherId") String teacherId);
}

View File

@ -1,8 +1,7 @@
package com.edufocus.edufocus.lecture.service;
import com.edufocus.edufocus.lecture.entity.Lecture;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import com.edufocus.edufocus.lecture.entity.LectureRegist;
import org.springframework.stereotype.Service;
import java.util.List;
@ -11,13 +10,12 @@ import java.util.List;
@Service
public interface LectureService {
void createLecture(Lecture lecture);
void createLecture(long userId, LectureRegist lectureRegist);
void deleteLecture(long lectureId);
boolean deleteLecture(long userId, long LectureId);
List<Lecture> findAllLecture();
Lecture findLectureByTitle(String title);
List<Lecture> findLectureByTeacherId(String teacherId);
List<Lecture> findAllLecture();
}

View File

@ -1,31 +1,57 @@
package com.edufocus.edufocus.lecture.service;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.lecture.entity.LectureRegist;
import com.edufocus.edufocus.lecture.repository.LectureRepository;
import com.edufocus.edufocus.user.model.entity.User;
import com.edufocus.edufocus.user.model.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
@RequiredArgsConstructor
public class LectureServiceImpl implements LectureService {
@Autowired
private final LectureRepository lectureRepository;
private final UserRepository userRepository;
@Override
public void createLecture(Lecture lecture) {
public void createLecture(long userId, LectureRegist lectureRegist) {
User user = userRepository.findById(userId).get();
Lecture lecture = new Lecture();
lecture.setUser(user);
lecture.setTitle(lectureRegist.getTitle());
lecture.setDescription(lectureRegist.getDescription());
lecture.setStartDate(lectureRegist.getStartDate());
lecture.setEndDate(lectureRegist.getEndDate());
lecture.setPlan(lectureRegist.getPlan());
lectureRepository.save(lecture);
}
@Override
public void deleteLecture(long lectureId) {
public boolean deleteLecture(long userId, long lectureId) {
Lecture lecture = lectureRepository.findById(lectureId).get();
if (lecture.getUser().getId() != userId) {
return false;
}
lectureRepository.deleteById(lectureId);
return true;
}
@Override
public List<Lecture> findAllLecture() {
return lectureRepository.findAll();
}
@Override
@ -33,13 +59,5 @@ public class LectureServiceImpl implements LectureService {
return lectureRepository.findByTitle(title);
}
@Override
public List<Lecture> findLectureByTeacherId(String teacherId) {
return lectureRepository.findByTeacherId(teacherId);
}
@Override
public List<Lecture> findAllLecture() {
return lectureRepository.findAll();
}
}

View File

@ -0,0 +1,83 @@
package com.edufocus.edufocus.qna.controller;
import com.edufocus.edufocus.qna.entity.Qna;
import com.edufocus.edufocus.qna.service.QnaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.List;
@RestController
@RequestMapping("/qna")
@Slf4j
@RequiredArgsConstructor
public class QnaController {
private final QnaService qnaService;
@PostMapping
public ResponseEntity<Qna> createQna(@RequestBody Qna qna) {
try{
qnaService.createQna(qna);
return new ResponseEntity<>(qna, HttpStatus.CREATED);
}catch (Exception e){
throw new RuntimeException(e);
}
}
@PutMapping("/{id}")
public ResponseEntity<Qna> updateQna(@PathVariable Long id, @RequestBody Qna qna) {
try{
qnaService.updateQna(id,qna);
return new ResponseEntity<>(qna, HttpStatus.ACCEPTED);
}catch (Exception e)
{
throw new RuntimeException(e); }
}
@DeleteMapping("/{id}")
public ResponseEntity<Qna> deleteQna(@PathVariable Long id) {
try {
qnaService.deleteQna(id);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@GetMapping("/{id}")
public ResponseEntity<Qna> getQna(@PathVariable Long id) {
try{
Qna findQna= qnaService.getQna(id);
return new ResponseEntity<>(findQna, HttpStatus.ACCEPTED);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@GetMapping("/all/{id}")
public ResponseEntity<List<Qna>> getAllQna(@PathVariable Long id) {
try {
System.out.print("@@@@@@@@@@@@@@@@@@@@@@@>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
List<Qna> qnaList= qnaService.getAllQnasByLecture(id);
for(Qna qna:qnaList)
{
System.out.print(qna.toString());
}
return new ResponseEntity<>(qnaList, HttpStatus.ACCEPTED);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,54 @@
package com.edufocus.edufocus.qna.entity;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.checkerframework.checker.units.qual.C;
import java.util.Date;
@Entity
@Getter
@Setter
public class Qna {
// 연관관계 주인
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "qna_id")
private Long id;
@Column
private String title;
@Column
private String content;
@Column(name = "created_at")
@Temporal(TemporalType.DATE)
private Date createdAt;
@Column(name = "modified_at")
@Temporal(TemporalType.DATE)
private Date modifiedAt;
@Column
private String answer;
@ManyToOne
@JoinColumn(name= "id")
private User user;
@ManyToOne
@JoinColumn(name= "lecture_id")
private Lecture lecture;
}

View File

@ -0,0 +1,18 @@
package com.edufocus.edufocus.qna.repository;
import com.edufocus.edufocus.qna.entity.Qna;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface QnaRepository extends JpaRepository<Qna, Long> {
@Query(value = "SELECT * FROM qna WHERE lecture_id = :lectureId", nativeQuery = true)
List<Qna> findLecture(@Param("lectureId") Long lectureId);
}

View File

@ -0,0 +1,19 @@
package com.edufocus.edufocus.qna.service;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.qna.entity.Qna;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.List;
@Service
public interface QnaService {
void createQna(Qna qna) throws SQLException;
void updateQna(Long id,Qna qna) throws SQLException;
void deleteQna(Long id) throws SQLException;
Qna getQna(Long id) throws SQLException;
List<Qna> getAllQnasByLecture(Long lectureId) throws SQLException;
}

View File

@ -0,0 +1,60 @@
package com.edufocus.edufocus.qna.service;
import com.edufocus.edufocus.qna.entity.Qna;
import com.edufocus.edufocus.qna.repository.QnaRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
@RequiredArgsConstructor
public class QnaServiceImpl implements QnaService{
private final QnaRepository qnaRepository;
@Override
public void createQna(Qna qna) {
qnaRepository.save(qna);
}
@Override
public void updateQna(Long id,Qna qna) {
Optional<Qna> findQna = qnaRepository.findById(id);
qna.setModifiedAt(new Date());
qnaRepository.save(qna);
}
@Override
public void deleteQna(Long id) {
qnaRepository.deleteById(id);
}
@Override
public Qna getQna(Long id) {
return null;
}
@Override
public List<Qna> getAllQnasByLecture(Long lectureId) {
System.out.printf(lectureId+"!!!!!!!!!!!!!!!!!!!!!!");
return qnaRepository.findLecture(lectureId);
}
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.controller;
public class QuizController {
}

View File

@ -0,0 +1,54 @@
package com.edufocus.edufocus.quiz.entity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Entity
@Getter
@Setter
public class Quiz {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "quizset_id")
private QuizSet quizSet;
@Column
private String title;
@Column
private String description;
@Column
private String answer;
@Column (name = "is_single")
private boolean isSingle;
@Column
private String image;
@Column
private String choice1;
@Column
private String choice2;
@Column
private String choice3;
@Column
private String choice4;
public void setQuizSet(QuizSet quizSet) {
this.quizSet = quizSet;
if (!quizSet.getQuizzes().contains(this)) {
quizSet.getQuizzes().remove(this);
}
}
}

View File

@ -0,0 +1,40 @@
package com.edufocus.edufocus.quiz.entity;
import com.edufocus.edufocus.user.model.entity.User;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
public class QuizSet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Column
private String title;
@Column
private String image;
@OneToMany(mappedBy = "quizSet")
private List<Quiz> quizzes = new ArrayList<Quiz>();
public void addQuiz(Quiz quiz) {
this.quizzes.add(quiz);
if (quiz.getQuizSet() != this) {
quiz.setQuizSet(this);
}
}
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.repository;
public interface QuizRepository {
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.repository;
public interface QuizSetRepository {
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.service;
public interface QuizService {
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.service;
public class QuizServiceImpl {
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.service;
public interface QuizSetService {
}

View File

@ -0,0 +1,4 @@
package com.edufocus.edufocus.quiz.service;
public class QuizSetServiceImpl {
}

View File

@ -0,0 +1,42 @@
package com.edufocus.edufocus.registration.controller;
import com.edufocus.edufocus.registration.entity.Registration;
import com.edufocus.edufocus.registration.service.RegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/registration")
@Slf4j
public class RegistrationController {
private final RegistrationService registrationServiceImpl;
public RegistrationController(RegistrationService registrationServiceImpl) {
this.registrationServiceImpl = registrationServiceImpl;
}
@PostMapping
public ResponseEntity<?> register(@RequestBody Registration registration) {
registrationServiceImpl.createRegistration(registration);
return new ResponseEntity<>(HttpStatus.OK);
}
@PatchMapping("/registrationId/{registrationId}")
public ResponseEntity<?> acceptRigistration(@PathVariable long registrationId) {
registrationServiceImpl.acceptRegistration(registrationId);
return new ResponseEntity<>(HttpStatus.OK);
}
@DeleteMapping("/registrationId/{registrationId}")
public ResponseEntity<?> deleteRigistration(@PathVariable long registrationId) {
registrationServiceImpl.deleteRegistration(registrationId);
return new ResponseEntity<>(HttpStatus.OK);
}
}

View File

@ -0,0 +1,28 @@
package com.edufocus.edufocus.registration.entity;
import com.edufocus.edufocus.lecture.entity.Lecture;
import com.edufocus.edufocus.user.model.entity.User;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Entity
@Getter
@Setter
public class Registration {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "lecture_id")
private Lecture lecture;
@Enumerated(EnumType.STRING)
private RegistrationStatus status ;
}

View File

@ -0,0 +1,5 @@
package com.edufocus.edufocus.registration.entity;
public enum RegistrationStatus {
WAITING, ACCEPTED
}

View File

@ -0,0 +1,11 @@
package com.edufocus.edufocus.registration.repository;
import com.edufocus.edufocus.registration.entity.Registration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface RegistrationRepository extends JpaRepository<Registration, Long> {
}

View File

@ -0,0 +1,17 @@
package com.edufocus.edufocus.registration.service;
import com.edufocus.edufocus.registration.entity.Registration;
import org.springframework.stereotype.Service;
@Service
public interface RegistrationService {
void createRegistration(Registration registration);
void acceptRegistration(long RegistrationId);
void deleteRegistration(long registrationId);
boolean isAcceptedRegistration(long registrationId);
}

View File

@ -0,0 +1,46 @@
package com.edufocus.edufocus.registration.service;
import com.edufocus.edufocus.registration.entity.Registration;
import com.edufocus.edufocus.registration.entity.RegistrationStatus;
import com.edufocus.edufocus.registration.repository.RegistrationRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@Transactional
@RequiredArgsConstructor
public class RegistrationServiceImpl implements RegistrationService {
private final RegistrationRepository registrationRepository;
@Override
public void createRegistration(Registration registration) {
registrationRepository.save(registration);
}
@Override
public void acceptRegistration(long registrationId) {
Optional<Registration> registration = registrationRepository.findById(registrationId);
if (registration.isPresent()) {
Registration reg = registration.get();
reg.setStatus(RegistrationStatus.valueOf("ACCEPTED"));
registrationRepository.save(reg);
}
}
@Override
public void deleteRegistration(long registrationId) {
registrationRepository.deleteById(registrationId);
}
@Override
public boolean isAcceptedRegistration(long registrationId) {
Optional<Registration> registration = registrationRepository.findById(registrationId);
return registration.isPresent() && registration.get().getStatus().equals("ACCEPTED");
}
}

View File

@ -0,0 +1,41 @@
package com.edufocus.edufocus.user.config;
import com.edufocus.edufocus.user.intercepter.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfiguration implements WebMvcConfigurer {
private JWTInterceptor jwtInterceptor;
public WebConfiguration(JWTInterceptor jwtInterceptor) {
super();
this.jwtInterceptor = jwtInterceptor;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("*")
.allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(),
HttpMethod.PATCH.name())
.maxAge(1800); // Pre-flight Caching
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("classpath:/static/assets/img/");
registry.addResourceHandler("/*.html**").addResourceLocations("classpath:/static/");
}
}

View File

@ -2,14 +2,19 @@ package com.edufocus.edufocus.user.controller;
import com.edufocus.edufocus.user.model.entity.User;
import com.edufocus.edufocus.user.model.service.UserService;
import com.edufocus.edufocus.user.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
@ -18,24 +23,163 @@ import org.springframework.web.bind.annotation.RestController;
public class UserController {
private final UserService userService;
private final JWTUtil jwtUtil;
@PostMapping("/join")
public ResponseEntity<String> join(@RequestBody User user) throws Exception {
System.out.println("!!!");
userService.join(user);
return ResponseEntity.ok("User registered successfully");
}
//
// @PostMapping("/login")
// public ResponseEntity<User> login(@RequestBody User user) {
// try {
// User loggedInUser = userService.login(user);
// return ResponseEntity.ok(loggedInUser);
//
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
@Operation(summary = "로그인", description = "아이디와 비밀번호를 이용하여 로그인 처리.")
@PostMapping("/login")
public ResponseEntity<User> login(@RequestBody User user) {
public ResponseEntity<Map<String, Object>> login(
@RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user) {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
try {
User loggedInUser = userService.login(user);
return ResponseEntity.ok(loggedInUser);
User loginUser = userService.login(user);
if (loginUser != null) {
String accessToken = jwtUtil.createAccessToken(String.valueOf(loginUser.getId()));
String refreshToken = jwtUtil.createRefreshToken(String.valueOf(loginUser.getId()));
// 발급받은 refresh token DB에 저장.
userService.saveRefreshToken(loginUser.getId(), refreshToken);
// JSON 으로 token 전달.
System.out.println(accessToken);
resultMap.put("access-token", accessToken);
resultMap.put("refresh-token", refreshToken);
status = HttpStatus.CREATED;
} else {
resultMap.put("message", "아이디 또는 패스워드를 확인해 주세요.");
status = HttpStatus.UNAUTHORIZED;
}
} catch (Exception e) {
throw new RuntimeException(e);
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
return new ResponseEntity<>(resultMap, status);
}
@Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.")
@GetMapping("/info/{userId}")
public ResponseEntity<Map<String, Object>> getInfo(
@PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId,
HttpServletRequest request) {
//logger.debug("userId : {} ", userId);
String id = String.valueOf(userId);
System.out.println("!>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(id);
System.out.println(id.getClass().getName());
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
if (jwtUtil.checkToken(request.getHeader("Authorization"))) {
log.info("사용 가능한 토큰!!!");
try {
// 로그인 사용자 정보.
User member = userService.userInfo(userId);
resultMap.put("userInfo", member);
status = HttpStatus.OK;
} catch (Exception e) {
log.error("정보조회 실패 : {}", e);
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
} else {
System.out.println(jwtUtil.checkToken(request.getHeader("Authorization")));
log.error("사용 불가능 토큰!!!");
resultMap.put("message", "Unauthorized token");
status = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
}
@GetMapping("/logout/{userId}")
public ResponseEntity<?> removeToken(@PathVariable ("userId") @Parameter(description = "로그아웃 할 회원의 아이디.", required = true) Long userId) {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
try {
userService.deleteRefreshToken(userId);
status = HttpStatus.OK;
} catch (Exception e) {
log.error("로그아웃 실패 : {}", e);
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
}
@Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.")
@PostMapping("/refresh")
public ResponseEntity<?> refreshToken(@RequestBody User user, HttpServletRequest request)
throws Exception {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
String token = request.getHeader("refreshToken");
log.debug("token : {}, memberDto : {}", token, user);
if (jwtUtil.checkToken(token)) {
if (token.equals(userService.getRefreshToken(user.getId()))) {
String accessToken = jwtUtil.createAccessToken(String.valueOf(user.getId()));
log.debug("token : {}", accessToken);
log.debug("정상적으로 access token 재발급!!!");
resultMap.put("access-token", accessToken);
status = HttpStatus.CREATED;
}
} else {
log.debug("refresh token 도 사용 불가!!!!!!!");
status = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
}
@Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.")
@GetMapping("/member")
public ResponseEntity<Map<String, Object>> getMember(HttpServletRequest request) {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
String token = request.getHeader("Authorization");
if (jwtUtil.checkToken(token)) {
String userId = jwtUtil.getUserId(token);
log.info("사용 가능한 토큰!!! userId: {}", userId);
try {
User user = userService.userInfo(Long.parseLong(userId));
resultMap.put("userInfo", user);
status = HttpStatus.OK;
} catch (Exception e) {
log.error("정보조회 실패 : {}", e);
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
} else {
log.error("사용 불가능 토큰!!!");
status = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
}
}

View File

@ -0,0 +1,40 @@
package com.edufocus.edufocus.user.intercepter;
import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import com.edufocus.edufocus.user.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
private final String HEADER_AUTH = "Authorization";
private JWTUtil jwtUtil;
public JWTInterceptor(JWTUtil jwtUtil) {
super();
this.jwtUtil = jwtUtil;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
final String token = request.getHeader(HEADER_AUTH);
if (token != null && jwtUtil.checkToken(token)) {
log.info("토큰 사용 가능 : {}", token);
return true;
} else {
log.info("토큰 사용 불가능 : {}", token);
throw new UnAuthorizedException();
}
}
}

View File

@ -1,10 +1,15 @@
package com.edufocus.edufocus.user.model.entity;
import com.edufocus.edufocus.qna.entity.Qna;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
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
@Getter
@ -15,14 +20,20 @@ public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 자동 증가 설정
@Column(name = "id")
private Long id;
private String user_id;
@Column(name = "user_id", unique = true, nullable = false)
private String userId;
private String email;
private String password;
@Enumerated(EnumType.STRING) // 혹은 EnumType.ORDINAL
private UserRole role;
private String refreshToken;
}

View File

@ -0,0 +1,11 @@
package com.edufocus.edufocus.user.model.exception;
public class UnAuthorizedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnAuthorizedException() {
super("계정 권한이 유효하지 않습니다.\n다시 로그인을 하세요.");
}
}

View File

@ -1,8 +1,28 @@
package com.edufocus.edufocus.user.model.repository;
import com.edufocus.edufocus.user.model.entity.User;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User,Long> {
@Modifying
@Transactional
@Query("UPDATE User u SET u.refreshToken = :refreshToken WHERE u.id = :id")
void saveRefreshToken(@Param("id") Long id, @Param("refreshToken") String refreshToken);
@Query("SELECT u.refreshToken FROM User u WHERE u.id = :id")
String getRefreshToken(@Param("id") Long id);
@Modifying
@Transactional
@Query("UPDATE User u SET u.refreshToken = NULL WHERE u.id = :id")
void deleteRefreshToken(@Param("id") Long id);
Optional<User> findByUserId(String userId);
}

View File

@ -5,4 +5,8 @@ import com.edufocus.edufocus.user.model.entity.User;
public interface UserService {
void join(User user) throws Exception;
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;
}

View File

@ -10,6 +10,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Service
@ -26,18 +28,65 @@ public class UserServiceImpl implements UserService{
userRepository.save(user);
}
public User login(User user) throws SQLException
{
Optional<User> findUser = userRepository.findById(user.getId());
Optional<User> findUser = userRepository.findByUserId(user.getUserId());
if(findUser.isEmpty())
{
throw new UserException("없는 유저");
}
return findUser.get();
if(findUser.isPresent())
{
User find = findUser.get();
if(find.getPassword().equals(user.getPassword()))
{
return find;
}
else{
throw new UserException("비밀번호 틀림");
}
}
else{
throw new UserException("없는 유저");
}
}
@Override
public User userInfo(Long id)
{
try{
return userRepository.findById(id).get();
}
catch (Exception e)
{
throw new UserException(e.getMessage());
}
}
@Override
public void saveRefreshToken(Long id, String refreshToken) throws Exception {
userRepository.saveRefreshToken(id, refreshToken);
}
@Override
public String getRefreshToken(Long id) throws Exception {
return userRepository.getRefreshToken(id);
}
@Override
public void deleteRefreshToken(Long id) throws Exception {
userRepository.deleteRefreshToken(id);
}
}

View File

@ -0,0 +1,85 @@
package com.edufocus.edufocus.user.util;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class JWTUtil {
@Value("${jwt.salt}")
private String salt;
@Value("${jwt.access-token.expiretime}")
private long accessTokenExpireTime;
@Value("${jwt.refresh-token.expiretime}")
private long refreshTokenExpireTime;
public String createAccessToken(String id) {
return create(id, "access-token", accessTokenExpireTime);
}
public String createRefreshToken(String id) {
return create(id, "refresh-token", refreshTokenExpireTime);
}
private String create(String id, String subject, long expireTime) {
Claims claims = Jwts.claims()
.setSubject(subject)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expireTime));
claims.put("id", id);
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setClaims(claims)
.signWith(SignatureAlgorithm.HS256, generateKey())
.compact();
}
private byte[] generateKey() {
return salt.getBytes(StandardCharsets.UTF_8);
}
public boolean checkToken(String token) {
try {
Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(generateKey())
.build()
.parseClaimsJws(token);
log.debug("claims: {}", claims);
return true;
} catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException | ExpiredJwtException e) {
log.error("Token validation error: {}", e.getMessage());
return false;
} catch (Exception e) {
System.out.println(token);
log.error("Unexpected error while validating token: {}", e.getMessage());
return false;
}
}
public String getUserId(String authorization) {
try {
Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(generateKey())
.build()
.parseClaimsJws(authorization);
Map<String, Object> value = claims.getBody();
log.info("value : {}", value);
return (String) value.get("id");
} catch (Exception e) {
log.error("Failed to get user ID from token: {}", e.getMessage());
throw new UnAuthorizedException();
}
}
}

View File

@ -6,7 +6,15 @@ server.ssl.enabled=false
# LiveKit configuration
livekit.api.key=${LIVEKIT_API_KEY:devkey}
livekit.api.secret=${LIVEKIT_API_SECRET:secret}
# JWT Salt (??? ?? ???? ???)
jwt.salt=ssafy-screte-key-20240404-ssafy-screte-key-20240404-ssafy-screte-key-20240404
# Access Token ?? ?? (??? ??)
jwt.access-token.expiretime=3600000
# Refresh Token ?? ?? (??? ??)
jwt.refresh-token.expiretime=86400000
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/edufocus?useSSL=false
spring.datasource.username=root