Skip to content

Commit

Permalink
wrapper response
Browse files Browse the repository at this point in the history
  • Loading branch information
blackstar-baba committed Aug 8, 2020
1 parent 67000d2 commit 13b2e94
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 84 deletions.
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
package com.blackstar.softwarelab.exception;
package com.blackstar.softwarelab.bean;

import com.fasterxml.jackson.annotation.JsonValue;

public enum ErrorCode {
public enum Code {

SUCCESS(-1),
GENERAL(2),
AUTHENTICATION(10),
JWT_TOKEN_EXPIRED(11),
PERMISSION_DENIED(20),
INVALID_ARGUMENTS(30),
BAD_REQUEST_PARAMS(31);

private int errorCode;
private int code;

ErrorCode(int errorCode) {
this.errorCode = errorCode;
Code(int code) {
this.code = code;
}

@JsonValue
public int getErrorCode() {
return errorCode;
public int getCode() {
return code;
}

}
60 changes: 60 additions & 0 deletions src/main/java/com/blackstar/softwarelab/bean/Response.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.blackstar.softwarelab.bean;

import org.springframework.http.HttpStatus;

import java.util.Date;

public class Response {

// General message
private final String message;

// code
private final Code code;

private final Object data;

private final Date timestamp;

protected Response(final String message, final Code code) {
this.message = message;
this.code = code;
this.timestamp = new java.util.Date();
this.data = null;
}

protected Response(final String message, final Code code, Object data) {
this.message = message;
this.code = code;
this.timestamp = new java.util.Date();
this.data = data;
}

public static Response of(final String message, final Code code) {
return new Response(message, code);
}

public static Response of(final String message, final Code code, Object data) {
return new Response(message, code, data);
}

public static Response ofSuccess(Object data){
return new Response(null, Code.SUCCESS, data);
}

public String getMessage() {
return message;
}

public Code getCode() {
return code;
}

public Date getTimestamp() {
return timestamp;
}

public Object getData() {
return data;
}
}
37 changes: 18 additions & 19 deletions src/main/java/com/blackstar/softwarelab/common/BaseController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package com.blackstar.softwarelab.common;

import com.blackstar.softwarelab.exception.ErrorCode;
import com.blackstar.softwarelab.exception.ErrorResponse;
import com.blackstar.softwarelab.bean.Code;
import com.blackstar.softwarelab.bean.Response;
import com.blackstar.softwarelab.bean.SecurityUser;
import com.blackstar.softwarelab.entity.SysUser;
import com.blackstar.softwarelab.service.ISysUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

Expand All @@ -20,20 +18,11 @@
public abstract class BaseController {


@Autowired
private ISysUserService userService;

private ObjectMapper objectMapper = new ObjectMapper();

public SecurityUser getSecurityUser() {

SysUser user = userService.getById("205635b9-ab37-43cb-82c2-811a58880fa1");

return SecurityUser.builder()
.id(user.getId())
.mail(user.getMail())
.username(user.getUsername())
.build();
return getCurrentUser();
}


Expand All @@ -42,10 +31,20 @@ public void handleRuntimeException(RuntimeException ex, HttpServletResponse resp
log.error(ex.getMessage());
try {
objectMapper.writeValue(response.getWriter(),
ErrorResponse.of(ex.getMessage(),
ErrorCode.GENERAL, HttpStatus.INTERNAL_SERVER_ERROR));
Response.of(ex.getMessage(),
Code.GENERAL, null));
} catch (IOException e) {
log.error("Can't handle exception",e);
log.error("Can't handle exception", e);
}
}

protected SecurityUser getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof SecurityUser) {
return (SecurityUser) authentication.getPrincipal();
} else {
return null;
// throw new Exception("您无权进行此操作!", Code.AUTHENTICATION);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import com.blackstar.softwarelab.config.jwt.extractor.TokenExtractor;
import com.blackstar.softwarelab.config.rest.RestAuthenticationProvider;
import com.blackstar.softwarelab.config.rest.RestLoginProcessingFilter;
import com.blackstar.softwarelab.exception.ErrorResponseHandler;
import com.blackstar.softwarelab.handler.ErrorResponseHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -41,7 +41,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";

public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";
protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/index.html", "/static/**", "/api/noauth/**", "/webjars/**", "/api/whiteLabel/**"};
protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/api/files/**","/index.html", "/static/**", "/api/noauth/**", "/webjars/**", "/api/whiteLabel/**"};
public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
public static final String WS_TOKEN_BASED_AUTH_ENTRY_POINT = "/api/ws/**";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ private Authentication authenticateByUsernameAndPassword(String username, String
if (sysUser == null) {
throw new UsernameNotFoundException("user not found: " + username);
}

if (!encoder.matches(password, sysUser.getPassword())) {
throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.blackstar.softwarelab.config.rest;

import com.blackstar.softwarelab.exception.ErrorResponseHandler;
import com.blackstar.softwarelab.handler.ErrorResponseHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.blackstar.softwarelab.config.rest;

import com.blackstar.softwarelab.bean.Response;
import com.blackstar.softwarelab.bean.SecurityUser;
import com.blackstar.softwarelab.config.jwt.JwtToken;
import com.blackstar.softwarelab.config.jwt.JwtTokenFactory;
Expand Down Expand Up @@ -48,7 +49,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(response.getWriter(), tokenMap);
// mapper.writeValue(response.getWriter(), tokenMap);
mapper.writeValue(response.getWriter(), Response.ofSuccess(tokenMap));

clearAuthenticationAttributes(request);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class FileController extends BaseController {
@Autowired
private IFileService fileService;

@RequestMapping(value = "/logos/{app}")
@RequestMapping(value = "/logo/{app}")
public void getLogo(@PathVariable("app") String app, HttpServletResponse response) {
fileService.writeAppLogoToResponse(app, response);
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blackstar.softwarelab.exception;
package com.blackstar.softwarelab.handler;

import com.blackstar.softwarelab.bean.Code;
import com.blackstar.softwarelab.bean.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -46,8 +48,8 @@ public void handle(HttpServletRequest request, HttpServletResponse response,
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.FORBIDDEN.value());
mapper.writeValue(response.getWriter(),
ErrorResponse.of("You don't have permission to perform this operation!",
ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN));
Response.of("You don't have permission to perform this operation!",
Code.PERMISSION_DENIED, null));
}
}

Expand All @@ -60,8 +62,8 @@ public void handle(Exception exception, HttpServletResponse response) {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);

response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
mapper.writeValue(response.getWriter(), ErrorResponse.of(exception.getMessage(),
ErrorCode.GENERAL, HttpStatus.INTERNAL_SERVER_ERROR));
mapper.writeValue(response.getWriter(), Response.of(exception.getMessage(),
Code.GENERAL, null));
} catch (IOException e) {
log.error("Can't handle exception", e);
}
Expand Down
3 changes: 1 addition & 2 deletions src/main/resources/db/data.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
--table user
INSERT INTO sys_user (id, username, password, mail, create_time, update_time, status)
VALUES ('00000000-0000-0000-0000-000000000000', 'admin', null, null, null, null, null);

VALUES ('00000000-0000-0000-0000-000000000000', 'admin', '$2a$10$vFOaYBYNk3tkFOrZ2y5NMerpt2SuXZeshfOHiKvyEh4PSI9EseWzC', null, null, null, null);

--table app source
INSERT INTO app_source (id, version, repository)
Expand Down

0 comments on commit 13b2e94

Please sign in to comment.