[Practice] 사용자 관련 API 만들기 (5)

2021. 4. 17. 17:12Spring/Practice

1. 문제

  • 사용자의 포인트 정보를 만들고 게시글을 작성할 경우, 포인트를 누적하는 API

 

 

 

2. 풀이

- schema.sql

DROP TABLE IF EXISTS USER;
DROP TABLE IF EXISTS NOTICE;

create table USER (
    ID          BIGINT auto_increment primary key,
    EMAIL       VARCHAR(255),
    NAME        VARCHAR(255),
    PASSWORD    VARCHAR(255),
    PHONE       VARCHAR(255),
    REG_DATE    TIMESTAMP,
    UPDATE_DATE TIMESTAMP,
    STATUS      INTEGER,
    LOCK_YN     BOOLEAN DEFAULT FALSE
);

create table NOTICE (
    ID          BIGINT auto_increment primary key,
    TITLE       VARCHAR(255),
    CONTENTS    VARCHAR(255),

    HITS        INTEGER,
    LIKES       INTEGER,

    REG_DATE    TIMESTAMP,
    UPDATE_DATE TIMESTAMP,
    DELETED     BOOLEAN DEFAULT FALSE,
    DELETED_DATE    TIMESTAMP,

    USER_ID     BIGINT,
    constraint FK_NOTICE_USER_ID foreign key(USER_ID) references USER(ID)
);

create table NOTICE_LIKE (
    ID          BIGINT auto_increment primary key,

    NOTICE_ID   BIGINT,
    constraint FK_NOTICE_LIKE_NOTICE_ID foreign key(NOTICE_ID) references NOTICE(ID),

    USER_ID     BIGINT,
    constraint FK_NOTICE_LIKE_USER_ID foreign key(USER_ID) references USER(ID)
);

create table USER_LOGIN_HISTORY (
    ID          BIGINT auto_increment primary key,
    USER_ID     BIGINT,
    EMAIL       VARCHAR(255),
    NAME        VARCHAR(255),
    LOGIN_DATE  TIMESTAMP,
    IP_ADDR     VARCHAR(255)
);

create table BOARD_TYPE (
    ID          BIGINT auto_increment primary key,
    BOARD_NAME  VARCHAR(255),
    REG_DATE    TIMESTAMP,
    UPDATE_DATE TIMESTAMP,
    USING_YN    BOOLEAN DEFAULT FALSE
);

-- auto-generated definition
create table BOARD
(
    ID            BIGINT auto_increment primary key,
    CONTENTS      VARCHAR(255),
    REG_DATE      TIMESTAMP,
    TITLE         VARCHAR(255),
    BOARD_TYPE_ID BIGINT,
    USER_ID       BIGINT,
    TOP_YN        BOOLEAN DEFAULT FALSE,
    PUBLISH_START_DATE    DATE,
    PUBLISH_END_DATE      DATE,

    constraint FK_BOARD_BOARD_TYPE_ID foreign key (BOARD_TYPE_ID) references BOARD_TYPE (ID),
    constraint FK_BOARD_USER_ID foreign key (USER_ID) references USER (ID)
);

-- auto-generated definition
create table BOARD_HITS
(
    ID       BIGINT auto_increment primary key,
    REG_DATE TIMESTAMP,
    BOARD_ID BIGINT,
    USER_ID  BIGINT,

    constraint FK_BOARD_HITS_BOARD_ID foreign key (BOARD_ID) references BOARD (ID),
    constraint FK_BOARD_HITS_USER_ID foreign key (USER_ID) references USER (ID)
);

create table BOARD_LIKE
(
    ID       BIGINT auto_increment primary key,
    REG_DATE TIMESTAMP,
    BOARD_ID BIGINT,
    USER_ID  BIGINT,

    constraint FK_BOARD_LIKE_BOARD_ID foreign key (BOARD_ID) references BOARD (ID),
    constraint FK_BOARD_LIKE_USER_ID foreign key (USER_ID) references USER (ID)
);

-- auto-generated definition
create table BOARD_BAD_REPORT
(
    ID             BIGINT auto_increment primary key,
    BOARD_CONTENTS VARCHAR(255),
    BOARD_ID       BIGINT,
    BOARD_REG_DATE TIMESTAMP,
    BOARD_TITLE    VARCHAR(255),
    BOARD_USER_ID  BIGINT,
    COMMENTS       VARCHAR(255),
    USER_EMAIL     VARCHAR(255),
    USER_ID        BIGINT,
    USER_NAME      VARCHAR(255)
);

-- auto-generated definition
create table BOARD_SCRAP
(
    ID             BIGINT auto_increment primary key,
    BOARD_CONTENTS VARCHAR(255),
    BOARD_ID       BIGINT,
    BOARD_REG_DATE TIMESTAMP,
    BOARD_TITLE    VARCHAR(255),
    BOARD_TYPE_ID  BIGINT,
    BOARD_USER_ID  BIGINT,
    REG_DATE       TIMESTAMP,
    USER_ID        BIGINT,
    constraint FK_BOARD_SCRAP_USER_ID foreign key (USER_ID) references USER (ID)
);

-- auto-generated definition
create table BOARD_BOOKMARK
(
    ID             BIGINT auto_increment primary key,
    BOARD_ID       BIGINT,
    BOARD_TITLE    VARCHAR(255),
    BOARD_TYPE_ID  BIGINT,
    BOARD_URL      VARCHAR(255),
    REG_DATE       TIMESTAMP,
    USER_ID        BIGINT,

    constraint FK_BOARD_BOOKMARK_USER_ID foreign key (USER_ID) references USER (ID)
);

create table USER_INTEREST (
    ID                  BIGINT auto_increment primary key,
    USER_ID             BIGINT,
    INTEREST_USER_ID    BIGINT,
    REG_DATE            TIMESTAMP,
    constraint FK_USER_INTEREST_USER_ID foreign key (USER_ID) references USER (ID),
    constraint FK_USER_INTEREST_INTEREST_USER_ID foreign key (INTEREST_USER_ID) references USER (ID)
);

-- auto-generated definition
create table BOARD_COMMENT
(
    ID       BIGINT auto_increment primary key,
    COMMENTS VARCHAR(255),
    REG_DATE TIMESTAMP,
    BOARD_ID BIGINT,
    USER_ID  BIGINT,

    constraint FK_BOARD_COMMENT_USER_ID foreign key (USER_ID) references USER (ID),
    constraint FK_BOARD_COMMENT_BOARD_ID foreign key (BOARD_ID) references BOARD (ID)
);

-- auto-generated definition
create table USER_POINT
(
    ID              BIGINT auto_increment primary key,
    POINT           INTEGER,
    USER_POINT_TYPE VARCHAR(255),
    USER_ID         BIGINT,
    constraint FK_USER_POINT_USER_ID foreign key (USER_ID) references USER (ID)
);

- UserPointType.java

package com.example.jpa.sample.user.model;

public enum  UserPointType {

    NONE(0),

    USER_REGISTER(100),

    ADD_POST(200),

    ADD_COMMENT(150),

    ADD_LIKE(50);

    int value;

    public int getValue() {
        return this.value;
    }

    UserPointType(int value) {
        this.value = value;
    }
}

- UserPoint.java

package com.example.jpa.sample.user.entity;

import com.example.jpa.sample.user.model.UserPointType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@Entity
public class UserPoint {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn
    private User user;

    @Enumerated(EnumType.STRING) // enum 타입을 문자열로 저장
    @Column
    private UserPointType userPointType;

    @Column
    private int point;
}

- UserPointRepository.java

package com.example.jpa.sample.user.repository;

import com.example.jpa.sample.user.entity.UserPoint;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserPointRepository extends JpaRepository<UserPoint, Long> {

}

- UserPointInput.java

package com.example.jpa.sample.user.model;

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

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class UserPointInput {

    private UserPointType userPointType;
}

- UserPointService.java

package com.example.jpa.sample.user.service;

import com.example.jpa.sample.board.model.ServiceResult;
import com.example.jpa.sample.user.model.UserPointInput;

public interface UserPointService {

    ServiceResult addPoint(String email, UserPointInput userPointInput);
}

- UserPointServiceImpl.java

package com.example.jpa.sample.user.service;

import com.example.jpa.sample.board.model.ServiceResult;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.entity.UserPoint;
import com.example.jpa.sample.user.model.UserPointInput;
import com.example.jpa.sample.user.repository.UserPointRepository;
import com.example.jpa.sample.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@RequiredArgsConstructor
@Service
public class UserPointServiceImpl implements UserPointService {

    private final UserRepository userRepository;
    private final UserPointRepository userPointRepository;

    @Override
    public ServiceResult addPoint(String email, UserPointInput userPointInput) {
        Optional<User> optionalUser = userRepository.findByEmail(email);
        if(!optionalUser.isPresent()) {
            return ServiceResult.fail("회원 정보가 존재하지 않습니다.");
        }
        User user = optionalUser.get();

        userPointRepository.save(UserPoint.builder()
                .user(user)
                .userPointType(userPointInput.getUserPointType())
                .point(userPointInput.getUserPointType().getValue())
                .build());

        return ServiceResult.success();
    }
}

- ApiUserController.java

package com.example.jpa.sample.user.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.example.jpa.sample.board.entity.Board;
import com.example.jpa.sample.board.entity.BoardComment;
import com.example.jpa.sample.board.model.ServiceResult;
import com.example.jpa.sample.board.service.BoardService;
import com.example.jpa.sample.common.model.ResponseResult;
import com.example.jpa.sample.notice.entity.Notice;
import com.example.jpa.sample.notice.entity.NoticeLike;
import com.example.jpa.sample.notice.model.NoticeResponse;
import com.example.jpa.sample.notice.model.ResponseError;
import com.example.jpa.sample.notice.repository.NoticeLikeRepository;
import com.example.jpa.sample.notice.repository.NoticeRepository;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.exception.ExistsEmailException;
import com.example.jpa.sample.user.exception.PasswordNotMatchException;
import com.example.jpa.sample.user.exception.UserNotFoundException;
import com.example.jpa.sample.user.model.*;
import com.example.jpa.sample.user.repository.UserPointRepository;
import com.example.jpa.sample.user.repository.UserRepository;
import com.example.jpa.sample.user.service.UserPointService;
import com.example.jpa.sample.util.JwtUtils;
import com.example.jpa.sample.util.PasswordUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RequiredArgsConstructor
@RestController
public class ApiUserController {

    private final UserRepository userRepository;
    private final NoticeRepository noticeRepository;
    private final NoticeLikeRepository noticeLikeRepository;

    private final BoardService boardService;
    private final UserPointService userPointService;

    /*
    // 문제 1
    @PostMapping("/api/user")
    public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

//        return ResponseEntity.ok().build();
        return new ResponseEntity<>(HttpStatus.OK);
    }
     */

    /*
    // 문제 2
    @PostMapping("/api/user")
    public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        userRepository.save(User.builder()
                .email(userInput.getEmail())
                .name(userInput.getName())
                .password(userInput.getPassword())
                .phone(userInput.getPhone())
                .regDate(LocalDateTime.now())
                .build()
        );

        return new ResponseEntity<>(HttpStatus.OK);
    }
     */

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<?> handlerUserNotFoundException(UserNotFoundException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
    }

    // 문제 3
    @PutMapping("/api/user/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody @Valid UserUpdate userUpdate, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));
        user.setPhone(userUpdate.getPhone());
        user.setUpdateDate(LocalDateTime.now());
        userRepository.save(user);

        return ResponseEntity.ok().build();
    }

    // 문제 4
    @GetMapping("/api/user/{id}")
    public UserResponse getUser(@PathVariable Long id) {

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

//        UserResponse userResponse = new UserResponse(user);
        UserResponse userResponse = UserResponse.of(user);

        return userResponse;
    }

    // 문제 5
    @GetMapping("/api/user/{id}/notice")
    public List<NoticeResponse> userNotice(@PathVariable Long id) {

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        List<Notice> noticeList = noticeRepository.findByUser(user);

        List<NoticeResponse> noticeResponsesList = new ArrayList<>();
        noticeList.stream().forEach(e -> {
            noticeResponsesList.add(NoticeResponse.of(e));
        });

        return noticeResponsesList;
    }

    @ExceptionHandler(value = {ExistsEmailException.class, PasswordNotMatchException.class})
    public ResponseEntity<?> handlerExistsEmailException(RuntimeException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
    }

    /*
    // 문제 6
    @PostMapping("/api/user")
    public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        if(userRepository.countByEmail(userInput.getEmail()) > 0) {
            throw new ExistsEmailException("이미 가입된 이메일이 존재합니다.");
        }

        userRepository.save(User.builder()
                .email(userInput.getEmail())
                .name(userInput.getName())
                .password(userInput.getPassword())
                .phone(userInput.getPhone())
                .regDate(LocalDateTime.now())
                .build()
        );

        return new ResponseEntity<>(HttpStatus.OK);
    }
     */

    // 문제 7
    @PatchMapping("/api/user/{id}/password")
    public ResponseEntity<?> updateUserPassword(@PathVariable Long id, @RequestBody @Valid UserInputPassword userInputPassword, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        User user = userRepository.findByIdAndPassword(id, userInputPassword.getPassword()).orElseThrow(() -> new PasswordNotMatchException("비밀번호가 일치하지 않습니다."));
        user.setPassword(userInputPassword.getNewPassword());
        userRepository.save(user);

        return ResponseEntity.ok().build();
    }

    private String getEncyrptPassword(String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encryptedPassword = bCryptPasswordEncoder.encode(password);

        return encryptedPassword;
    }

    // 문제 8
    @PostMapping("/api/user")
    public ResponseEntity<?> addUser(@RequestBody @Valid UserInput userInput, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        if(userRepository.countByEmail(userInput.getEmail()) > 0) {
            throw new ExistsEmailException("이미 가입된 이메일이 존재합니다.");
        }

        userRepository.save(User.builder()
                .email(userInput.getEmail())
                .name(userInput.getName())
                .password(getEncyrptPassword(userInput.getPassword()))
                .phone(userInput.getPhone())
                .regDate(LocalDateTime.now())
                .build()
        );

        return new ResponseEntity<>(HttpStatus.OK);
    }

    // 문제 9
    @DeleteMapping("/api/user/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        try {
            userRepository.delete(user);
        } catch (DataIntegrityViolationException e) {
            String message = "제약조건에 문제가 발생했습니다.";
            return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            String message = "회원탈퇴 중 문제가 발생했습니다.";
            return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
        }

        return ResponseEntity.ok().build();

    }

    // 문제 10
    @GetMapping("/api/user")
    public ResponseEntity<?> findUser(@RequestBody UserInputFind userInputFind) {

        User user = userRepository.findByNameAndPhone(userInputFind.getName(), userInputFind.getPhone())
                .orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        UserResponse userResponse = UserResponse.of(user);
        return ResponseEntity.ok().body(userResponse);
    }

    private String getResetpassword() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
    }

    private void sendSMS(String message) {
        System.out.println("[문자메시지전송]\n" + message);
    }

    // 문제 11
    @GetMapping("/api/user/{id}/password/reset")
    public ResponseEntity<?> resetUserPassword(@PathVariable Long id) {

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        String resetPassword = getResetpassword();
        String resetEncryptPassword = getEncyrptPassword(resetPassword);
        user.setPassword(resetEncryptPassword);
        userRepository.save(user);

        // 문자 전송
        String message = String.format("[%s]님의 임시 비밀번호가 [%s]로 초기화 되었습니다.", user.getName(), resetPassword);
        sendSMS(message);

        return ResponseEntity.ok().build();
    }

    // 문제 12
    @GetMapping("/api/user/{id}/notice/like")
    public List<NoticeLike> likeNotice(@PathVariable Long id) {

        User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        List<NoticeLike> noticeLikeList = noticeLikeRepository.findByUser(user);
        return noticeLikeList;
    }

    // 문제 13
    @PostMapping("/api/user/login")
    public ResponseEntity<?> createToken(@RequestBody @Valid UserLogin userLogin, Errors errors) {

        List<ResponseError> responseErrorList = new ArrayList<>();

        if(errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> {
                responseErrorList.add(ResponseError.of((FieldError)e));
            });
            return new ResponseEntity<>(responseErrorList, HttpStatus.BAD_REQUEST);
        }

        User user = userRepository.findByEmail(userLogin.getEmail()).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        if(!PasswordUtils.equalPassword(userLogin.getPassword(), user.getPassword())) {
            throw new PasswordNotMatchException("비밀번호가 일치하지 않습니다.");
        }

        LocalDateTime expiredDateTime = LocalDateTime.now().plusMonths(1);
        Date expiredDate = java.sql.Timestamp.valueOf(expiredDateTime);

        String token = JWT.create()
                .withExpiresAt(expiredDate) // 만료일 (1개월)
                .withClaim("user_id", user.getId()) // 키 저장
                .withSubject(user.getName()) // 일반적으로 사용자 이름 삽입
                .withIssuer(user.getEmail())
                .sign(Algorithm.HMAC512("q1w2e3r4t5!".getBytes())); // 암호화 키

        return ResponseEntity.ok().body(UserLoginToken.builder().token(token).build());
    }

    // 문제 14
    @PatchMapping("/api/user/login")
    public ResponseEntity<?> refreshToken(HttpServletRequest request) {

        String token = request.getHeader("X-ACCESS-TOKEN");

        String email = "";

        try {
            email = JWT.require(Algorithm.HMAC512("q1w2e3r4t5!".getBytes()))
                    .build()
                    .verify(token) // Bearer asdfjqwlejfildlka
                    .getIssuer();
        } catch (SignatureVerificationException e) {
            throw new ExistsEmailException("이메일이 존재하지 않습니다."); // 예시 1
        } catch (Exception e) {
            throw new ExistsEmailException("토큰 발행에 실패하였습니다."); // 예시 2
        }

        User user = userRepository.findByEmail(email).orElseThrow(() -> new UserNotFoundException("사용자 정보가 없습니다."));

        LocalDateTime expiredDateTime = LocalDateTime.now().plusMonths(1);
        Date expiredDate = java.sql.Timestamp.valueOf(expiredDateTime);

        String newToken = JWT.create()
                .withExpiresAt(expiredDate) // 만료일 (1개월)
                .withClaim("user_id", user.getId()) // 키 저장
                .withSubject(user.getName()) // 일반적으로 사용자 이름 삽입
                .withIssuer(user.getEmail())
                .sign(Algorithm.HMAC512("q1w2e3r4t5!".getBytes())); // 암호화 키

        return ResponseEntity.ok().body(UserLoginToken.builder().token(newToken).build());
    }

    // 문제 15
    @DeleteMapping("/api/user/login")
    public ResponseEntity<?> removeToken(@RequestHeader("X-ACCESS-TOKEN") String token) {

        String email = "";
        try {
            email = JwtUtils.getIssuer(token);
        } catch(SignatureVerificationException e) {
            return new ResponseEntity<>("토큰 정보가 정확하지 않습니다.", HttpStatus.BAD_REQUEST);
        }

        // 일반적이라면 세션, 쿠키 삭제
        // 클라이언트에서는 쿠키/로컬 스토리지/세션스토리지 삭제
        // 블랙리스트 작성

        return ResponseEntity.ok().build();
    }

    //------------------------------------------------------------------------------
    // 문제 3
    @GetMapping("/api/user/board/post")
    public ResponseEntity<?> myPost(@RequestHeader("X-ACCESS-TOKEN") String token) {
        String email = "";
        try {
            email = JwtUtils.getIssuer(token);
        } catch(JWTVerificationException e) {
            return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
        }

        List<Board> boardList = boardService.postList(email);

        return ResponseResult.success(boardList);
    }

    // 문제 4
    @GetMapping("/api/user/board/comment")
    public ResponseEntity<?> myComments(@RequestHeader("X-ACCESS-TOKEN") String token) {
        String email = "";
        try {
            email = JwtUtils.getIssuer(token);
        } catch(JWTVerificationException e) {
            return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
        }

        List<BoardComment> boardCommentList = boardService.commentList(email);

        return ResponseResult.success(boardCommentList);
    }

    // 문제 5
    @PostMapping("/api/user/point")
    public ResponseEntity<?> userPoint(@RequestHeader("X-ACCESS-TOKEN") String token, @RequestBody UserPointInput userPointInput) {
        String email = "";
        try {
            email = JwtUtils.getIssuer(token);
        } catch(JWTVerificationException e) {
            return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
        }

        ServiceResult result = userPointService.addPoint(email, userPointInput);

        return ResponseResult.success(result);
    }
}
728x90