下面列出了org.springframework.http.HttpStatus#FORBIDDEN 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(
value = "/component/{id}",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<QueryResult> queryComponent(
@PathVariable("id") long componentId,
@RequestBody List<FilterParameter> filterParams,
HttpServletRequest request
) {
Component component = componentDao.findById(componentId);
if (component.getJdbcDataSourceId() == 0) {
return new ResponseEntity(QueryResult.ofError(Constants.ERROR_NO_DATA_SOURCE_FOUND), HttpStatus.OK);
}
boolean isAccessValid = isComponentAccessValid(component, request);
if (isAccessValid) {
String sql = component.getSqlQuery();
DataSource dataSource = jdbcDataSourceService.getDataSource(component.getJdbcDataSourceId());
User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
List<FilterParameter> newFilterParams = addUserAttributesToFilterParams(user.getUserAttributes(), filterParams);
QueryResult queryResult = jdbcQueryService.queryByParams(dataSource, sql, newFilterParams, Constants.QUERY_RESULT_NOLIMIT);
return new ResponseEntity(queryResult, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
public BookingResult updateBooking(int bookingId, Booking bookingToUpdate, String token) throws SQLException {
if(authRequests.postCheckAuth(token)){
if(dateCheckValidator.isValid(bookingToUpdate.getBookingDates())) {
if (bookingDB.checkForBookingConflict(bookingToUpdate)) {
return new BookingResult(HttpStatus.CONFLICT);
} else {
CreatedBooking updatedBooking = bookingDB.update(bookingId, bookingToUpdate);
if(updatedBooking != null){
return new BookingResult(updatedBooking, HttpStatus.OK);
} else {
return new BookingResult(HttpStatus.NOT_FOUND);
}
}
} else {
return new BookingResult(HttpStatus.CONFLICT);
}
} else {
return new BookingResult(HttpStatus.FORBIDDEN);
}
}
/**
* Converts the given exception to the most suiting HTTP response status.
*
* @return one of HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN,
* HttpStatus.BAD_REQUEST, HttpStatus.INTERNAL_SERVER_ERROR
* @param exc
* the exception to be converted
*/
HttpStatus exceptionToStatus(final Exception exc) {
if (exc instanceof BankService.ClientNotFoundExc) {
return HttpStatus.NOT_FOUND;
}
if (exc instanceof Client.NotManagedAccountExc) {
return HttpStatus.NOT_FOUND;
}
if (exc instanceof Client.NotOwnerExc) {
return HttpStatus.FORBIDDEN;
}
if (exc instanceof Client.WithoutRightExc) {
return HttpStatus.FORBIDDEN;
}
final String excClassName = exc.getClass().getName();
if (excClassName.startsWith(restInterfacePackagePrefix) || excClassName.startsWith(domainPackagePrefix)) {
return HttpStatus.BAD_REQUEST;
}
return HttpStatus.INTERNAL_SERVER_ERROR;
}
@ResponseBody
@RequestMapping("/error")
public String error(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = super.getStatus(request);
if (status == HttpStatus.NOT_FOUND) {
return "wrong";
}
if (status == HttpStatus.FORBIDDEN || status == HttpStatus.UNAUTHORIZED) {
AuthenticatUtil.needAuthenticate(response);
return "";
}
return "wrong";
}
public List<Illustration> queryCollectionIllust(Integer collectionId, Integer page, Integer pageSize) {
//校验画集是否公开 画集isPublic 或者user是本人
Collection collection = queryCollectionById(collectionId);
if (collection == null) {
throw new BusinessException(HttpStatus.NOT_FOUND, "未找到该画集");
}
if (collection.getIsPublic() == 0) {
Map<String, Object> context = AppContext.get();
if (context != null && context.get(AuthConstant.USER_ID) != null) {
if (context.get(AuthConstant.USER_ID) != collection.getUserId()) {
throw new BusinessException(HttpStatus.FORBIDDEN, "无权限访问");
}
}
}
List<Integer> illustIdList = collectionMapper.queryCollectionIllustIdList(collectionId, (page - 1) * pageSize, pageSize);
return illustrationBizService.queryIllustrationByIllustIdList(illustIdList);
}
@RequestMapping(value = "{grouping}/studentsToEnroll")
public @ResponseBody ResponseEntity<String> getStudentsToEnroll(@PathVariable Grouping grouping) {
if (!personInGroupingAttends(grouping, AccessControl.getPerson())) {
// throw new DomainException("error.grouping.notEnroled");
return new ResponseEntity<>(
createErrorJson((new DomainException("error.grouping.notEnroled")).getLocalizedMessage()),
HttpStatus.FORBIDDEN);
}
if (!groupingIsOpenForEnrollment(grouping)) {
// throw new DomainException("error.grouping.notOpenToEnrollment");
return new ResponseEntity<>(
createErrorJson((new DomainException("error.studentGroupShift.notOpen")).getLocalizedMessage()),
HttpStatus.FORBIDDEN);
}
return new ResponseEntity<>(view(grouping
.getAttendsSet()
.stream()
.filter(attends -> grouping.getStudentGroupsSet().stream()
.noneMatch(sg -> sg.getAttendsSet().stream().anyMatch(at -> at.equals(attends))))
.map(Attends::getRegistration).map(Registration::getPerson).collect(Collectors.toList())).toString(), HttpStatus.OK);
}
@ExceptionHandler({ AccessDeniedException.class })
public ResponseEntity<Object> handleAccessDeniedException(HttpClientErrorException ex, WebRequest request) {
final String error = "Digits access authorization failed" ;
final ApiError apiError = new ApiError(HttpStatus.FORBIDDEN, ex.getLocalizedMessage(), error);
return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.FORBIDDEN);
}
public RoomResult updateRoom(int roomId, Room roomToUpdate, String token) throws SQLException {
if(authRequests.postCheckAuth(token)){
Room updatedRoom = roomDB.update(roomId, roomToUpdate);
if(updatedRoom != null){
return new RoomResult(HttpStatus.ACCEPTED, updatedRoom);
} else {
return new RoomResult(HttpStatus.NOT_FOUND);
}
} else {
return new RoomResult(HttpStatus.FORBIDDEN);
}
}
/**
* DELETE /blood-pressures/:id : delete the "id" bloodPressure.
*
* @param id the id of the bloodPressure to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/blood-pressures/{id}")
@Timed
public ResponseEntity<?> deleteBloodPressure(@PathVariable Long id) {
log.debug("REST request to delete BloodPressure : {}", id);
Optional<BloodPressure> bloodPressure = bloodPressureRepository.findById(id);
if (bloodPressure.isPresent() && bloodPressure.get().getUser() != null &&
!bloodPressure.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
bloodPressureRepository.deleteById(id);
bloodPressureSearchRepository.deleteById(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
logger.warn("TDS Error", ex);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
String mess = ex.getMessage();
if (mess != null && mess.startsWith("RequestTooLarge")) // RequestTooLargeException only avail in tds module
return new ResponseEntity<>("Request Too Large: " + htmlEscape(mess), responseHeaders, HttpStatus.FORBIDDEN);
else
return new ResponseEntity<>("IllegalArgumentException: " + htmlEscape(mess), responseHeaders,
HttpStatus.BAD_REQUEST);
}
/**
* AccessDeniedException异常处理返回json
* 状态码:403
* @param exception
* @return
*/
@ExceptionHandler({ AccessDeniedException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public Map<String, Object> badMethodExpressException(AccessDeniedException exception) {
Map<String, Object> data = new HashMap<>();
data.put("resp_code", HttpStatus.FORBIDDEN.value());
data.put("resp_msg", exception.getMessage());
return data;
}
@ExceptionHandler(value = EntandoAuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorRestResponse processEntandoAuthorizationException(EntandoAuthorizationException ex) {
logger.debug("Handling {} error", ex.getClass().getSimpleName());
RestError error = new RestError(RestErrorCodes.UNAUTHORIZED, this.resolveLocalizedErrorMessage("UNAUTHORIZED", new Object[]{ex.getUsername(), ex.getRequestURI(), ex.getMethod()}));
return new ErrorRestResponse(error);
}
@RequestMapping(value = "/deleteDepartment", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> deleteDepartment(@RequestBody String departmentJson) {
try {
departmentService.deleteDepartment(createDepartmentBeanFromJSON(departmentJson));
return new ResponseEntity<String>(HttpStatus.OK);
} catch (DomainException dme) {
return new ResponseEntity<String>(createErrorJson(dme.getLocalizedMessage()), HttpStatus.FORBIDDEN);
}
}
@ExceptionHandler(AuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public Response<Void> handleException(AuthorizationException e) {
log.error("权限验证未通过 {}",e.getMessage());
shiroEventListener.afterLogin(currentUserName.get(),false,e.getMessage());
ShiroExceptionHandler.remove();
return new Response<>(HttpStatus.FORBIDDEN.value() + "", "当前用户无权限访问", null);
}
Forbidden(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
super(HttpStatus.FORBIDDEN, statusText, headers, body, charset);
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorVM processAccessDeniedException(AccessDeniedException e) {
return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully sent the email"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found"),
@ApiResponse(code = 417, message = "Expectation Failed"),
@ApiResponse(code = 408, message = "operation timed out")
}
)
@ApiOperation(value = "Send a Text Email", response = ResponseEntity.class)
@RequestMapping(value = "/send-plain-text-mail", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> sendTextMail(@ApiParam(value = "Provide Mail Message Request Body", required = true) final @RequestBody MailMessageRequestBody mailMessageRequestBody) {
try {
log.info("fromAddress==sendMailWithTemplate from config {}",fromAddress);
log.info("mailTemplateRequestBody.getFrom()===sendMailWithTemplate from param {}",mailMessageRequestBody.getFrom());
mailService.prepareAndSendMail("",mailMessageRequestBody.getFrom(),
mailMessageRequestBody.getTo(),
mailMessageRequestBody.getSubject(),
mailMessageRequestBody.getMailBodyAsString(),
mailMessageRequestBody.getPlaceholderValues(), mailMessageRequestBody.getAttachmentUrl(), true);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception exception) {
log.error(EXE_EMAIL_SEND, exception);
try {
log.info("fromAddress==sendMailWithTemplate from catch block from config {}",fromAddress);
log.info("mailTemplateRequestBody.getFrom() from catch block===sendMailWithTemplate from param {}",mailMessageRequestBody.getFrom());
mailService.prepareAndSendMail(mailMessageRequestBody.getFrom(),fromAddress,
mailMessageRequestBody.getTo(),
mailMessageRequestBody.getSubject(),
mailMessageRequestBody.getMailBodyAsString(),
mailMessageRequestBody.getPlaceholderValues(), mailMessageRequestBody.getAttachmentUrl(), true);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
log.error(EXE_EMAIL_SEND, e);
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) {
return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}
/**
* 1. cas 服务端会通过post请求,并且把用户信息以"用户名:密码"进行Base64编码放在authorization请求头中
* 2. 返回200状态码并且格式为{"@class":"org.apereo.cas.authentication.principal.SimplePrincipal","id":"casuser","attributes":{}} 是成功的
* 2. 返回状态码403用户不可用;404账号不存在;423账户被锁定;428过期;其他登录失败
*
* @param httpHeaders
* @return
*/
@PostMapping("/login")
public Object login(@RequestHeader HttpHeaders httpHeaders) {
LOGGER.info("Rest api login.");
LOGGER.debug("request headers: {}", httpHeaders);
SysUser user = null;
try {
UserTemp userTemp = obtainUserFormHeader(httpHeaders);
//尝试查找用户库是否存在
user = new SysUser();
user.setUsername("anumbrella");
user.setPassword("123");
if (user != null) {
if (!user.getPassword().equals(userTemp.password)) {
//密码不匹配
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
if (user.isDisable()) {
//禁用 403
return new ResponseEntity(HttpStatus.FORBIDDEN);
}
if (user.isLocked()) {
//锁定 423
return new ResponseEntity(HttpStatus.LOCKED);
}
if (user.isExpired()) {
//过期 428
return new ResponseEntity(HttpStatus.PRECONDITION_REQUIRED);
}
} else {
//不存在 404
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
} catch (UnsupportedEncodingException e) {
LOGGER.error("", e);
new ResponseEntity(HttpStatus.BAD_REQUEST);
}
LOGGER.info("[{}] login is ok", user.getUsername());
//成功返回json
return user;
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) {
return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}