Java 类org.springframework.security.core.annotation.AuthenticationPrincipal 实例源码

项目:Diber-backend    文件:OrderController.java   
@PreAuthorize("@securityServiceImpl.hasAdminPermissions(#userPrincipal)")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteOrder(@AuthenticationPrincipal User userPrincipal,
                                     @PathVariable("id") long id) {
    LOGGER.info("Start deleteOrder");
    Order order = orderService.getById(id);

    if (order == null) {
        LOGGER.error("Order with id {} is not found", id);
        return new ResponseEntity<>("Order not found", HttpStatus.NOT_FOUND);
    }

    for (Request request : order.getRequests()) {
        LOGGER.info("set order to null of request with id: {}", request.getId());
        request.setOrder(null);
    }

    orderService.delete(id);
    return new ResponseEntity<>(id, HttpStatus.NO_CONTENT);
}
项目:Diber-backend    文件:AddressController.java   
@PreAuthorize("@securityServiceImpl.hasAdminPermissions(#userPrincipal)")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteAddress(@AuthenticationPrincipal User userPrincipal,
                                       @PathVariable("id") long id) {
    LOGGER.info("Start deleteAddress");
    Address address = addressService.findOne(id);

    if (address == null) {
        LOGGER.error("Address with id {} is not found", id);
        return new ResponseEntity<>("Address not found", HttpStatus.NOT_FOUND);
    }

    // todo also maybe only set "disabled/deleted" property to true and doesn't show to user instead of deleting
    // todo add check for order status and if one of the orders has "In progress" status then don't delete address

    for (Order order : address.getOrders()) {
        //order.setAddressFrom(null);
        // todo
    }

    addressService.delete(id);
    return new ResponseEntity<>(id, HttpStatus.NO_CONTENT);
}
项目:Diber-backend    文件:UserAddressController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #userId)")
@RequestMapping(value = "/{address_id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteAddress(@AuthenticationPrincipal User userPrincipal,
                                       @PathVariable("user_id") long userId,
                                       @PathVariable("address_id") long addressId) {
    LOGGER.info("Start deleteAddress addressId: {}", addressId);
    Address address = addressService.findOne(addressId);

    if (address == null) {
        LOGGER.error("Address with id {} is not found", addressId);
        return new ResponseEntity<>("Address not found", HttpStatus.NOT_FOUND);
    }

    // todo add check for order status and if one of the orders has "In progress" status then don't delete address

    for (Order order : address.getOrders()) {
        order.setAddressFrom(null);
    }

    addressService.delete(addressId);
    return new ResponseEntity<>(addressId, HttpStatus.NO_CONTENT);
}
项目:bxbot-ui-server    文件:MarketsConfigController.java   
/**
 * Updates a given Market configuration.
 *
 * @param user         the authenticated user.
 * @param botId        the id of the Bot to update the Market config for.
 * @param marketId     id of the Market config to update.
 * @param marketConfig the updated Market config.
 * @return 200 'Ok' and the updated Market config if successful, some other HTTP status code otherwise.
 */
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/{botId}" + MARKETS_RESOURCE_PATH + "/{marketId}", method = RequestMethod.PUT)
public ResponseEntity<?> updateMarket(@AuthenticationPrincipal User user, @PathVariable String botId,
                                      @PathVariable String marketId, @RequestBody MarketConfig marketConfig) {

    if (marketConfig.getId() == null || !marketId.equals(marketConfig.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    LOG.info("PUT " + CONFIG_ENDPOINT_BASE_URI + botId + MARKETS_RESOURCE_PATH + "/" + marketId + " - updateMarket() "); //- caller: " + user.getUsername());
    LOG.info("Request: " + marketConfig);

    final MarketConfig updatedConfig = marketConfigService.updateMarketConfig(botId, marketConfig);
    return updatedConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(updatedConfig, HttpStatus.OK);
}
项目:bxbot-ui-server    文件:BotsConfigController.java   
/**
 * Updates the Bot config configuration for a given Bot id.
 *
 * @param user      the authenticated user making the request.
 * @param botConfig the Bot config to update.
 * @return 200 'OK' HTTP status code with updated Bot config if successful, some other HTTP status code otherwise.
 */
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/{botId}", method = RequestMethod.PUT)
public ResponseEntity<?> updateBot(@AuthenticationPrincipal User user, @PathVariable String botId, @RequestBody BotConfig botConfig) {

    LOG.info("PUT " + CONFIG_ENDPOINT_BASE_URI + botId + " - updateBot()"); // - caller: " + user.getUsername());
    LOG.info("Request: " + botConfig);

    if (!botId.equals(botConfig.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    final BotConfig updateBotConfig = botConfigService.updateBotConfig(botConfig);
    return updateBotConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(updateBotConfig, HttpStatus.OK);
}
项目:bxbot-ui-server    文件:BotsConfigController.java   
/**
 * Deletes a Bot configuration for a given id.
 *
 * @param user  the authenticated user.
 * @param botId the id of the Bot configuration to delete.
 * @return 204 'No Content' HTTP status code if delete successful, some other HTTP status code otherwise.
 */
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/{botId}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteBot(@AuthenticationPrincipal User user, @PathVariable String botId) {

    LOG.info("DELETE " + CONFIG_ENDPOINT_BASE_URI + botId + " - deleteBot()"); // - caller: " + user.getUsername());

    final BotConfig deletedConfig = botConfigService.deleteBotConfig(botId);
    return deletedConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
项目:bxbot-ui-server    文件:StrategiesConfigController.java   
/**
 * Updates a given Strategy configuration.
 *
 * @param user           the authenticated user.
 * @param botId          the id of the Bot to update the Strategy config for.
 * @param strategyId     id of the Strategy config to update.
 * @param strategyConfig the updated Strategy config.
 * @return 200 'Ok' and the updated Strategy config if successful, some other HTTP status code otherwise.
 */
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/{botId}" + STRATEGIES_RESOURCE_PATH + "/{strategyId}", method = RequestMethod.PUT)
public ResponseEntity<?> updateStrategy(@AuthenticationPrincipal User user, @PathVariable String botId,
                                        @PathVariable String strategyId, @RequestBody StrategyConfig strategyConfig) {

    if (strategyConfig.getId() == null || !strategyId.equals(strategyConfig.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    LOG.info("PUT " + CONFIG_ENDPOINT_BASE_URI + botId + STRATEGIES_RESOURCE_PATH + "/" + strategyId + " - updateStrategy() "); //- caller: " + user.getUsername());
    LOG.info("Request: " + strategyConfig);

    final StrategyConfig updatedConfig = strategyConfigService.updateStrategyConfig(botId, strategyConfig);
    return updatedConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(updatedConfig, HttpStatus.OK);
}
项目:services-in-one    文件:TeamsController.java   
@PutMapping(path = "/{teamId}/quota")
@ResponseStatus(HttpStatus.OK)
public TeamQuota updateTeamQuota(@AuthenticationPrincipal final Object claims, @PathVariable final String teamId, @RequestBody final TeamQuotaInfo teamQuotaInfo){
    //check if team owner
    String userId = ((Claims) claims).getSubject();
    if (!teamService.isOwner(teamId, userId)) {
        log.warn("Access denied for {} : /teams/{}/quota PUT", userId, teamId);
        throw new ForbiddenException();
    }

    TeamQuota teamQuota = teamService.updateTeamQuota(teamId, teamQuotaInfo);

    Team team = teamService.getTeamById(teamId);
    ZonedDateTime startDate = team.getApplicationDate();
    ZonedDateTime endDate = ZonedDateTime.now();
    String usage = analyticsService.getUsageStatistics(teamId, startDate, endDate);

    return new TeamQuotaInfo(teamQuota, usage);
}
项目:services-in-one    文件:UploadController.java   
@GetMapping(params = {"filename"})
public String deleteUpload(@AuthenticationPrincipal Object claims, @RequestParam("filename") String filename) {
    if (claims == null || !(claims instanceof Claims)) {
        throw new UnauthorizedException();
    }
    try {
        if (uploadService.deleteUpload("", "", filename)) {
            log.info("File {} deleted.", filename);
            return "Deleted";
        } else {
            log.info("File {} not deleted.", filename);
            return "Not Deleted";
        }
    } catch (IOException e) {
        log.error("Unable to delete file: {}", e);
        throw new BadRequestException();
    }
}
项目:pivotal-cla    文件:AdminLinkClaController.java   
@RequestMapping(value = "/admin/cla/link/migrate", method = RequestMethod.POST)
public String updatePullRequestStatuses(@AuthenticationPrincipal User user, @ModelAttribute UpdatePullRequestStatusesForm updatePullRequestStatusesForm, HttpServletRequest request) throws Exception {
    String claName = updatePullRequestStatusesForm.getClaName();
    String urlEncodedClaName = URLEncoder.encode(claName, "UTF-8");


    UrlBuilder signClaUrlBldr = UrlBuilder.fromRequest(request);
    String signClaUrl = signClaUrlBldr.path("/sign/" + urlEncodedClaName).build();

    UrlBuilder aboutUrlBldr = UrlBuilder.fromRequest(request);
    String aboutUrl = aboutUrlBldr.path("/about").build();

    UrlBuilder baseSyncUrlBldr = UrlBuilder.fromRequest(request);
    String baseSyncUrl = baseSyncUrlBldr.path("/sync/" + urlEncodedClaName).build();

    MigratePullRequestStatusRequest migratePullRequests = MigratePullRequestStatusRequest.builder()
                        .accessToken(user.getAccessToken())
                        .commitStatusUrl(signClaUrl)
                        .repositoryIds(updatePullRequestStatusesForm.getRepositories())
                        .faqUrl(aboutUrl)
                        .baseSyncUrl(baseSyncUrl)
                        .build();

    claService.migratePullRequestStatus(updatePullRequestStatusesForm.getClaName(), migratePullRequests);
    return "redirect:/admin/cla/link";
}
项目:services-in-one    文件:UploadController.java   
@PostMapping(value = "/chunks/{resumableChunkNumber}")
@ResponseStatus(HttpStatus.ACCEPTED)
public String fileUpload(@AuthenticationPrincipal Object claims,
                         @RequestBody @Valid ResumableInfo resumableInfo,
                         @PathVariable String resumableChunkNumber) {
    if (claims == null || !(claims instanceof Claims)) {
        throw new UnauthorizedException();
    }
    switch (uploadService.addChunk(resumableInfo, Integer.parseInt(resumableChunkNumber), null, null)) {
        case FINISHED:
            return "Finished";
        case UPLOAD:
            return "Upload";
        default:
            return "";
    }
}
项目:services-in-one    文件:AnalyticsController.java   
@GetMapping("/usage/teams/{id}")
@ResponseStatus(HttpStatus.OK)
public String getUsageStatistics(@AuthenticationPrincipal Object claims,
                                 @PathVariable final String id,
                                 @RequestParam(value = "startDate", required = false) String startDate,
                                 @RequestParam(value = "endDate", required = false) String endDate) {
    if (claims == null || !(claims instanceof Claims)) {
        log.warn("Access denied for: /analytics/usage/teams GET");
        throw new UnauthorizedException();
    }

    ZonedDateTime start = getZonedDateTime(startDate);
    ZonedDateTime end = getZonedDateTime(endDate);
    ZonedDateTime now = ZonedDateTime.now();
    if (start == null)
        start = now.with(firstDayOfMonth());
    if (end == null)
        end = now.with(lastDayOfMonth());

    return analyticsService.getUsageStatistics(id, start, end);
}
项目:services-in-one    文件:AnalyticsController.java   
@GetMapping("/energy")
@ResponseStatus(HttpStatus.OK)
public List<Double> getEnergyStatistics(@AuthenticationPrincipal Object claims,
                                    @RequestParam(value = "startDate", required = false) String startDate,
                                    @RequestParam(value = "endDate", required = false) String endDate) {

    //check admin using validator class from common
    checkAdmin((Claims) claims);

    ZonedDateTime start = getZonedDateTime(startDate);
    ZonedDateTime end = getZonedDateTime(endDate);
    ZonedDateTime now = ZonedDateTime.now();
    if (start == null) {
        start = now.with(firstDayOfMonth());
    }
    if (end == null) {
        end = now.with(lastDayOfMonth());
    }
    return analyticsService.getEnergyStatistics(start, end);
}
项目:services-in-one    文件:DataController.java   
@GetMapping()
@ResponseStatus(HttpStatus.OK)
public List<Data> getDatasets(@AuthenticationPrincipal Object claims) {
    if (claims == null || !(claims instanceof Claims)) {
        log.warn("Access denied for: /datasets GET");
        throw new UnauthorizedException();
    }
    try {
        checkAdmin((Claims) claims);
        return dataService.getDatasets().stream().map(DataInfo::new).collect(Collectors.toList());
    } catch (ForbiddenException e) {
        String contextUserId = ((Claims) claims).getSubject();
        return dataService.getDatasets().stream()
                .filter(d -> !(d.getVisibility() == DataVisibility.PRIVATE && !d.getContributorId().equals(contextUserId)))
                .map(DataInfo::new).collect(Collectors.toList());
    }
}
项目:services-in-one    文件:DataController.java   
@GetMapping(path = "/{id}")
@ResponseStatus(HttpStatus.OK)
public Data getDatasetById(@AuthenticationPrincipal Object claims, @PathVariable Long id) {
    if (claims == null || !(claims instanceof Claims)) {
        throw new UnauthorizedException();
    }
    try {
        checkAdmin((Claims) claims);
        return new DataInfo(dataService.getDataset(id));
    } catch (ForbiddenException e) {
        String contextUserId = ((Claims) claims).getSubject();
        Data data = dataService.getDataset(id);
        if (!(data.getVisibility() == DataVisibility.PRIVATE && !data.getContributorId().equals(contextUserId))) {
            return new DataInfo(data);
        } else {
            throw new ForbiddenException();
        }
    }
}
项目:pivotal-cla    文件:IclaController.java   
@RequestMapping("/sign/{claName}/icla")
public String claForm(@AuthenticationPrincipal User user, @ModelAttribute SignClaForm signClaForm,
        Map<String, Object> model) {
    String claName = signClaForm.getClaName();

    IndividualSignature signed = claService.findIndividualSignaturesFor(user, claName);
    ContributorLicenseAgreement cla = signed == null ? clas.findByNameAndPrimaryTrue(claName) : signed.getCla();
    if(cla == null) {
        throw new ResourceNotFoundException();
    }
    if(cla.getSupersedingCla() != null) {
        cla = cla.getSupersedingCla();
    }
    signClaForm.setSigned(signed != null);
    signClaForm.setName(user.getName());
    signClaForm.setClaId(cla.getId());
    model.put("cla", cla);

    return "cla/icla/sign";
}
项目:services-in-one    文件:DataController.java   
@GetMapping(path = "/{did}/resources/{rid}/download", params = {"visibility"})
public void downloadPublicResource(@AuthenticationPrincipal Object claims,
                                   @PathVariable Long did, @PathVariable Long rid,
                                   @RequestParam("visibility") DataVisibility visibility,
                                   HttpServletResponse response, HttpServletRequest request) {
    if (claims == null && visibility != DataVisibility.PUBLIC) {
        log.warn("Access denied for: /datasets/" + did + "/resources/" + rid + "/download?visibility=" + visibility);
        throw new UnauthorizedException();
    }
    Enumeration values = request.getHeaders("PublicUserId");
    if (values.hasMoreElements()) {
        String puid = (String) values.nextElement();
        log.info("Public user id: {}", puid);
        dataService.downloadPublicOpenResource(response, did, rid, Long.valueOf(puid));
    } else {
        log.warn("No public user id provided");
        throw new BadRequestException();
    }
}
项目:pivotal-cla    文件:ClaController.java   
@RequestMapping("/sign/{claName}")
public String signIndex(@AuthenticationPrincipal User user, @ModelAttribute ClaRequest claRequest,
        Map<String, Object> model) throws Exception {
    String claName = claRequest.getClaName();
    Integer pullRequestId = claRequest.getPullRequestId();
    String repositoryId = claRequest.getRepositoryId();
    ContributorLicenseAgreement cla = clas.findByNameAndPrimaryTrue(claName);
    if(cla == null) {
        throw new ResourceNotFoundException();
    }

    boolean signed = user != null && claService.hasSigned(user, claName);

    model.put("repositoryId",repositoryId);
    model.put("pullRequestId", pullRequestId);
    model.put("signed", signed);
    model.put("claName", claName);
    return "index";
}
项目:programmeren3    文件:QuestionAnswerController.java   
@GetMapping("/q/{questionId}")
public ModelAndView showQuestion(@PathVariable long questionId, @AuthenticationPrincipal CustomUserDetails userDetails) {
    QuestionAnswer question = this.questionAnswerService.getQuestion(questionId);
    if (question != null) {
        final Vote vote  = this.voteService.getVoteByUser(question, userDetails);
        final Map<QuestionAnswer, Vote> answersWithVotes = this.questionAnswerService.getAnswersWithUserVotes(question, userDetails);

        final QuestionAnswerDto questionDto = dtoMapper.toDto(question, vote);
        final List<QuestionAnswerDto> answerDtos = dtoMapper.toDto(answersWithVotes);

        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("show_question");
        modelAndView.getModel().put("question", questionDto);
        modelAndView.getModel().put("answers", answerDtos);
        return modelAndView;
    }
    else {
        // This would be a good way to handle this:
        throw new HttpServerErrorException(HttpStatus.NOT_FOUND, "QuestionAnswer with ID '" + questionId + "' not found.");

        // Alternatively, let this exceptions be picked up by AppWideExceptionHandler:
        //throw new QuestionNotFoundException("QuestionAnswer with ID '" + questionId + "' not found.");
    }
}
项目:Diber-backend    文件:OrderController.java   
@PreAuthorize("@securityServiceImpl.hasAdminPermissions(#userPrincipal)")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteOrder(@AuthenticationPrincipal User userPrincipal,
                                     @PathVariable("id") long id) {
    LOGGER.info("Start deleteOrder");
    Order order = orderService.getById(id);

    if (order == null) {
        LOGGER.error("Order with id {} is not found", id);
        return new ResponseEntity<>("Order not found", HttpStatus.NOT_FOUND);
    }

    for (Request request : order.getRequests()) {
        LOGGER.info("set order to null of request with id: {}", request.getId());
        request.setOrder(null);
    }

    orderService.delete(id);
    return new ResponseEntity<>(id, HttpStatus.NO_CONTENT);
}
项目:entelect-spring-webapp-template    文件:AccountController.java   
@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public ModelAndView passwordReset(@AuthenticationPrincipal CustomUser activeUser,
                                  @Valid @ModelAttribute ResetPasswordForm resetPasswordForm,
                                  BindingResult binding,
                                  RedirectAttributes redirectAttributes) {
    if (binding.hasErrors()) {
        log.info(String.format("Password reset for %s failed due to invalid input.",
            activeUser.getAppUser().getEmail()));

        redirectAttributes.addFlashAttribute("error", "Password reset failed.");

        return new ModelAndView("redirect:/account");
    }

    if (!resetPasswordForm.getPassword().equals(resetPasswordForm.getPasswordConfirmation())) {
        redirectAttributes.addFlashAttribute("error", "Passwords must match.");
        return new ModelAndView("redirect:/account");
    }

    redirectAttributes.addFlashAttribute("message", "Password has been changed.");
    appUserService.resetPassword(activeUser.getAppUser(), resetPasswordForm.getPassword());
    return new ModelAndView("redirect:/account");
}
项目:raptor    文件:TreeController.java   
@RequestMapping(
        method = RequestMethod.GET
)
@ApiOperation(
        value = "List all trees",
        notes = "",
        response = TreeNode.class,
        responseContainer = "List",
        nickname = "list"
)
@PreAuthorize("@raptorSecurity.list(principal, 'tree')")
public ResponseEntity<?> list(
        @AuthenticationPrincipal User currentUser
) {
    TreeNode root = (new TreeNode()).id(null).user(currentUser);
    List<TreeNode> roots = treeService.children(root);
    List<TreeNode> nodes = roots.stream().map((n) -> treeService.tree(n)).collect(Collectors.toList());
    return ResponseEntity.ok(nodes);
}
项目:Diber-backend    文件:UserAddressController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #userId)")
@RequestMapping(value = "/{address_id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteAddress(@AuthenticationPrincipal User userPrincipal,
                                       @PathVariable("user_id") long userId,
                                       @PathVariable("address_id") long addressId) {
    LOGGER.info("Start deleteAddress addressId: {}", addressId);
    Address address = addressService.findOne(addressId);

    if (address == null) {
        LOGGER.error("Address with id {} is not found", addressId);
        return new ResponseEntity<>("Address not found", HttpStatus.NOT_FOUND);
    }

    // todo add check for order status and if one of the orders has "In progress" status then don't delete address

    for (Order order : address.getOrders()) {
        order.setAddressFrom(null);
    }

    addressService.delete(addressId);
    return new ResponseEntity<>(addressId, HttpStatus.NO_CONTENT);
}
项目:todolist    文件:TaskController.java   
@JsonView(ModelBase.API.class)
@RequestMapping(method=RequestMethod.POST)
public ResponseEntity<?> create(@AuthenticationPrincipal User user, @Valid @ModelAttribute TaskForm form, Errors errors) {
    Task task;

    if(errors.hasErrors()) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors.toString());
    }

    try {
        task = new Task();
        task.setPriority(Task.TaskPriority.NORMAL);
        task.setBelongsTo(user);
        task.setBelongsToName(user.getName());
        task.setBelongsToEmail(user.getEmail());
        taskService.save(form.push(task));
    } catch (DataAccessException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex);
    }

    return ResponseEntity.ok(task);
}
项目:raptor    文件:ProfileController.java   
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/{name}")
@ApiOperation(
        value = "Return a profile value by key",
        notes = "",
        response = org.createnet.raptor.models.profile.Profile.class,
        nickname = "getProfile"
)
@PreAuthorize("@raptorSecurity.can(principal, 'profile', 'read', #userId)")
public ResponseEntity<?> getProfile(
        @AuthenticationPrincipal User currentUser,
        @PathVariable("userId") String userId,
        @PathVariable("name") String name
) {

    if ((userId == null || name == null) || (userId.isEmpty() || name.isEmpty())) {
        return JsonErrorResponse.badRequest();
    }

    org.createnet.raptor.models.profile.Profile pref = profileService.get(userId, name);
    if (pref == null) {
        return JsonErrorResponse.entity(HttpStatus.NOT_FOUND, "Not found");
    }
    return ResponseEntity.ok(toJSON(pref.getValue()));
}
项目:raptor    文件:ProfileController.java   
@RequestMapping(method = RequestMethod.PUT, value = "/{userId}/{name}")
@ApiOperation(
        value = "Set an profile value by key",
        notes = "",
        response = org.createnet.raptor.models.profile.Profile.class,
        nickname = "setProfile"
)
@PreAuthorize("@raptorSecurity.can(principal, 'profile', 'create', #userId) or @raptorSecurity.can(principal, 'profile', 'update', #userId)")
public ResponseEntity<?> setProfile(
        @AuthenticationPrincipal User currentUser,
        @PathVariable("userId") String userId,
        @PathVariable("name") String name,
        @RequestBody JsonNode body
) {

    if ((userId == null || name == null) || (userId.isEmpty() || name.isEmpty())) {
        return JsonErrorResponse.badRequest();
    }

    org.createnet.raptor.models.profile.Profile pref = new org.createnet.raptor.models.profile.Profile(userId, name, body.toString());
    profileService.save(pref);
    return ResponseEntity.ok(toJSON(pref.getValue()));
}
项目:raptor    文件:ProfileController.java   
@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}/{name}")
@ApiOperation(
        value = "Drop an profile value by key",
        notes = "",
        response = org.createnet.raptor.models.profile.Profile.class,
        nickname = "deleteProfile"
)
@PreAuthorize("@raptorSecurity.can(principal, 'profile', 'delete', #userId)")
public ResponseEntity<?> deleteProfile(
        @AuthenticationPrincipal User currentUser,
        @PathVariable("userId") String userId,
        @PathVariable("name") String name
) {

    if ((userId == null || name == null) || (userId.isEmpty() || name.isEmpty())) {
        return JsonErrorResponse.badRequest();
    }

    org.createnet.raptor.models.profile.Profile pref = profileService.get(userId, name);
    if (pref == null) {
        return JsonErrorResponse.entity(HttpStatus.NOT_FOUND, "Not found");
    }

    profileService.delete(pref);
    return ResponseEntity.accepted().build();
}
项目:raptor    文件:InventoryController.java   
@RequestMapping(method = RequestMethod.GET)
@ApiOperation(value = "Return the user devices", notes = "", response = Device.class, nickname = "getDevices")
@PreAuthorize("@raptorSecurity.list(principal, 'device')")

public ResponseEntity<?> getDevices(
        @AuthenticationPrincipal User currentUser,
        Pageable pageable
) {

    String userId = currentUser.getId();
    if (currentUser.isAdmin()) {
        userId = null;
    }

    QDevice device = new QDevice("device");
    BooleanBuilder predicate = new BooleanBuilder();

    if (userId != null) {
        predicate.and(device.userId.eq(userId));
    }

    Page<Device> result = deviceService.search(predicate, pageable);

    return ResponseEntity.ok(result);
}
项目:raptor    文件:InventoryController.java   
@RequestMapping(method = RequestMethod.DELETE, value = "/{deviceId}")
@ApiOperation(value = "Delete a device instance", notes = "", response = Device.class, nickname = "deleteDevice")
@PreAuthorize("@raptorSecurity.can(principal, 'device', 'delete', #deviceId)")
public ResponseEntity<?> deleteDevice(@AuthenticationPrincipal User currentUser,
        @PathVariable("deviceId") String deviceId) {

    Device device = deviceService.get(deviceId);
    if (device == null) {
        return JsonErrorResponse.entity(HttpStatus.NOT_FOUND, "Device not found");
    }

    deviceService.delete(device);

    eventPublisher.delete(device);

    return ResponseEntity.accepted().build();
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@PostMapping(value = BASE_PATH)
public Mono<String> createFile(
        @RequestPart("file") Flux<FilePart> files,
        @AuthenticationPrincipal Principal principal) {
    return imageService.createImage(files, principal)
        .then(Mono.just("redirect:/"));
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@PostMapping(value = BASE_PATH)
public Mono<String> createFile(
    @RequestPart("file") Flux<FilePart> files,
    @AuthenticationPrincipal Principal principal) {
    return imageService.createImage(files, principal)
        .then(Mono.just("redirect:/"));
}
项目:spring-authorization-server    文件:UserInfoRestController.java   
@RequestMapping(path = "/userinfo", method = RequestMethod.GET)
public ResponseEntity<?> getCurrentUser(@AuthenticationPrincipal CommonUser commonUser) {
    if (commonUser != null) {
        return ResponseEntity.ok(new UserInfoResource(commonUser.getUser()));
    } else {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
项目:Diber-backend    文件:UserReviewController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #userId)")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getReviews(@AuthenticationPrincipal User userPrincipal,
                                    @PathVariable("user_id") long userId) {
    LOGGER.info("Start getReviews userId: {}", userId);
    //List<Review> reviews = reviewService.findByUserId(userId); // todo separate this
    List<Review> reviews = reviewService.findByCourierId(userId);
    return new ResponseEntity<>(ReviewDto.toDto(reviews), HttpStatus.OK);
}
项目:Diber-backend    文件:UserController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #id)")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> getById(@AuthenticationPrincipal User userPrincipal,
                                 @PathVariable("id") long id) {
    LOGGER.info("Start getById id: {}", id);
    User user = userService.findOne(id);

    if (user == null) {
        LOGGER.error("User with id {} is not found", id);
        return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>(UserDto.toDto(user), HttpStatus.OK);
}
项目:Diber-backend    文件:UserController.java   
@PreAuthorize("@securityServiceImpl.hasAdminPermissions(#userPrincipal)")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getUsers(@AuthenticationPrincipal User userPrincipal, Pageable pageable) {
    LOGGER.info("Start getUsers");
    Page<User> users = userService.findAllByPage(pageable);
    Page<UserDto> ordersDtos = users.map(UserDto::toDto);
    return new ResponseEntity<>(ordersDtos, HttpStatus.OK);
}
项目:Diber-backend    文件:UserController.java   
@PreAuthorize("@securityServiceImpl.hasAdminPermissions(#userPrincipal)")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteById(@AuthenticationPrincipal User userPrincipal,
                                    @PathVariable("id") long id) {
    LOGGER.info("Start deleteById id: {}", id);
    User user = userService.findOne(id);

    if (user == null) {
        LOGGER.error("User with id {} is not found", id);
        return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
    }

    userService.delete(id);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
项目:Diber-backend    文件:UserRequestController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#user, #userId)")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getRequests(@AuthenticationPrincipal User user,
                                     @PathVariable("user_id") long userId) {
    LOGGER.info("Start getRequests userId: {}", userId);
    List<Request> requests = requestService.findByCourierId(userId);
    List<RequestDto> requestsDtos = RequestDto.toDto(requests);
    return new ResponseEntity<>(requestsDtos, HttpStatus.OK);
}
项目:Diber-backend    文件:UserOrderController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #userId)")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getOrders(@AuthenticationPrincipal User userPrincipal,
                                   @PathVariable("user_id") long userId, Pageable pageable) {
    LOGGER.info("getOrders for userId: {}", userId);
    Page<Order> orders = orderService.findByUserId(userId, pageable);
    Page<OrderDto> ordersDtos = orders.map(OrderDto::toDto);
    return new ResponseEntity<>(ordersDtos, HttpStatus.OK);
}
项目:Diber-backend    文件:UserAddressController.java   
@PreAuthorize("@securityServiceImpl.hasPermissions(#userPrincipal, #userId)")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getAddresses(@AuthenticationPrincipal User userPrincipal,
                                      @PathVariable("user_id") long userId) {

    LOGGER.info("Start getAddresses user_id: {}", userId);
    List<Address> addresses = addressService.findByUserId(userId);
    List<AddressDto> addressesDtos = AddressDto.toDto(addresses);
    return new ResponseEntity<>(addressesDtos, HttpStatus.OK);
}
项目:bxbot-ui-server    文件:BotStatusController.java   
/**
 * Returns the Bot status for a given Bot id.
 *
 * @param user  the authenticated user.
 * @param botId the id of the Bot to fetch.
 * @return the Bot status for the given id.
 */
@PreAuthorize("hasRole('USER')")
@RequestMapping(value = "/{botId}" + STATUS_RESOURCE_PATH, method = RequestMethod.GET)
public ResponseEntity<?> getBotStatus(@AuthenticationPrincipal User user, @PathVariable String botId) {

    LOG.info("GET " + RUNTIME_ENDPOINT_BASE_URI + botId + STATUS_RESOURCE_PATH + " - getBotStatus()"); // - caller: " + user.getUsername());

    final BotStatus botStatus = botProcessService.getBotStatus(botId);
    return botStatus == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(botStatus, HttpStatus.OK);
}