Java Code Examples for org.springframework.security.access.prepost.PreAuthorize

The following examples show how to use org.springframework.security.access.prepost.PreAuthorize. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 修改
 */
@SysLog("修改菜单")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:menu:update')")
public ResponseEntity<String> update(@Valid @RequestBody SysMenu menu){
	//数据校验
	verifyForm(menu);

	if(menu.getType() == MenuType.MENU.getValue()){
		if(StrUtil.isBlank(menu.getUrl())){
			return ResponseEntity.badRequest().body("菜单URL不能为空");
		}
	}
	sysMenuService.updateById(menu);

	return ResponseEntity.ok().build();
}
 
Example 2
Source Project: RuoYi-Vue   Source File: SysDeptController.java    License: MIT License 6 votes vote down vote up
/**
 * 查询部门列表(排除节点)
 */
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list/exclude/{deptId}")
public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
{
    List<SysDept> depts = deptService.selectDeptList(new SysDept());
    Iterator<SysDept> it = depts.iterator();
    while (it.hasNext())
    {
        SysDept d = (SysDept) it.next();
        if (d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
        {
            it.remove();
        }
    }
    return AjaxResult.success(depts);
}
 
Example 3
Source Project: macrozheng   Source File: PmsBrandController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "更新品牌")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:update')")
public CommonResult update(@PathVariable("id") Long id,
                           @Validated @RequestBody PmsBrandParam pmsBrandParam,
                           BindingResult result) {
    CommonResult commonResult;
    int count = brandService.updateBrand(id, pmsBrandParam);
    if (count == 1) {
        commonResult = CommonResult.success(count);
    } else {
        commonResult = CommonResult.failed();
    }
    return commonResult;
}
 
Example 4
/**
 * 删除用户
 */
@SysLog("删除用户")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys:user:delete')")
public ResponseEntity<String> delete(@RequestBody Long[] userIds){
	if (userIds.length == 0) {
		return ResponseEntity.badRequest().body("请选择需要删除的用户");
	}
	if(ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)){
		return ResponseEntity.badRequest().body("系统管理员不能删除");
	}
	if(ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())){
		return ResponseEntity.badRequest().body("当前用户不能删除");
	}
	sysUserService.deleteBatch(userIds,SecurityUtils.getSysUser().getShopId());
	return ResponseEntity.ok().build();
}
 
Example 5
Source Project: RuoYi-Vue   Source File: SysMenuController.java    License: MIT License 6 votes vote down vote up
/**
 * 修改菜单
 */
@PreAuthorize("@ss.hasPermi('system:menu:edit')")
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysMenu menu)
{
    if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
    {
        return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
    }
    else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
            && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
    {
        return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头");
    }
    menu.setUpdateBy(SecurityUtils.getUsername());
    return toAjax(menuService.updateMenu(menu));
}
 
Example 6
Source Project: yshopmall   Source File: SysUserController.java    License: Apache License 2.0 6 votes vote down vote up
@Log("删除用户")
@ApiOperation("删除用户")
@DeleteMapping
@PreAuthorize("@el.check('admin','user:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){

    UserDto user = userService.findByName(SecurityUtils.getUsername());
    for (Long id : ids) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足,不能删除:" + userService.findByName(SecurityUtils.getUsername()).getUsername());
        }
    }
    userService.delete(ids);
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example 7
/**
 * 修改用户
 */
@SysLog("修改用户")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:user:update')")
public ResponseEntity<String> update(@Valid @RequestBody SysUser user){
	String password = user.getPassword();

	SysUser dbUser = sysUserService.getSysUserById(user.getUserId());

	if (!Objects.equals(dbUser.getShopId(), SecurityUtils.getSysUser().getShopId())) {
		throw new YamiShopBindException("没有权限修改该用户信息");
	}
	SysUser dbUserNameInfo = sysUserService.getByUserName(user.getUsername());

	if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),user.getUserId())) {
		return ResponseEntity.badRequest().body("该用户已存在");
	}
	if (StrUtil.isBlank(password)) {
		user.setPassword(null);
	}else {
		user.setPassword(passwordEncoder.encode(user.getPassword()));
	}
	sysUserService.updateUserAndUserRole(user);
	return ResponseEntity.ok().build();
}
 
Example 8
Source Project: mall-learning   Source File: PmsBrandController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation("添加品牌")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:create')")
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
    CommonResult commonResult;
    int count = brandService.createBrand(pmsBrand);
    if (count == 1) {
        commonResult = CommonResult.success(pmsBrand);
        LOGGER.debug("createBrand success:{}", pmsBrand);
    } else {
        commonResult = CommonResult.failed("操作失败");
        LOGGER.debug("createBrand failed:{}", pmsBrand);
    }
    return commonResult;
}
 
Example 9
Source Project: sk-admin   Source File: PictureController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("查询图片")
@PreAuthorize("@sk.check('pictures:list')")
@GetMapping
@ApiOperation("查询图片")
public ResponseEntity<Object> getRoles(PictureQuery criteria, Pageable pageable){
    return new ResponseEntity<>(pictureService.queryAll(criteria,pageable), HttpStatus.OK);
}
 
Example 10
Source Project: cloud-service   Source File: SysPermissionController.java    License: MIT License 5 votes vote down vote up
/**
 * 删除权限标识
 * 
 * @param id
 */
@LogAnnotation(module = "删除权限")
@PreAuthorize("hasAuthority('back:permission:delete')")
@DeleteMapping("/permissions/{id}")
public void delete(@PathVariable Long id) {
	sysPermissionService.delete(id);
}
 
Example 11
Source Project: yshopmall   Source File: SysUserController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("查询用户")
@ApiOperation("查询用户")
@GetMapping
@PreAuthorize("@el.check('admin','user:list')")
public ResponseEntity<Object> getUsers(UserQueryCriteria criteria, Pageable pageable){
    Set<Long> deptSet = new HashSet<>();
    Set<Long> result = new HashSet<>();
    if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
        deptSet.add(criteria.getDeptId());
        deptSet.addAll(dataScope.getDeptChildren(deptService.findByPid(criteria.getDeptId())));
    }
    // 数据权限
    Set<Long> deptIds = dataScope.getDeptIds();
    // 查询条件不为空并且数据权限不为空则取交集
    if (!CollectionUtils.isEmpty(deptIds) && !CollectionUtils.isEmpty(deptSet)){
        // 取交集
        result.addAll(deptSet);
        result.retainAll(deptIds);
        // 若无交集,则代表无数据权限
        criteria.setDeptIds(result);
        if(result.size() == 0){
            return new ResponseEntity<>(PageUtil.toPage(null,0),HttpStatus.OK);
        } else {
            return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
        }
    // 否则取并集
    } else {
        result.addAll(deptSet);
        result.addAll(deptIds);
        criteria.setDeptIds(result);
        return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
    }
}
 
Example 12
Source Project: java-master   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拥有管理员权限可修改任何用户的密码,否则只能修改自己的密码
 */
@PreAuthorize("hasAuthority('ROLE_ADMIN') or (#reqVo.username == #userDetails.username and !T(org.springframework.util.StringUtils).isEmpty(#reqVo.password))")
@PostMapping("/updatePassword")
public Result<Integer> updatePassword(@Validated @RequestBody UpdatePasswordReqVo reqVo,
                                      @AuthenticationPrincipal UserDetails userDetails) {
    return new Result<>(userService.updatePassword(reqVo, userDetails));
}
 
Example 13
Source Project: yshopmall   Source File: StoreProductController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("新增商品")
@ApiOperation(value = "新增商品")
@CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY,allEntries = true)
@PostMapping(value = "/yxStoreProduct")
@PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_CREATE')")
public ResponseEntity create(@Validated @RequestBody YxStoreProduct resources){

    resources.setAddTime(OrderUtil.getSecondTimestampTwo());
    if(ObjectUtil.isEmpty(resources.getGiveIntegral())) resources.setGiveIntegral(BigDecimal.ZERO);
    if(ObjectUtil.isEmpty(resources.getCost())) resources.setCost(BigDecimal.ZERO);
    return new ResponseEntity(yxStoreProductService.saveProduct(resources),HttpStatus.CREATED);
}
 
Example 14
Source Project: java-starthere   Source File: UserController.java    License: MIT License 5 votes vote down vote up
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@GetMapping(value = "/user/name/{userName}",
            produces = {"application/json"})
public ResponseEntity<?> getUserByName(HttpServletRequest request,
                                       @PathVariable
                                               String userName)
{
    logger.trace(request.getMethod()
                        .toUpperCase() + " " + request.getRequestURI() + " accessed");

    User u = userService.findByName(userName);
    return new ResponseEntity<>(u,
                                HttpStatus.OK);
}
 
Example 15
Source Project: FEBS-Cloud   Source File: MenuController.java    License: Apache License 2.0 5 votes vote down vote up
@DeleteMapping("/{menuIds}")
@PreAuthorize("hasAuthority('menu:delete')")
@ControllerEndpoint(operation = "删除菜单/按钮", exceptionMessage = "删除菜单/按钮失败")
public void deleteMenus(@NotBlank(message = "{required}") @PathVariable String menuIds) {
    String[] ids = menuIds.split(StringConstant.COMMA);
    this.menuService.deleteMeuns(ids);
}
 
Example 16
Source Project: yshopmall   Source File: SystemStoreController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('yxSystemStore:list')")
public void download(HttpServletResponse response, YxSystemStoreQueryCriteria criteria) throws IOException {
    yxSystemStoreService.download(generator.convert(yxSystemStoreService.queryAll(criteria), YxSystemStoreDto.class), response);
}
 
Example 17
Source Project: Blog   Source File: TagController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 新增一个标签
 *
 * @param tagName 标签名
 * @return
 */
@ApiOperation(value = "新增标签", notes = "标签名")
@PreAuthorize("hasAuthority('USER')")
@PostMapping
public Result newTag(String tagName) {
    if (!formatUtil.checkStringNull(tagName)) {
        return Result.create(StatusCode.ERROR, "参数异常");
    }
    try {
        tagService.saveTag(tagName);
        return Result.create(StatusCode.OK, "新增成功");
    } catch (RuntimeException e) {
        return Result.create(StatusCode.ERROR, "新增失败," + e.getMessage());
    }
}
 
Example 18
Source Project: mall-learning   Source File: PmsBrandController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation("获取所有品牌列表")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:read')")
public CommonResult<List<PmsBrand>> getBrandList() {
    return CommonResult.success(brandService.listAllBrand());
}
 
Example 19
Source Project: xmall   Source File: PmsBrandController.java    License: MIT License 5 votes vote down vote up
@ApiOperation(value = "批量删除品牌")
@RequestMapping(value = "/delete/batch", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:delete')")
public Object deleteBatch(@RequestParam("ids") List<Long> ids) {
    int count = brandService.deleteBrand(ids);
    if (count > 0) {
        return new CommonResult().success(count);
    } else {
        return new CommonResult().failed();
    }
}
 
Example 20
Source Project: cymbal   Source File: NodeController.java    License: Apache License 2.0 5 votes vote down vote up
@PutMapping("/nodes/{nodeId}")
@PreAuthorize("hasRole('ADMIN')")
@ResponseBody
public void updateNode(@PathVariable final String nodeId, @RequestBody final NodeDTO nodeDTO) {
    Node node = nodeConverter.dtoToPo(nodeDTO);
    nodeProcessService.updateNode(node);
}
 
Example 21
/**
 * 修改
 */
@PutMapping
@PreAuthorize("@pms.hasPermission('admin:attribute:update')")
public ResponseEntity<Void> update(@Valid ProdProp prodProp){
	ProdProp dbProdProp = prodPropService.getById(prodProp.getPropId());
	if (!Objects.equals(dbProdProp.getShopId(), SecurityUtils.getSysUser().getShopId())) {
		throw new YamiShopBindException("没有权限获取该商品规格信息");
	}
	prodProp.setRule(ProdPropRule.ATTRIBUTE.value());
	prodProp.setShopId(SecurityUtils.getSysUser().getShopId());
	prodPropService.updateProdPropAndValues(prodProp);
	return ResponseEntity.ok().build();
}
 
Example 22
Source Project: Blog   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取用户绑定的邮箱
 *
 * @return
 */
@ApiOperation(value = "获取用户绑定的邮箱", notes = "获取用户绑定的邮箱")
@PreAuthorize("hasAuthority('USER')")
@GetMapping("/mail")
public Result getUserMail() {
    return Result.create(StatusCode.OK, "查询成功", userService.findUserMail());
}
 
Example 23
Source Project: RuoYi-Vue   Source File: SysConfigController.java    License: MIT License 5 votes vote down vote up
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:config:export')")
@GetMapping("/export")
public AjaxResult export(SysConfig config)
{
    List<SysConfig> list = configService.selectConfigList(config);
    ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
    return util.exportExcel(list, "参数数据");
}
 
Example 24
Source Project: macrozheng   Source File: PmsBrandController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "根据品牌名称分页获取品牌列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:read')")
public CommonResult<CommonPage<PmsBrand>> getList(@RequestParam(value = "keyword", required = false) String keyword,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
    List<PmsBrand> brandList = brandService.listBrand(keyword, pageNum, pageSize);
    return CommonResult.success(CommonPage.restPage(brandList));
}
 
Example 25
Source Project: open-capacity-platform   Source File: SysUserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 用户查询
     * http://192.168.3.2:7000/users?access_token=3b45d059-601b-4c63-85f9-9d77128ee94d&start=0&length=10
     * @param params
     * @return
     * @throws JsonProcessingException 
     */
    @PreAuthorize("hasAuthority('user:get/users')")
    @ApiOperation(value = "用户查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit",value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/users")
    @LogAnnotation(module="user-center",recordRequestParam=false)
//  searchKey=username, searchValue=as
    public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) throws JsonProcessingException {
        return appUserService.findUsers(params);
    }
 
Example 26
Source Project: FEBS-Cloud   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("excel")
@PreAuthorize("hasAuthority('user:export')")
@ControllerEndpoint(operation = "导出用户数据", exceptionMessage = "导出Excel失败")
public void export(QueryRequest queryRequest, SystemUser user, HttpServletResponse response) {
    List<SystemUser> users = this.userService.findUserDetailList(user, queryRequest).getRecords();
    ExcelKit.$Export(SystemUser.class, response).downXlsx(users, false);
}
 
Example 27
@ApiOperation(value = "批量更新显示状态")
@RequestMapping(value = "/update/showStatus", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAuthority('pms:brand:update')")
public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids,
                                     @RequestParam("showStatus") Integer showStatus) {
    int count = brandService.updateShowStatus(ids, showStatus);
    if (count > 0) {
        return CommonResult.success(count);
    } else {
        return CommonResult.failed();
    }
}
 
Example 28
Source Project: kylin-on-parquet-v2   Source File: AccessService.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN + " or hasPermission(#ae, 'ADMINISTRATION')")
public MutableAclRecord revoke(AclEntity ae, int accessEntryIndex) {
    Message msg = MsgPicker.getMsg();

    if (ae == null)
        throw new BadRequestException(msg.getACL_DOMAIN_NOT_FOUND());

    MutableAclRecord acl = aclService.readAcl(new ObjectIdentityImpl(ae));
    Sid sid = acl.getAclRecord().getAccessControlEntryAt(accessEntryIndex).getSid();

    secureOwner(acl, sid);

    return aclService.upsertAce(acl, sid, null);
}
 
Example 29
Source Project: kylin-on-parquet-v2   Source File: StreamingV2Service.java    License: Apache License 2.0 5 votes vote down vote up
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN)
public void removeReceiver(Node receiver) {
    List<ReplicaSet> replicaSets = streamMetadataStore.getReplicaSets();
    for (ReplicaSet replicaSet : replicaSets) {
        Set<Node> receivers = replicaSet.getNodes();
        if (receivers != null && receivers.contains(receiver)) {
            throw new IllegalStateException("Before remove receiver, it must be firstly removed from replica set:"
                    + replicaSet.getReplicaSetID());
        }
    }
    streamMetadataStore.removeReceiver(receiver);
}
 
Example 30
Source Project: RuoYi-Vue   Source File: SysJobLogController.java    License: MIT License 5 votes vote down vote up
/**
 * 导出定时任务调度日志列表
 */
@PreAuthorize("@ss.hasPermi('monitor:job:export')")
@Log(title = "任务调度日志", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJobLog sysJobLog)
{
    List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
    ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class);
    return util.exportExcel(list, "调度日志");
}