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:com.ge.predix.web.cors.CORSFilter.java

void buildCorsXhrPreFlightResponse(final HttpServletRequest request, final HttpServletResponse response) {
    String accessControlRequestMethod = request.getHeader("Access-Control-Request-Method");
    if (null == accessControlRequestMethod) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;//w  w w  . j  a  va 2s .c o m
    }
    if (!"GET".equalsIgnoreCase(accessControlRequestMethod)) {
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Methods", "GET");

    String accessControlRequestHeaders = request.getHeader("Access-Control-Request-Headers");
    if (null == accessControlRequestHeaders) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }
    if (!headersAllowed(accessControlRequestHeaders)) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Headers", "Authorization, X-Requested-With");
    response.addHeader("Access-Control-Max-Age", this.maxAge);
}

From source file:com.chevres.rss.restapi.controller.UserController.java

@CrossOrigin
@RequestMapping(path = "/users", method = RequestMethod.GET)
@ResponseBody//from ww w. j  a v  a2s .  c  om
public ResponseEntity<String> getUsers(@RequestHeader(value = "User-token") String userToken) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    UserDAO userDAO = context.getBean(UserDAO.class);
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);

    UserAuth userAuth = userAuthDAO.findByToken(userToken);
    if (userAuth == null) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("invalid_token"), HttpStatus.BAD_REQUEST);
    }

    boolean isAdmin = userDAO.isAdmin(userAuth.getIdUser());
    if (!isAdmin) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("admin_required"), HttpStatus.FORBIDDEN);
    }

    List<User> users = userDAO.findEveryone();
    List<SuccessGetUserWithIdResponse> finalList = new ArrayList<>();
    for (User user : users) {
        finalList.add(new SuccessGetUserWithIdResponse(user.getId(), user.getUsername(), user.getType()));
    }

    context.close();

    return new ResponseEntity(new SuccessGetUsersResponse(finalList), HttpStatus.OK);
}

From source file:fi.hsl.parkandride.itest.RequestLogITest.java

@Test
public void report_RequestLog_unauthorized() {
    given().contentType(ContentType.JSON).accept(MEDIA_TYPE_EXCEL)
            .header(authorization(devHelper.login(apiUser.username).token)).body(new ReportParameters()).when()
            .post(UrlSchema.REPORT, REQUEST_LOG).then().assertThat().statusCode(HttpStatus.FORBIDDEN.value());
}

From source file:org.mitre.uma.web.PolicyAPI.java

/**
 * Create a new policy on the given resource set
 * @param rsid//  ww  w.  j ava2 s.c  om
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}"
        + POLICYURL, method = RequestMethod.POST, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String createNewPolicyForResourceSet(@PathVariable(value = "rsid") Long rsid,
        @RequestBody String jsonString, Model m, Authentication auth) {
    ResourceSet rs = resourceSetService.getById(rsid);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (!rs.getOwner().equals(auth.getName())) {
        logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got "
                + auth.getName());

        // authenticated user didn't match the owner of the resource set
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    Policy p = gson.fromJson(jsonString, Policy.class);

    if (p.getId() != null) {
        logger.warn("Tried to add a policy with a non-null ID: " + p.getId());
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    for (Claim claim : p.getClaimsRequired()) {
        if (claim.getId() != null) {
            logger.warn("Tried to add a policy with a non-null claim ID: " + claim.getId());
            m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
            return HttpCodeView.VIEWNAME;
        }
    }

    rs.getPolicies().add(p);
    ResourceSet saved = resourceSetService.update(rs, rs);

    // find the new policy object
    Collection<Policy> newPolicies = Sets.difference(new HashSet<>(saved.getPolicies()),
            new HashSet<>(rs.getPolicies()));

    if (newPolicies.size() == 1) {
        Policy newPolicy = newPolicies.iterator().next();
        m.addAttribute(JsonEntityView.ENTITY, newPolicy);
        return JsonEntityView.VIEWNAME;
    } else {
        logger.warn("Unexpected result trying to add a new policy object: " + newPolicies);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        return HttpCodeView.VIEWNAME;
    }

}

From source file:plbtw.klmpk.barang.hilang.controller.UserController.java

@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public CustomResponseMessage addUser(@RequestHeader String apiKey, @RequestBody UserRequest userRequest) {
    try {//  ww w . j a  v  a  2  s .  com
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        LogRequest temp = DependencyFactory.createLog(apiKey, "Post");

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);

        if (userService.checkUserExist(userRequest.getEmail()) != null) {
            return new CustomResponseMessage(HttpStatus.METHOD_NOT_ALLOWED, "Email Already Used");
        }

        User user = new User();
        user.setUsername(userRequest.getUsername());
        user.setEmail(userRequest.getEmail());
        user.setPassword(userRequest.getPassword());
        user.setAlamat(userRequest.getAlamat());
        user.setNoHp(userRequest.getNoHp());
        userService.addUser(user);
        return new CustomResponseMessage(HttpStatus.CREATED, "User Has Been Created");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

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

/**
 * Uploads a image to the solution and updates the solution data with
 * the name of the file being uploaded. Returns a <b>403 Forbidden</b> if
 * the logged in user is not the owner of the solution.
 *///from  ww  w .  j  ava 2 s.co  m
@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload-image")
public ResponseEntity<String> uploadImage(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());
    if (!canEdit(principal, id)) {
        return new ResponseEntity<String>("Logged in user is not the owner of the solution",
                HttpStatus.FORBIDDEN);
    }
    fileService.saveSolutionFile(id, file);
    // get solution and update with new information
    Node node = marketplaceDAO.getSolution(id);
    node.setImage(file.getOriginalFilename());
    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:org.cloudfoundry.identity.uaa.integration.PasswordChangeEndpointIntegrationTests.java

@Test
@OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.Implicit.class, initialize = false)
public void testUserChangesOthersPasswordFails() throws Exception {

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set("source", "credentials");
    parameters.set("username", joe.getUserName());
    parameters.set("password", "password");
    context.getAccessTokenRequest().putAll(parameters);

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("newpassword");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT, new HttpEntity<PasswordChangeRequest>(change, headers), null, bob.getId());
    assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());

}

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

/**
 * This function is saving the settings for the system durable. In case the database connection changed, the system is restarted. The function is invoked by POSTing the parameters to the URI /api/admin/settings.
 * NOTE: At the moment the restarting of the application is not working correctly. To apply changed database settings the application needs to be redeployed manually from the management interface.
 * @param currentAdmin If the logged in user is a super admin, this field specifies the new super admin. If the logged in user is a normal admin, this field needs to contain his email.
 * @param adminPasswordNew The new password for the currently logged in admin.
 * @param adminPasswordNewRe The retyped new password for the currently logged in admin.
 * @param clubName The club name./*from w ww  .  j  a v  a 2s .  c  o  m*/
 * @param clubLogo The club logo. If this parameter is present the former club logo is going to be replaced.
 * @param databaseHost The hostname of the used MongoDB server.
 * @param databasePort The port of the used MongoDB server.
 * @param databaseUser The username, used to authenticate against the MongoDB server.
 * @param databasePassword The password, used to authenticate against the MongoDB server.
 * @param databaseCollection The name of the database collection, where the data of this system is stored in.
 * @param rememberMeTokenKey The phrase used to secure the remember me cookies.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentAdminPassword The password of the currently logged in user, used to authenticate the changes.
 * @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.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveSettings(@RequestParam(required = false) String currentAdmin,
        @RequestParam(required = false) String adminPasswordNew,
        @RequestParam(required = false) String adminPasswordNewRe,
        @RequestParam(required = false) String clubName, @RequestParam(required = false) MultipartFile clubLogo,
        @RequestParam(required = false) String databaseHost,
        @RequestParam(required = false) String databasePort,
        @RequestParam(required = false) String databaseUser,
        @RequestParam(required = false) String databasePassword,
        @RequestParam(required = false) String databaseCollection, @RequestParam Map<String, String> parameters,
        @RequestParam String currentAdminPassword, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save settings");
    Settings settings = Settings.loadSettings(settingsRepository);
    if (!passwordEncoder.isPasswordValid(currentUser.getPassword(), currentAdminPassword,
            currentUser.getSalt())) {
        logger.warn("[" + currentUser + "] The stated password is invalid");
        return new ResponseEntity<>("The stated password is incorrect, please try again", HttpStatus.FORBIDDEN);
    } else if (currentUser.isAdmin()) {
        if (currentUser.isSuperAdmin()) {
            logger.debug("[" + currentUser + "] The user is a super admin");
            if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) {
                logger.warn("[" + currentUser + "] The super admin user is changing to " + currentAdmin);
                Division rootDivision = divisionRepository.findByName(settings.getClubName());
                if (rootDivision == null) {
                    logger.warn("[" + currentUser + "] Unable to find root division " + settings.getClubName());
                    return new ResponseEntity<>("Unable to find root division",
                            HttpStatus.INTERNAL_SERVER_ERROR);
                }

                User newSuperAdmin = userRepository.findByEmail(currentAdmin);
                if (newSuperAdmin == null) {
                    logger.warn("[" + currentUser + "] Unable to find new super admin " + currentAdmin);
                    return new ResponseEntity<>("Unable to find new super admin",
                            HttpStatus.INTERNAL_SERVER_ERROR);
                }

                logger.debug("[" + currentUser + "] Saving new super admin");
                rootDivision.setAdminUser(newSuperAdmin);
                divisionRepository.save(rootDivision);
                logger.info("[" + currentUser + "] Successfully saved " + currentAdmin + " as new super admin");
            }
            try {
                if (clubName != null && !clubName.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting club name to " + clubName);
                    Division rootDivision = divisionRepository.findByName(settings.getClubName());
                    if (rootDivision == null) {
                        logger.warn("[" + currentUser + "] Unable to find former root division.");
                        return new ResponseEntity<>("Unable to find former root division",
                                HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    //Changing and saving the root division
                    rootDivision.setName(clubName);
                    divisionRepository.save(rootDivision);
                    settings.setClubName(clubName);
                }

                if (clubLogo != null && !clubLogo.isEmpty()) {
                    logger.debug("[" + currentUser + "] Saving club logo");
                    try {
                        gridFSRepository.storeClubLogo(clubLogo);
                    } catch (MongoException e) {
                        logger.warn("[" + currentUser + "] Problem while saving club logo: " + e.getMessage());
                        return new ResponseEntity<>("Problem while saving club logo: " + e.getMessage(),
                                HttpStatus.BAD_REQUEST);
                    }
                }

                if (databaseHost != null && !databaseHost.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting database host to " + databaseHost);
                    settings.setDatabaseHost(databaseHost);
                }

                if (databasePort != null && !databasePort.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting database port to " + databasePort);
                    settings.setDatabasePort(databasePort);
                }

                if (databaseUser != null) {
                    logger.debug("[" + currentUser + "] Setting database user to " + databaseUser);
                    settings.setDatabaseUser(databaseUser);
                }

                if (databasePassword != null) {
                    logger.debug("[" + currentUser + "] Setting database password");
                    settings.setDatabasePassword(databasePassword);
                }

                if (databaseCollection != null && !databaseCollection.isEmpty()) {
                    logger.debug(
                            "[" + currentUser + "] Setting database collection name " + databaseCollection);
                    settings.setDatabaseName(databaseCollection);
                }

                logger.debug("[" + currentUser + "] Gathering all custom user fields");
                //Reducing parameters to custom user field parameters only and the value of the input
                List<String> reducedValues = parameters.keySet().parallelStream()
                        .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty())
                        .distinct() //Only allowing distinct keys
                        .map(key -> key.substring(4)) //Reducing the key to the initial 'name' value, used to create the fields by jQuery
                        .collect(Collectors.toList());

                //Analysing the values and checking, if
                if (!reducedValues.isEmpty()) {
                    logger.debug("[" + currentUser + "] There are custom user fields available");
                    ArrayList<String> customUserFieldValues = new ArrayList<>();
                    reducedValues.parallelStream().forEach(key -> {
                        if (parameters.get("delete" + key) != null) {
                            logger.warn("[" + currentUser + "] Deleting custom user field " + key);
                            if (parameters.get("deleteContent" + key) != null) {
                                logger.warn("[" + currentUser + "] Deleting content of custom user field " + key
                                        + " on every user object");
                                List<User> user = mongoTemplate.find(
                                        new Query(Criteria.where("customUserField." + key).exists(true)),
                                        User.class);
                                if (user != null && !user.isEmpty()) {
                                    user.parallelStream().forEach(thisUser -> {
                                        thisUser.removeCustomUserField(key);
                                        try {
                                            logger.trace(
                                                    "[" + currentUser + "] Deleting custom user field content "
                                                            + key + " for user " + thisUser.getEmail());
                                            userRepository.save(thisUser);
                                        } catch (ConstraintViolationException e) {
                                            logger.warn("[" + currentUser
                                                    + "] A database constraint was violated while trying to delete the custom user field "
                                                    + key + " for user " + thisUser.getEmail() + ": "
                                                    + e.getMessage());
                                        }
                                    });
                                }
                            }
                        } else {
                            String value = parameters.get("cuf_" + key).trim();
                            if (!key.equals(value) && settings.getCustomUserFields().contains(key)) //The key was renamed
                            {
                                logger.debug("[" + currentUser + "] The custom user field " + key
                                        + " changed to " + value);
                                List<User> user = mongoTemplate.find(
                                        new Query(Criteria.where("customUserField." + key).exists(true)),
                                        User.class);
                                if (user != null && !user.isEmpty()) {
                                    user.parallelStream().forEach(thisUser -> {
                                        thisUser.renameCustomUserField(key, value);
                                        try {
                                            logger.trace("[" + currentUser + "] Renaming custom user field "
                                                    + key + " to " + value + " for user "
                                                    + thisUser.getEmail());
                                            userRepository.save(thisUser);
                                        } catch (ConstraintViolationException e) {
                                            logger.warn("[" + currentUser
                                                    + "] A database constraint was violated while trying to rename the custom user field "
                                                    + key + " for user " + thisUser.getEmail() + ": "
                                                    + e.getMessage());
                                        }
                                    });
                                }
                            }
                            logger.debug("[" + currentUser + "] Adding " + value + " as custom user field");
                            customUserFieldValues.add(value);
                        }
                    });
                    settings.setCustomUserFields(customUserFieldValues);
                }

                logger.debug("[" + currentUser + "] Saving updated settings file");
                settings.saveSettings(currentUser, settingsRepository);
                logger.info("[" + currentUser + "] Successfully saved updated settings file");
            } catch (IOException e) {
                logger.warn("[" + currentUser + "] Unable to update settings file: " + e.getMessage());
                return new ResponseEntity<>("Unable to update settings file", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            logger.debug("[" + currentUser + "] The user is an admin");
            if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) {
                logger.warn("[" + currentUser + "] The current user differs from the stated user");
                return new ResponseEntity<>("The current user differs from the stated user",
                        HttpStatus.BAD_REQUEST);
            }
        }

        if (adminPasswordNew != null && adminPasswordNewRe != null && !adminPasswordNew.isEmpty()
                && !adminPasswordNewRe.isEmpty()) {
            logger.info("[" + currentUser + "] The user wants to change his password.");
            if (!adminPasswordNew.equals(adminPasswordNewRe)) {
                logger.warn("[" + currentUser + "] The stated passwords did not match");
                return new ResponseEntity<>("The stated passwords did not match", HttpStatus.BAD_REQUEST);
            } else {
                currentUser.setPassword(adminPasswordNew);
                try {
                    logger.debug("[" + currentUser + "] Saving new user password.");
                    userRepository.save(currentUser);
                    logger.info("[" + currentUser + "] Successfully saved new user password");
                } catch (ConstraintViolationException e) {
                    logger.warn("[" + currentUser
                            + "] A database constraint was violated while saving the user: " + e.getMessage());
                    return new ResponseEntity<>("A database constraint was violated while saving the user.",
                            HttpStatus.BAD_REQUEST);
                }
            }
        }
    } else {
        logger.warn("[" + currentUser + "] A user who is not an admin tries to change the settings ");
        return new ResponseEntity<>("You are not allowed to change these settings", HttpStatus.FORBIDDEN);
    }
    logger.info("[" + currentUser + "] Successfully updated all settings");
    return new ResponseEntity<>("Successfully updated settings", HttpStatus.OK);
}

From source file:plbtw.klmpk.barang.hilang.controller.BarangController.java

@RequestMapping(method = RequestMethod.PUT, produces = "application/json")
public CustomResponseMessage updateBarang(@RequestHeader String apiKey,
        @RequestBody BarangRequest barangRequest) {
    try {//from  w  w  w .  j a v  a2 s.  c om
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        LogRequest temp = DependencyFactory.createLog(apiKey, "Put");

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);

        Barang barang = barangService.getBarang(barangRequest.getId());
        barang.setJumlah(barangRequest.getJumlahBarang());
        barang.setKategoriBarang(kategoriBarangService.getKategoriBarang(barangRequest.getIdKategoriBarang()));
        barang.setNama(barangRequest.getNama());
        barang.setStatus(barangRequest.getStatus());
        barang.setUrl_image(barangRequest.getUrl_image());
        barang.setUser(userService.getUser(barangRequest.getIdUserPemilik()));
        barangService.updateBarang(barang);
        return new CustomResponseMessage(HttpStatus.CREATED, "Update Barang Successfull");
    } catch (NullPointerException ex) {
        return new CustomResponseMessage(HttpStatus.NOT_FOUND, "Data not found");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

From source file:com.tikinou.schedulesdirect.ClientUtils.java

public int retryConnection(SchedulesDirectClient client, AuthenticatedBaseCommandParameter params,
        HttpClientErrorException ex, int numRetries) throws Exception {
    numRetries--;//  w  w w.  j  av  a 2  s . c om
    if (numRetries < 0)
        throw ex;
    if (ex.getStatusCode() == HttpStatus.FORBIDDEN) {
        client.getCredentials().resetTokenInfo();
        params.setToken(null);
        client.connect(client.getCredentials(), false);
        params.setToken(client.getCredentials().getToken());
    }
    return numRetries;
}