Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2e5e6be

Browse files
author
kimyonghwa
committed
Develop simple board
2 parents dac4f28 + 0bcbc81 commit 2e5e6be

File tree

18 files changed

+200
-76
lines changed

18 files changed

+200
-76
lines changed

‎src/main/java/com/rest/api/SpringRestApiApplication.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
77
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
88
import org.springframework.context.annotation.Bean;
9+
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
910
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
1011
import org.springframework.security.crypto.password.PasswordEncoder;
1112
import org.springframework.web.client.RestTemplate;
1213

14+
@EnableJpaAuditing
1315
@SpringBootApplication
1416
public class SpringRestApiApplication {
1517
public static void main(String[] args) {

‎src/main/java/com/rest/api/advice/ExceptionAdvice.java‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public class ExceptionAdvice {
2626
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
2727
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
2828
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
29-
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg")+"("+e.getMessage()+")");
29+
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg") + "(" + e.getMessage() + ")");
3030
}
3131

3232
@ExceptionHandler(CUserNotFoundException.class)
@@ -48,7 +48,7 @@ public CommonResult authenticationEntryPointException(HttpServletRequest request
4848
}
4949

5050
@ExceptionHandler(AccessDeniedException.class)
51-
@ResponseStatus(HttpStatus.UNAUTHORIZED)
51+
@ResponseStatus(HttpStatus.FORBIDDEN)
5252
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
5353
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
5454
}
@@ -65,10 +65,23 @@ public CommonResult communicationException(HttpServletRequest request, CUserExis
6565
return responseService.getFailResult(Integer.valueOf(getMessage("existingUser.code")), getMessage("existingUser.msg"));
6666
}
6767

68+
@ExceptionHandler(CNotOwnerException.class)
69+
@ResponseStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION)
70+
public CommonResult notOwnerException(HttpServletRequest request, CNotOwnerException e) {
71+
return responseService.getFailResult(Integer.valueOf(getMessage("notOwner.code")), getMessage("notOwner.msg"));
72+
}
73+
74+
@ExceptionHandler(CResourceNotExistException.class)
75+
@ResponseStatus(HttpStatus.NOT_FOUND)
76+
public CommonResult resourceNotExistException(HttpServletRequest request, CResourceNotExistException e) {
77+
return responseService.getFailResult(Integer.valueOf(getMessage("resourceNotExist.code")), getMessage("resourceNotExist.msg"));
78+
}
79+
6880
// code정보에 해당하는 메시지를 조회합니다.
6981
private String getMessage(String code) {
7082
return getMessage(code, null);
7183
}
84+
7285
// code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
7386
private String getMessage(String code, Object[] args) {
7487
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.rest.api.advice.exception;
2+
3+
public class CNotOwnerException extends RuntimeException {
4+
5+
private static final long serialVersionUID = 2241549550934267615L;
6+
7+
public CNotOwnerException(String msg, Throwable t) {
8+
super(msg, t);
9+
}
10+
11+
public CNotOwnerException(String msg) {
12+
super(msg);
13+
}
14+
15+
public CNotOwnerException() {
16+
super();
17+
}
18+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.rest.api.advice.exception;
2+
3+
public class CResourceNotExistException extends RuntimeException {
4+
public CResourceNotExistException(String msg, Throwable t) {
5+
super(msg, t);
6+
}
7+
8+
public CResourceNotExistException(String msg) {
9+
super(msg);
10+
}
11+
12+
public CResourceNotExistException() {
13+
super();
14+
}
15+
}

‎src/main/java/com/rest/api/config/security/CustomAccessDeniedHandler.java‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
import org.springframework.security.web.access.AccessDeniedHandler;
66
import org.springframework.stereotype.Component;
77

8-
import javax.servlet.RequestDispatcher;
9-
import javax.servlet.ServletException;
108
import javax.servlet.http.HttpServletRequest;
119
import javax.servlet.http.HttpServletResponse;
1210
import java.io.IOException;
@@ -16,9 +14,7 @@
1614
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
1715

1816
@Override
19-
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
20-
ServletException {
21-
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/accessdenied");
22-
dispatcher.forward(request, response);
17+
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException {
18+
response.sendRedirect("/exception/accessdenied");
2319
}
24-
}
20+
}

‎src/main/java/com/rest/api/config/security/CustomAuthenticationEntryPoint.java‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,15 @@
55
import org.springframework.security.web.AuthenticationEntryPoint;
66
import org.springframework.stereotype.Component;
77

8-
import javax.servlet.RequestDispatcher;
9-
import javax.servlet.ServletException;
108
import javax.servlet.http.HttpServletRequest;
119
import javax.servlet.http.HttpServletResponse;
1210
import java.io.IOException;
1311

1412
@Slf4j
1513
@Component
1614
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
17-
1815
@Override
19-
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
20-
ServletException {
21-
// RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/entrypoint");
22-
// dispatcher.forward(request, response);
16+
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
2317
response.sendRedirect("/exception/entrypoint");
2418
}
25-
}
19+
}

‎src/main/java/com/rest/api/config/security/SecurityConfiguration.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ protected void configure(HttpSecurity http) throws Exception {
3232
.and()
3333
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
3434
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
35-
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/*", "/v1/board/*/posts").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
35+
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
3636
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
3737
.and()
3838
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())

‎src/main/java/com/rest/api/controller/HelloController.java‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import lombok.extern.slf4j.Slf4j;
66
import org.springframework.stereotype.Controller;
77
import org.springframework.web.bind.annotation.GetMapping;
8-
import org.springframework.web.bind.annotation.RequestMapping;
98
import org.springframework.web.bind.annotation.ResponseBody;
109

1110
@Slf4j

‎src/main/java/com/rest/api/controller/v1/board/BoardController.java‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@
33
import com.rest.api.entity.board.Board;
44
import com.rest.api.entity.board.Post;
55
import com.rest.api.model.board.ParamsPost;
6+
import com.rest.api.model.response.CommonResult;
67
import com.rest.api.model.response.ListResult;
78
import com.rest.api.model.response.SingleResult;
89
import com.rest.api.service.ResponseService;
910
import com.rest.api.service.board.BoardService;
1011
import io.swagger.annotations.Api;
12+
import io.swagger.annotations.ApiImplicitParam;
13+
import io.swagger.annotations.ApiImplicitParams;
1114
import io.swagger.annotations.ApiOperation;
1215
import lombok.RequiredArgsConstructor;
16+
import org.springframework.security.core.Authentication;
17+
import org.springframework.security.core.context.SecurityContextHolder;
1318
import org.springframework.web.bind.annotation.*;
1419

1520
import javax.validation.Valid;
@@ -24,20 +29,54 @@ public class BoardController {
2429
private final ResponseService responseService;
2530

2631
@ApiOperation(value = "게시판 정보 조회", notes = "게시판 정보를 조회한다.")
27-
@GetMapping(value="/{boardName}")
32+
@GetMapping(value = "/{boardName}")
2833
public SingleResult<Board> boardInfo(@PathVariable String boardName) {
2934
return responseService.getSingleResult(boardService.findBoard(boardName));
3035
}
3136

32-
@ApiOperation(value = "게시판 포스트 조회", notes = "게시판의 포스팅 정보를 조회한다.")
33-
@GetMapping(value="/{boardName}/posts")
37+
@ApiOperation(value = "게시판 글 리스트", notes = "게시판의 포스팅 정보를 조회한다.")
38+
@GetMapping(value = "/{boardName}/posts")
3439
public ListResult<Post> posts(@PathVariable String boardName) {
3540
return responseService.getListResult(boardService.findPosts(boardName));
3641
}
3742

38-
@ApiOperation(value = "게시판 글쓰기", notes = "게시판에 글을 작성한다.")
39-
@PostMapping(value="/{boardName}")
40-
public SingleResult<Post> post(@PathVariable String boardName, @Valid ParamsPost post) {
41-
return responseService.getSingleResult(boardService.writePost(boardName, post));
43+
@ApiImplicitParams({
44+
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
45+
})
46+
@ApiOperation(value = "게시판 글 작성", notes = "게시판에 글을 작성한다.")
47+
@PostMapping(value = "/{boardName}")
48+
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
49+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
50+
String uid = authentication.getName();
51+
return responseService.getSingleResult(boardService.writePost(uid, boardName, post));
52+
}
53+
54+
@ApiOperation(value = "게시판 글 상세", notes = "게시판 글 상세정보를 조회한다.")
55+
@GetMapping(value = "/post/{postId}")
56+
public SingleResult<Post> post(@PathVariable long postId) {
57+
return responseService.getSingleResult(boardService.getPost(postId));
58+
}
59+
60+
@ApiImplicitParams({
61+
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
62+
})
63+
@ApiOperation(value = "게시판 글 수정", notes = "게시판의 글을 수정한다.")
64+
@PutMapping(value = "/post/{postId}")
65+
public SingleResult<Post> post(@PathVariable long postId, @Valid @ModelAttribute ParamsPost post) {
66+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
67+
String uid = authentication.getName();
68+
return responseService.getSingleResult(boardService.updatePost(postId, uid, post));
69+
}
70+
71+
@ApiImplicitParams({
72+
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
73+
})
74+
@ApiOperation(value = "게시판 글 삭제", notes = "게시판의 글을 삭제한다.")
75+
@DeleteMapping(value = "/post/{postId}")
76+
public CommonResult deletePost(@PathVariable long postId) {
77+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
78+
String uid = authentication.getName();
79+
boardService.deletePost(postId, uid);
80+
return responseService.getSuccessResult();
4281
}
4382
}

‎src/main/java/com/rest/api/entity/User.java‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
package com.rest.api.entity;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
34
import com.fasterxml.jackson.annotation.JsonProperty;
4-
import lombok.*;
5+
import lombok.AllArgsConstructor;
6+
import lombok.Builder;
7+
import lombok.Getter;
8+
import lombok.NoArgsConstructor;
59
import org.springframework.security.core.GrantedAuthority;
610
import org.springframework.security.core.authority.SimpleGrantedAuthority;
711
import org.springframework.security.core.userdetails.UserDetails;
@@ -18,10 +22,11 @@
1822
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
1923
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
2024
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
25+
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
2126
public class User implements UserDetails {
2227
@Id // pk
2328
@GeneratedValue(strategy = GenerationType.IDENTITY)
24-
private long msrl;
29+
private Long msrl;
2530
@Column(nullable = false, unique = true, length = 50)
2631
private String uid;
2732
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /