Search in sources :

Example 1 with RestfulResult

use of cn.opencil.vo.RestfulResult in project CILManagement-Server by LiuinStein.

the class UserController method initPassword.

/**
 * For admin to initialize someone's password
 * The default password for everyone is 666666
 */
@RequestMapping(value = "/password/", method = RequestMethod.PATCH, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseStatus(HttpStatus.CREATED)
public RestfulResult initPassword(@RequestBody JSONObject input) throws SimpleHttpException, ValidationException {
    RBACUser user = input.toJavaObject(RBACUser.class);
    user.setPassword("666666");
    if (!userService.changeUserPassword(ValidationUtils.validate(user))) {
        throw new SimpleHttpException(500, "database access error", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new RestfulResult(0, "Password has been initialized!", new HashMap<>());
}
Also used : RBACUser(cn.opencil.po.RBACUser) SimpleHttpException(cn.opencil.exception.SimpleHttpException) RestfulResult(cn.opencil.vo.RestfulResult)

Example 2 with RestfulResult

use of cn.opencil.vo.RestfulResult in project CILManagement-Server by LiuinStein.

the class UserController method modifyPassword.

/**
 * Modify your own password
 */
@RequestMapping(value = "/password/", method = RequestMethod.PUT, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseStatus(HttpStatus.CREATED)
public RestfulResult modifyPassword(@RequestBody JSONObject input, HttpServletRequest request) throws SimpleHttpException, ValidationException {
    String oldPassword = input.getString("old_password");
    RBACUser userDetails = (RBACUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (oldPassword == null || !passwordEncoder.matches(oldPassword, userDetails.getPassword())) {
        throw new SimpleHttpException(403, "Old password error", HttpStatus.FORBIDDEN);
    }
    userDetails.setPassword(input.getString("new_password"));
    if (!userService.changeUserPassword(ValidationUtils.validate(userDetails))) {
        throw new SimpleHttpException(500, "database access error", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    // must re-login after password changing, otherwise, replay attacks maybe occurred
    new SecurityContextLogoutHandler().logout(request, null, SecurityContextHolder.getContext().getAuthentication());
    return new RestfulResult(0, "Password has been changed!", new HashMap<>());
}
Also used : SecurityContextLogoutHandler(org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler) RBACUser(cn.opencil.po.RBACUser) SimpleHttpException(cn.opencil.exception.SimpleHttpException) RestfulResult(cn.opencil.vo.RestfulResult)

Example 3 with RestfulResult

use of cn.opencil.vo.RestfulResult in project CILManagement-Server by LiuinStein.

the class UserController method modifyInfo.

/**
 * Modify someone's personal information
 */
@RequestMapping(value = "/info/", method = RequestMethod.PUT, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseStatus(HttpStatus.CREATED)
public RestfulResult modifyInfo(@RequestBody JSONObject input) throws ValidationException, SimpleHttpException {
    UserInfo info = ValidationUtils.validate(input.toJavaObject(UserInfo.class));
    RBACUser userDetails = (RBACUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if ((info.getEnrollTime() != null || info.getExitTime() != null) && !userDetails.getAuthorities().toString().equals("[admin]")) {
        // Only administers can modify the value of enroll_time&exit_time fields. If others submit that, it would be ignored.
        info.setEnrollTime(null);
        info.setExitTime(null);
    }
    if (!info.getId().equals(userDetails.getId()) && !userDetails.getAuthorities().toString().equals("[admin]")) {
        throw new SimpleHttpException(403, "need administer privilege", HttpStatus.FORBIDDEN);
    }
    if (!infoService.modifyUserInfo(info)) {
        throw new SimpleHttpException(500, "database access error", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new RestfulResult(0, "information has been changed!", new HashMap<>());
}
Also used : RBACUser(cn.opencil.po.RBACUser) SimpleHttpException(cn.opencil.exception.SimpleHttpException) RestfulResult(cn.opencil.vo.RestfulResult) UserInfo(cn.opencil.po.UserInfo)

Example 4 with RestfulResult

use of cn.opencil.vo.RestfulResult in project CILManagement-Server by LiuinStein.

the class GlobalExceptionResolver method resolveException.

/**
 * Resolve the exception form controller
 *
 * @param request   http request
 * @param response  http response
 * @param o         the executed handler, or null if none chosen at the time of the exception (for example, if multipart resolution failed)
 * @param exception the exception that threw from controller
 * @return a new ModelAndView
 * @implNote https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerExceptionResolver.html
 */
@NotNull
@Override
public ModelAndView resolveException(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @Nullable Object o, @NotNull Exception exception) {
    RestfulResult result = new RestfulResult(1, exception.getMessage(), new HashMap<>());
    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    if (exception instanceof SimpleException) {
        result.setCode(((SimpleException) exception).getCode());
    }
    if (exception instanceof SimpleHttpException) {
        response.setStatus(((SimpleHttpException) exception).getHttpStatusToReturn().value());
    }
    if (exception instanceof HttpRequestMethodNotSupportedException) {
        result.setCode(405);
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
    }
    if (exception instanceof ValidationException || exception instanceof ServletRequestBindingException || exception instanceof IllegalArgumentException) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
    }
    if (exception instanceof DataAccessException) {
        result.setMessage("database access error");
    }
    try {
        if ("application/xml".equals(request.getHeader("Accept"))) {
            response.setHeader("Content-Type", "application/xml;charset=UTF-8");
            response.getWriter().print(result.toXmlString());
        } else {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().print(result.toJsonString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new ModelAndView();
}
Also used : ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) ValidationException(com.shaoqunliu.validation.ValidationException) RestfulResult(cn.opencil.vo.RestfulResult) ModelAndView(org.springframework.web.servlet.ModelAndView) IOException(java.io.IOException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) DataAccessException(org.springframework.dao.DataAccessException) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with RestfulResult

use of cn.opencil.vo.RestfulResult in project CILManagement-Server by LiuinStein.

the class MyAuthenticationFailureHandle method onAuthenticationFailure.

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    RestfulResult result = new RestfulResult(1, e.getMessage(), new HashMap<>());
    SecurityRestfulResponsePrinter responseHandle = new SecurityRestfulResponsePrinter();
    responseHandle.print(request, response, result);
    if (e instanceof UsernameNotFoundException) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) RestfulResult(cn.opencil.vo.RestfulResult)

Aggregations

RestfulResult (cn.opencil.vo.RestfulResult)9 SimpleHttpException (cn.opencil.exception.SimpleHttpException)5 RBACUser (cn.opencil.po.RBACUser)4 UserInfo (cn.opencil.po.UserInfo)3 HashMap (java.util.HashMap)2 RBACUserRole (cn.opencil.po.RBACUserRole)1 JSONObject (com.alibaba.fastjson.JSONObject)1 ValidationException (com.shaoqunliu.validation.ValidationException)1 IOException (java.io.IOException)1 NotNull (org.jetbrains.annotations.NotNull)1 DataAccessException (org.springframework.dao.DataAccessException)1 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)1 SecurityContextLogoutHandler (org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler)1 HttpRequestMethodNotSupportedException (org.springframework.web.HttpRequestMethodNotSupportedException)1 ServletRequestBindingException (org.springframework.web.bind.ServletRequestBindingException)1 ModelAndView (org.springframework.web.servlet.ModelAndView)1