Example usage for org.springframework.http HttpStatus FORBIDDEN

List of usage examples for org.springframework.http HttpStatus FORBIDDEN

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FORBIDDEN.

Prototype

HttpStatus FORBIDDEN

To view the source code for org.springframework.http HttpStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden .

Usage

From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java

/**
 * Uploads a p2-repository to the solution and updates the solution data
 * Returns a <b>403 Forbidden</b> if the logged in user is not the owner of
 * the solution.//from w ww.java 2 s . c  o  m
 *
 * The URL to the update site will be overwritten with a new value pointing
 * to this server.
 */
@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload-p2repo")
public ResponseEntity<String> uploadRepository(Principal principal, @RequestParam("id") Long id,
        @RequestParam("file") MultipartFile file) throws Exception {
    // verify that we have the correct owner
    Account account = accountRepository.findOne(principal.getName());
    Account a = accountRepository.findAccountBySolutionId(id);
    if (!account.getUsername().equals(a.getUsername())) {
        return new ResponseEntity<String>("Logged in user is not the owner of the solution",
                HttpStatus.FORBIDDEN);
    }
    fileService.uploadRepository(id, file);
    // get solution and update with new information
    Node node = marketplaceDAO.getSolution(id);
    node.setUpdateurl("/files/" + id + "/");
    Object result = marketplaceDAO.saveOrUpdateSolution(node, account);
    if (result instanceof Node) {
        return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK);
    } else {
        return new ResponseEntity<String>((String) result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:de.sainth.recipe.backend.rest.controller.UserController.java

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
HttpEntity<User> update(@PathVariable("id") Long id, @Valid @RequestBody User user) {
    if (id.equals(user.getId())) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
        if (ROLE_ADMIN.name().equals(token.getRole())
                || (ROLE_USER.name().equals(token.getRole()) && token.getPrincipal().equals(id))) {
            if (repository.findOne(user.getId()) != null) {
                repository.save(user);//  w  w w . j a  v  a 2  s. c o  m
                return new ResponseEntity<>(user, HttpStatus.OK);
            }
        } else {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

From source file:org.mitre.openid.connect.web.ApprovedSiteAPI.java

/**
 * Get a single approved site//from ww w  . j  av  a2  s.  c o  m
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getApprovedSite(@PathVariable("id") Long id, ModelMap m, Principal p) {
    ApprovedSite approvedSite = approvedSiteService.getById(id);
    if (approvedSite == null) {
        logger.error("getApprovedSite failed; no approved site found for id: " + id);
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE,
                "The requested approved site with id: " + id + " could not be found.");
        return JsonErrorView.VIEWNAME;
    } else if (!approvedSite.getUserId().equals(p.getName())) {
        logger.error("getApprovedSite failed; principal " + p.getName() + " does not own approved site" + id);
        m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        m.put(JsonErrorView.ERROR_MESSAGE, "You do not have permission to view this approved site.");
        return JsonErrorView.VIEWNAME;
    } else {
        m.put(JsonEntityView.ENTITY, approvedSite);
        return JsonApprovedSiteView.VIEWNAME;
    }

}

From source file:org.cloudfoundry.identity.uaa.integration.TokenAdminEndpointsIntegrationTests.java

@Test
@OAuth2ContextConfiguration(resource = TokenResourceOwnerPassword.class)
public void testCannotListTokensOfAnotherUser() throws Exception {

    assertEquals(HttpStatus.FORBIDDEN, serverRunning.getForString("/oauth/users/foo/tokens").getStatusCode());
}

From source file:org.craftercms.profile.services.AuthenticationServiceIT.java

@Test
@DirtiesContext/*  w ww .  j  av a  2s . c  om*/
public void testExpiredAccessTokenError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(EXPIRED_ACCESS_TOKEN_ID);

    try {
        authenticationService.authenticate(DEFAULT_TENANT_NAME, ADMIN_USERNAME, ADMIN_PASSWORD);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.EXPIRED_ACCESS_TOKEN, e.getErrorCode());
    }
}

From source file:org.mitre.oauth2.web.TokenAPI.java

@RequestMapping(value = "/access/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public String deleteAccessTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2AccessTokenEntity token = tokenService.getAccessTokenById(id);

    if (token == null) {
        logger.error("getToken failed; token not found: " + id);
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE, "The requested token with id " + id + " could not be found.");
        return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
        logger.error("getToken failed; token does not belong to principal " + p.getName());
        m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        m.put(JsonErrorView.ERROR_MESSAGE, "You do not have permission to view this token");
        return JsonErrorView.VIEWNAME;
    } else {// www  . jav  a2 s .  co m
        tokenService.revokeAccessToken(token);

        return HttpCodeView.VIEWNAME;
    }
}

From source file:net.cpollet.shoppist.web.controller.TokenController.java

@ExceptionHandler({ InvalidTokenException.class })
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ResponseBody//from  w  ww.  ja va  2 s . c  om
public RestResponse tokenError(HttpServletRequest request, Exception exception) {
    logger.error("InvalidToken", exception);
    return RestResponseBuilder.aRestResponse() //
            .withHttpStatus(HttpStatus.FORBIDDEN.value()) //
            .withErrorStatus(MESSAGE_INVALID_TOKEN) //
            .withErrorDescription(exception.getMessage()) //
            .build();
}

From source file:de.steilerdev.myVerein.server.controller.admin.DivisionManagementController.java

/**
 * This function is saving changes on an exisiting division. If the division needs to be created see {@link DivisionManagementController#createDivision}. This function is invoked by POSTing the parameters to the URI /api/admin/division.
 * @param name The new name of the division.
 * @param oldName The old name of the division (might be equal to new name)
 * @param description The description of the division (may be empty)
 * @param admin The name of the administrating user (may be empty)
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*w w w . ja  va  2s .  c  om*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveDivision(@RequestParam String name, @RequestParam String oldName,
        @RequestParam String description, @RequestParam String admin, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "]  Saving division");
    //String successMessage = "Successfully saved division";
    if (currentUser.isAdmin()) {
        Division division;
        Division oldDivision = null;

        if (oldName.isEmpty()) {
            logger.warn("[" + currentUser + "]  The original name of the division is missing");
            return new ResponseEntity<>("The original name of the division is missing", HttpStatus.BAD_REQUEST);
        } else if (oldName.equals(name) && (division = divisionRepository.findByName(oldName)) != null) {
            //A division is changed, name stays.
            logger.debug("[" + currentUser + "]  An existing division is changed (" + oldName
                    + "). The name is unchanged.");
        } else if ((oldDivision = division = divisionRepository.findByName(oldName)) != null
                && divisionRepository.findByName(name) == null) {
            //An existing divisions name is changed and the name is unique
            logger.debug("[" + currentUser
                    + "]  An existing division is changed (including its name). The name changed from "
                    + oldName + " to " + name);
        } else if (division.getParent() == null) {
            logger.debug(
                    "[" + currentUser + "]  The root division is not allowed to be modified through this API");
            return new ResponseEntity<>("The root division is not allowed to be modified through this API",
                    HttpStatus.FORBIDDEN);
        } else {
            logger.warn("[" + currentUser + "]  Problem finding existing division (" + oldName
                    + "), either the existing division could not be located or the new name is already taken");
            return new ResponseEntity<>(
                    "Problem finding existing division, either the existing division could not be located or the new name is already taken",
                    HttpStatus.BAD_REQUEST);
        }

        if (currentUser.isAllowedToAdministrate(division, divisionRepository)) //Check if user is allowed to change the division (if he administrates one of the parent divisions)
        {
            User adminUser = null;
            if (admin != null && !admin.isEmpty()) {
                adminUser = userRepository.findByEmail(admin);
                if (adminUser == null) {
                    logger.warn("[" + currentUser + "]  Unable to find specified admin user: " + admin);
                    return new ResponseEntity<>("Unable to find specified admin user.", HttpStatus.BAD_REQUEST);
                }
            } else {
                logger.warn("[" + currentUser + "]  No admin stated for division " + division.getName());
            }
            division.setAdminUser(adminUser);
            division.setName(name);
            division.setDesc(description);

            try {
                if (oldDivision != null) {
                    logger.debug("[" + currentUser + "]  Deleting old division " + oldDivision.getName());
                    divisionRepository.delete(oldDivision);
                }
                divisionRepository.save(division);
                logger.info("[" + currentUser + "]  Successfully saved division " + division.getName());
                return new ResponseEntity<>("Successfully saved division", HttpStatus.OK);
            } catch (ConstraintViolationException e) {
                logger.warn("[" + currentUser
                        + "]  A database constraint was violated while saving the division: " + e.getMessage());
                return new ResponseEntity<>("A database constraint was violated while saving the division.",
                        HttpStatus.BAD_REQUEST);
            }
        } else {
            logger.warn("[" + currentUser + "]  The user is not allowed to change the division ("
                    + division.getName() + ")");
            return new ResponseEntity<>("You are not allowed to change this division.", HttpStatus.FORBIDDEN);
        }
    } else {
        logger.warn("[" + currentUser + "]  The user not allowed to create a new division.");
        return new ResponseEntity<>("You are not allowed to create a new division", HttpStatus.FORBIDDEN);
    }
}

From source file:org.lanqiao.examples.library.functional.BookEndpointTest.java

@Test
public void applyRequestWithError() {
    // token/*from w  w  w . j  av a  2s  . c  o m*/
    ResponseEntity<String> response = restTemplate.getForEntity(resourceUrl + "/{id}/request", String.class,
            1L);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    ErrorResult errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.NO_TOKEN.code);

    BookDto book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    // token
    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, "abc");
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.UNAUTHORIZED.code);

    book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    // 
    String token = login("calvin.xiao@springside.io");

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_OWNERSHIP_WRONG.code);

    book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    logout(token);

    // 
    token = login("calvin.xiao@springside.io");

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_STATUS_WRONG.code);

    // ?
    response = restTemplate.getForEntity(resourceUrl + "/{id}/cancel?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

    logout(token);
}

From source file:org.craftercms.profile.services.TenantServiceIT.java

@Test
@DirtiesContext/*from   w  w  w  . j a  v a2 s.  co  m*/
public void testExpiredAccessTokenError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(EXPIRED_ACCESS_TOKEN_ID);

    try {
        tenantService.createTenant(getCorporateTenant());
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.EXPIRED_ACCESS_TOKEN, e.getErrorCode());
    }
}