List of usage examples for org.springframework.http HttpStatus FORBIDDEN
HttpStatus FORBIDDEN
To view the source code for org.springframework.http HttpStatus FORBIDDEN.
Click Source Link
From source file:org.osiam.addons.selfadministration.controller.ChangeEmailController.java
/** * Validating the confirm token and saving the new email value as primary email if the validation was successful. * // ww w . j a v a 2 s . co m * @param authorization * Authorization header with HTTP Bearer authorization and a valid access token * @param userId * The user id for the user whom email address should be changed * @param confirmToken * The previously generated confirmation token from the confirmation email * @return The HTTP status code and the updated user if successful */ @RequestMapping(method = RequestMethod.POST, value = "/confirm", produces = "application/json") public ResponseEntity<String> confirm(@RequestHeader("Authorization") final String authorization, @RequestParam("userId") final String userId, @RequestParam("confirmToken") final String confirmToken) throws IOException, MessagingException { if (Strings.isNullOrEmpty(confirmToken)) { LOGGER.log(Level.WARNING, "Confirmation token miss match!"); return getErrorResponseEntity("No ongoing email change!", HttpStatus.UNAUTHORIZED); } User updatedUser; Optional<Email> oldEmail; try { AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization)) .build(); User user = connectorBuilder.createConnector().getUser(userId, accessToken); Extension extension = user.getExtension(internalScimExtensionUrn); String existingConfirmToken = extension.getField(confirmationTokenField, ExtensionFieldType.STRING); if (!existingConfirmToken.equals(confirmToken)) { LOGGER.log(Level.WARNING, "Confirmation token mismatch!"); return getErrorResponseEntity("No ongoing email change!", HttpStatus.FORBIDDEN); } String newEmail = extension.getField(tempEmail, ExtensionFieldType.STRING); oldEmail = SCIMHelper.getPrimaryOrFirstEmail(user); UpdateUser updateUser = getPreparedUserForEmailChange(extension, newEmail, oldEmail.get()); updatedUser = connectorBuilder.createConnector().updateUser(userId, updateUser, accessToken); } catch (OsiamRequestException e) { LOGGER.log(Level.WARNING, e.getMessage()); return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode())); } catch (OsiamClientException e) { return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } Locale locale = RegistrationHelper.getLocale(updatedUser.getLocale()); // build the Map with the link for replacement Map<String, Object> mailVariables = new HashMap<>(); mailVariables.put("user", updatedUser); try { renderAndSendEmailService.renderAndSendEmail("changeemailinfo", fromAddress, oldEmail.get().getValue(), locale, mailVariables); } catch (OsiamException e) { return getErrorResponseEntity("Problems creating email for confirming new user: \"" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK); }
From source file:org.osiam.addons.selfadministration.controller.LostPasswordController.java
/** * Method to change the users password if the preconditions are satisfied. * /* www .j a va2 s . c o m*/ * @param authorization * authZ header with valid access token * @param oneTimePassword * the previously generated one time password * @param newPassword * the new user password * @return the response with status code and the updated user if successfully * @throws IOException */ @RequestMapping(value = "/change", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> change(@RequestHeader("Authorization") final String authorization, @RequestParam String oneTimePassword, @RequestParam String newPassword) throws IOException { if (Strings.isNullOrEmpty(oneTimePassword)) { String errorMessage = "The submitted one time password is invalid!"; LOGGER.log(Level.SEVERE, errorMessage); return getErrorResponseEntity(errorMessage, HttpStatus.UNAUTHORIZED); } User updatedUser; try { AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization)) .build(); User user = connectorBuilder.createConnector().getCurrentUser(accessToken); // validate the oneTimePassword with the saved one from DB Extension extension = user.getExtension(internalScimExtensionUrn); String savedOneTimePassword = extension.getField(this.oneTimePassword, ExtensionFieldType.STRING); if (!savedOneTimePassword.equals(oneTimePassword)) { LOGGER.log(Level.SEVERE, "The submitted one time password is invalid!"); return getErrorResponseEntity("The submitted one time password is invalid!", HttpStatus.FORBIDDEN); } UpdateUser updateUser = getPreparedUserToChangePassword(extension, newPassword); updatedUser = connectorBuilder.createConnector().updateUser(user.getId(), updateUser, accessToken); } catch (OsiamRequestException e) { LOGGER.log(Level.WARNING, e.getMessage()); return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode())); } catch (OsiamClientException e) { return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK); }
From source file:plbtw.klmpk.barang.hilang.controller.UserController.java
@RequestMapping(method = RequestMethod.DELETE, produces = "application/json") public CustomResponseMessage deleteUser(@RequestHeader String apiKey, @RequestBody UserRequest userRequest) { try {// ww w .ja v a2 s . c om if (!authApiKey(apiKey)) { return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication"); } LogRequest temp = DependencyFactory.createLog(apiKey, "Delete"); if (checkRateLimit(RATE_LIMIT, apiKey)) { return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED, "Please wait a while, you have reached your rate limit"); } Log log = new Log(); log.setApiKey(temp.getApiKey()); log.setStatus(temp.getStatus()); log.setTimeRequest(temp.getTime_request()); logService.addLog(log); userService.deleteUser(userRequest.getId()); return new CustomResponseMessage(HttpStatus.CREATED, "Delete Successful"); } catch (Exception ex) { return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString()); } }
From source file:org.mitre.oauth2.web.TokenAPI.java
@RequestMapping(value = "/refresh/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) public String deleteRefreshTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) { OAuth2RefreshTokenEntity token = tokenService.getRefreshTokenById(id); if (token == null) { logger.error("refresh 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("refresh token " + id + " 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 {/*from w w w . j a v a2 s .c o m*/ tokenService.revokeRefreshToken(token); return HttpCodeView.VIEWNAME; } }
From source file:net.maritimecloud.identityregistry.controllers.EntityController.java
/** * Returns new certificate for the entity identified by the given ID * * @return a reply.../*w w w . ja v a 2 s. co m*/ * @throws McBasicRestException */ protected ResponseEntity<PemCertificate> newEntityCert(HttpServletRequest request, String orgMrn, String entityMrn, String type) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being queried belongs to the organization if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn) .equals(MrnUtil.getOrgShortNameFromEntityMrn(entityMrn))) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } T entity = this.entityService.getByMrn(entityMrn); if (entity == null) { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND, request.getServletPath()); } if (entity.getIdOrganization().compareTo(org.getId()) == 0) { PemCertificate ret = this.issueCertificate(entity, org, type, request); return new ResponseEntity<>(ret, HttpStatus.OK); } throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }
From source file:org.craftercms.profile.services.AuthenticationServiceIT.java
@Test public void testCreatePersistentLoginWithDisabledProfile() throws Exception { String profileId = profileService.getProfileByUsername(DEFAULT_TENANT_NAME, DISABLED_USER_USERNAME).getId() .toString();/*from www .ja v a2 s . c o m*/ try { authenticationService.createPersistentLogin(profileId); } catch (ProfileRestServiceException e) { assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); assertEquals(ErrorCode.DISABLED_PROFILE, e.getErrorCode()); } }
From source file:de.steilerdev.myVerein.server.controller.admin.DivisionManagementController.java
/** * This function is creating a new division and chooses the name based on the new division name and an integer, depending how many unnamed division exist. This function is invoked, by POSTing to the URI /api/admin/division together with a "new" non-empty parameter. * @param newFlag The non-empty parameter indicating the creation of a new empty division. * @param currentUser The currently logged in user. * @return An HTTP response with a status code together with a JSON map object, containing an 'errorMessage', or a 'successMessage' respectively. If the operation was successful the name of the new division is accessible via 'newDivisionName'. *///from w ww. j a v a 2 s .co m @RequestMapping(method = RequestMethod.POST, params = "new", produces = "application/json") public ResponseEntity<Map<String, String>> createDivision(@RequestParam("new") String newFlag, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Creating a new empty division"); Map<String, String> responseMap = new HashMap<>(); List<Division> administratedDivisions = getOptimizedSetOfAdministratedDivisions(currentUser); Division newDivision; if (newFlag.isEmpty()) { logger.warn("[" + currentUser + "] The new flag is not allowed to be empty"); responseMap.put("errorMessage", "The new flag parameter is not allowed to be empty"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else if (administratedDivisions != null && administratedDivisions.size() > 0) { String newName = newDivisionName; for (int i = 1; divisionRepository.findByName(newName) != null; i++) { newName = newDivisionName.concat(" " + i); } logger.debug("[" + currentUser + "] The temporary name of the new division is " + newName); newDivision = new Division(); //If there is a new division the parent is one of the administrated divisions. The correct layout is updated through a different request. newDivision.setParent(administratedDivisions.get(0)); newDivision.setName(newName); try { divisionRepository.save(newDivision); logger.info( "[" + currentUser + "] The new division was successfully created with name " + newName); responseMap.put("successMessage", "The new division was successfully created"); responseMap.put("newDivisionName", newName); return new ResponseEntity<>(responseMap, HttpStatus.OK); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while saving the division: " + e.getMessage()); responseMap.put("errorMessage", "A database constraint was violated while saving the division."); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } else { logger.warn("[" + currentUser + "] The user is not allowed to create a new division"); responseMap.put("errorMessage", "You are not allowed to create a new division"); return new ResponseEntity<>(responseMap, HttpStatus.FORBIDDEN); } }