Skip to content

Commit

Permalink
Apply Google Java Style Format
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaiser-Yang authored and github-actions[bot] committed Sep 16, 2024
1 parent 9a275ca commit d6c3632
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import edu.cmipt.gcs.constant.ApiPathConstant;
import edu.cmipt.gcs.constant.HeaderParameter;
import edu.cmipt.gcs.enumeration.ErrorCodeEnum;
import edu.cmipt.gcs.enumeration.TokenTypeEnum;
import edu.cmipt.gcs.exception.GenericException;
import edu.cmipt.gcs.pojo.error.ErrorVO;
import edu.cmipt.gcs.pojo.user.UserDTO;
Expand Down Expand Up @@ -146,7 +145,9 @@ public void signOut(@RequestBody List<String> tokenList) {
content = @Content(schema = @Schema(implementation = String.class))),
@ApiResponse(responseCode = "500", description = "Internal server error")
})
public ResponseEntity<Void> refreshToken(@RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken, @RequestHeader(HeaderParameter.REFRESH_TOKEN) String refreshToken) {
public ResponseEntity<Void> refreshToken(
@RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken,
@RequestHeader(HeaderParameter.REFRESH_TOKEN) String refreshToken) {
JwtUtil.blacklistToken(accessToken);
HttpHeaders headers = JwtUtil.generateHeaders(JwtUtil.getID(refreshToken), false);
return ResponseEntity.ok().headers(headers).build();
Expand Down
16 changes: 12 additions & 4 deletions src/main/java/edu/cmipt/gcs/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import edu.cmipt.gcs.constant.HeaderParameter;
import edu.cmipt.gcs.constant.ValidationConstant;
import edu.cmipt.gcs.enumeration.ErrorCodeEnum;
import edu.cmipt.gcs.enumeration.TokenTypeEnum;
import edu.cmipt.gcs.exception.GenericException;
import edu.cmipt.gcs.pojo.error.ErrorVO;
import edu.cmipt.gcs.pojo.user.UserDTO;
Expand All @@ -15,6 +14,7 @@
import edu.cmipt.gcs.service.UserService;
import edu.cmipt.gcs.util.JwtUtil;
import edu.cmipt.gcs.validation.group.UpdateGroup;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
Expand All @@ -24,6 +24,7 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
Expand Down Expand Up @@ -108,9 +109,16 @@ public UserVO getUserByName(@PathVariable("username") String username) {
in = ParameterIn.HEADER,
schema = @Schema(implementation = String.class))
})
public ResponseEntity<UserVO> updateUser(@RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken, @RequestHeader(HeaderParameter.REFRESH_TOKEN) String refreshToken, @Validated(UpdateGroup.class) @RequestBody UserDTO user) {
if (user.username() != null) { checkUsernameValidity(user.username()); }
if (user.email() != null) { checkEmailValidity(user.email()); }
public ResponseEntity<UserVO> updateUser(
@RequestHeader(HeaderParameter.ACCESS_TOKEN) String accessToken,
@RequestHeader(HeaderParameter.REFRESH_TOKEN) String refreshToken,
@Validated(UpdateGroup.class) @RequestBody UserDTO user) {
if (user.username() != null) {
checkUsernameValidity(user.username());
}
if (user.email() != null) {
checkEmailValidity(user.email());
}
// for the null fields, mybatis-plus will ignore by default
assert user.id() != null;
boolean res = userService.updateById(new UserPO(user));
Expand Down
42 changes: 28 additions & 14 deletions src/main/java/edu/cmipt/gcs/filter/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
Expand All @@ -29,9 +31,6 @@
import java.io.InputStreamReader;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* JwtFilter
*
Expand All @@ -45,8 +44,9 @@ public class JwtFilter extends OncePerRequestFilter {
/**
* CachedBodyHttpServletRequest
*
* The {@link}getInputStream() and {@link}getReader() methods of {@link}HttpServletRequest can only be called once.
* This class is used to cache the body of the request so that it can be read multiple times.
* <p>The {@link}getInputStream() and {@link}getReader() methods of {@link}HttpServletRequest
* can only be called once. This class is used to cache the body of the request so that it can
* be read multiple times.
*/
private class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private class CachedBodyServletInputStream extends ServletInputStream {
Expand Down Expand Up @@ -96,7 +96,8 @@ public ServletInputStream getInputStream() {

@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(this.cacheBody)));
return new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(this.cacheBody)));
}
}

Expand Down Expand Up @@ -124,21 +125,30 @@ protected void doFilterInternal(
}
// throw exception if authorization failed
CachedBodyHttpServletRequest cachedRequest = new CachedBodyHttpServletRequest(request);
authorize(cachedRequest, cachedRequest.getHeader(HeaderParameter.ACCESS_TOKEN), cachedRequest.getHeader(HeaderParameter.REFRESH_TOKEN));
authorize(
cachedRequest,
cachedRequest.getHeader(HeaderParameter.ACCESS_TOKEN),
cachedRequest.getHeader(HeaderParameter.REFRESH_TOKEN));
filterChain.doFilter(cachedRequest, response);
}

private void authorize(HttpServletRequest request, String accessToken, String refreshToken) {
if (accessToken != null && JwtUtil.getTokenType(accessToken) != TokenTypeEnum.ACCESS_TOKEN) {
if (accessToken != null
&& JwtUtil.getTokenType(accessToken) != TokenTypeEnum.ACCESS_TOKEN) {
throw new GenericException(ErrorCodeEnum.INVALID_TOKEN, accessToken);
}
if (refreshToken != null && JwtUtil.getTokenType(refreshToken) != TokenTypeEnum.REFRESH_TOKEN) {
if (refreshToken != null
&& JwtUtil.getTokenType(refreshToken) != TokenTypeEnum.REFRESH_TOKEN) {
throw new GenericException(ErrorCodeEnum.INVALID_TOKEN, refreshToken);
}
switch (request.getMethod()) {
case "GET":
if ((accessToken == null && !request.getRequestURI().equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH)) ||
(refreshToken == null && request.getRequestURI().equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH))) {
if ((accessToken == null
&& !request.getRequestURI()
.equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH))
|| (refreshToken == null
&& request.getRequestURI()
.equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH))) {
throw new GenericException(ErrorCodeEnum.TOKEN_NOT_FOUND);
}
break;
Expand All @@ -156,11 +166,15 @@ private void authorize(HttpServletRequest request, String accessToken, String re
String idInBody = getFromRequestBody(request, "id");
if (request.getRequestURI().startsWith(ApiPathConstant.USER_API_PREFIX)
&& !idInToken.equals(idInBody)) {
logger.info("User[{}] tried to update user[{}]'s information", idInToken, idInBody);
logger.info(
"User[{}] tried to update user[{}]'s information",
idInToken,
idInBody);
throw new GenericException(ErrorCodeEnum.ACCESS_DENIED);
}
} else if (request.getRequestURI().equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH) &&
refreshToken == null) {
} else if (request.getRequestURI()
.equals(ApiPathConstant.AUTHENTICATION_REFRESH_API_PATH)
&& refreshToken == null) {
// for refresh token, both access token and refresh token are needed
throw new GenericException(ErrorCodeEnum.TOKEN_NOT_FOUND);
} else {
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/edu/cmipt/gcs/pojo/user/UserDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import edu.cmipt.gcs.validation.group.UpdateGroup;

import io.swagger.v3.oas.annotations.media.Schema;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
Expand All @@ -19,9 +20,7 @@
*/
@Schema(description = "User Data Transfer Object")
public record UserDTO(
@Schema(
description = "User ID",
accessMode = Schema.AccessMode.READ_ONLY)
@Schema(description = "User ID", accessMode = Schema.AccessMode.READ_ONLY)
@Null(groups = CreateGroup.class, message = "USERDTO_ID_NULL {UserDTO.id.Null}")
@NotNull(
groups = UpdateGroup.class,
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/edu/cmipt/gcs/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

import io.jsonwebtoken.Jwts;

import org.springframework.http.HttpHeaders;

import java.util.Date;
import java.util.List;

import javax.crypto.SecretKey;

import org.springframework.http.HttpHeaders;

/**
* JwtUtil
*
Expand Down Expand Up @@ -89,7 +89,8 @@ public static HttpHeaders generateHeaders(String id, boolean addRefreshToken) {
HttpHeaders headers = new HttpHeaders();
headers.add(HeaderParameter.ACCESS_TOKEN, generateToken(id, TokenTypeEnum.ACCESS_TOKEN));
if (addRefreshToken) {
headers.add(HeaderParameter.REFRESH_TOKEN, generateToken(id, TokenTypeEnum.REFRESH_TOKEN));
headers.add(
HeaderParameter.REFRESH_TOKEN, generateToken(id, TokenTypeEnum.REFRESH_TOKEN));
}
return headers;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ public void testSignInValid() throws Exception {
.getResponse();
TestConstant.ACCESS_TOKEN = response.getHeader(HeaderParameter.ACCESS_TOKEN);
TestConstant.REFRESH_TOKEN = response.getHeader(HeaderParameter.REFRESH_TOKEN);
TestConstant.ID = JsonParserFactory.getJsonParser().parseMap(response.getContentAsString()).get("id").toString();
TestConstant.ID =
JsonParserFactory.getJsonParser()
.parseMap(response.getContentAsString())
.get("id")
.toString();
}

/**
Expand Down
111 changes: 65 additions & 46 deletions src/test/java/edu/cmipt/gcs/controller/UserControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,29 +136,39 @@ public void testUpdateUserValid() throws Exception {
TestConstant.USERNAME += new Date().getTime() + "new";
TestConstant.EMAIL = TestConstant.USERNAME + "@cmipt.edu";
TestConstant.USER_PASSWORD += "new";
var response = mvc.perform(
post(ApiPathConstant.USER_UPDATE_USER_API_PATH)
.header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN)
.header(HeaderParameter.REFRESH_TOKEN, TestConstant.REFRESH_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"id": "%s",
"username": "%s",
"email": "%s",
"userPassword": "%s"
}
""".formatted(TestConstant.ID, TestConstant.USERNAME, TestConstant.EMAIL, TestConstant.USER_PASSWORD)))
.andExpectAll(
status().isOk(),
header().exists(HeaderParameter.ACCESS_TOKEN),
header().exists(HeaderParameter.REFRESH_TOKEN),
jsonPath("$.username", is(TestConstant.USERNAME)),
jsonPath("$.email", is(TestConstant.EMAIL)),
jsonPath("$.id").isString())
.andReturn()
.getResponse();
var response =
mvc.perform(
post(ApiPathConstant.USER_UPDATE_USER_API_PATH)
.header(
HeaderParameter.ACCESS_TOKEN,
TestConstant.ACCESS_TOKEN)
.header(
HeaderParameter.REFRESH_TOKEN,
TestConstant.REFRESH_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"id": "%s",
"username": "%s",
"email": "%s",
"userPassword": "%s"
}
"""
.formatted(
TestConstant.ID,
TestConstant.USERNAME,
TestConstant.EMAIL,
TestConstant.USER_PASSWORD)))
.andExpectAll(
status().isOk(),
header().exists(HeaderParameter.ACCESS_TOKEN),
header().exists(HeaderParameter.REFRESH_TOKEN),
jsonPath("$.username", is(TestConstant.USERNAME)),
jsonPath("$.email", is(TestConstant.EMAIL)),
jsonPath("$.id").isString())
.andReturn()
.getResponse();
// make sure the new information is updated
TestConstant.ACCESS_TOKEN = response.getHeader(HeaderParameter.ACCESS_TOKEN);
TestConstant.REFRESH_TOKEN = response.getHeader(HeaderParameter.REFRESH_TOKEN);
Expand All @@ -168,28 +178,37 @@ public void testUpdateUserValid() throws Exception {
public void testUpdateUserInvalid() throws Exception {
String otherID = "123";
mvc.perform(
post(ApiPathConstant.USER_UPDATE_USER_API_PATH)
.header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN)
.header(HeaderParameter.REFRESH_TOKEN, TestConstant.REFRESH_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"id": "%s",
"username": "%s",
"email": "%s",
"userPassword": "%s"
}
""".formatted(otherID, TestConstant.USERNAME, TestConstant.EMAIL, TestConstant.USER_PASSWORD)))
.andExpectAll(
status().isForbidden(),
content()
.json(
"""
{
"code": %d,
"message": "%s"
}
""".formatted(ErrorCodeEnum.ACCESS_DENIED.ordinal(), MessageSourceUtil.getMessage(ErrorCodeEnum.ACCESS_DENIED))));
post(ApiPathConstant.USER_UPDATE_USER_API_PATH)
.header(HeaderParameter.ACCESS_TOKEN, TestConstant.ACCESS_TOKEN)
.header(HeaderParameter.REFRESH_TOKEN, TestConstant.REFRESH_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"id": "%s",
"username": "%s",
"email": "%s",
"userPassword": "%s"
}
"""
.formatted(
otherID,
TestConstant.USERNAME,
TestConstant.EMAIL,
TestConstant.USER_PASSWORD)))
.andExpectAll(
status().isForbidden(),
content()
.json(
"""
{
"code": %d,
"message": "%s"
}
"""
.formatted(
ErrorCodeEnum.ACCESS_DENIED.ordinal(),
MessageSourceUtil.getMessage(
ErrorCodeEnum.ACCESS_DENIED))));
}
}

0 comments on commit d6c3632

Please sign in to comment.