imporve:增加权限控制

This commit is contained in:
2019-06-29 18:42:58 +08:00
parent b0438d32a0
commit 08fd287667
28 changed files with 317 additions and 87 deletions
+29 -39
View File
@@ -38,8 +38,15 @@
<mysql.version>5.1.46</mysql.version>
<druid.version>1.1.16</druid.version>
<swagger2.version>2.8.0</swagger2.version>
<!-- <swagger-ui.version>3.18.3</swagger-ui.version>-->
<swagger-ui.version>2.8.0</swagger-ui.version>
<!-- <swagger-ui.version>2.9.2</swagger-ui.version>-->
<!-- <swagger2.version>2.8.0</swagger2.version>-->
<!-- <swagger2.version>2.8.0</swagger2.version>-->
<mybatis-spring-boot-starter.version>2.0.0</mybatis-spring-boot-starter.version>
<lombok.version>1.18.8</lombok.version>
<!-- <lombok.version>1.18.8</lombok.version>-->
<!-- <lombok.version>1.16.8</lombok.version>-->
<lombok.version>1.18.2</lombok.version>
<springboot.version>2.1.5.RELEASE</springboot.version>
<commons-lang3.version>3.7</commons-lang3.version>
<fastjson.version>1.2.54</fastjson.version>
@@ -48,6 +55,7 @@
<jjwt.version>0.10.5</jjwt.version>
<jjwt.version>0.10.5</jjwt.version>
<mapstruct.version>1.3.0.Final</mapstruct.version>
<!-- <mapstruct.version>1.2.0.Final</mapstruct.version>-->
</properties>
<dependencies>
<dependency>
@@ -65,12 +73,6 @@
<artifactId>hutool-all</artifactId>
<version>4.5.13</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>io.jsonwebtoken</groupId>-->
<!-- <artifactId>jjwt</artifactId>-->
<!-- <version>0.9.1</version>-->
<!-- </dependency>-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@@ -113,31 +115,11 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>com.h2database</groupId> -->
<!-- <artifactId>h2</artifactId> -->
<!-- <version>${h2.version}</version> -->
<!-- </dependency> -->
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-ehcache</artifactId>-->
<!-- <version>${hibernate.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-entitymanager</artifactId>-->
<!-- <version>${hibernate-entitymanager.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.alibaba</groupId>-->
<!-- <artifactId>druid</artifactId>-->
<!-- <version>${druid.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
@@ -148,6 +130,10 @@
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
</exclusion>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
@@ -157,8 +143,12 @@
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
<version>${swagger-ui.version}</version>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
</exclusion>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
@@ -209,12 +199,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springboot.version}</version>
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-tomcat</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-tomcat</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.mybatis.spring.boot</groupId>-->
@@ -247,7 +237,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@@ -262,11 +252,11 @@
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<!-- <options>-->
<!-- <mapstruct.suppressGeneratorTimestamp>true</mapstruct.suppressGeneratorTimestamp>-->
<!-- <mapstruct.defaultComponentModel>spring</mapstruct.defaultComponentModel>-->
<!-- </options>-->
</annotationProcessorPaths>
<!-- <options>-->
<!-- <mapstruct.suppressGeneratorTimestamp>true</mapstruct.suppressGeneratorTimestamp>-->
<!-- <mapstruct.defaultComponentModel>spring</mapstruct.defaultComponentModel>-->
<!-- </options>-->
<!-- <compilerArgs>-->
<!-- <arg>-Amapstruct.suppressGeneratorTimestamp=true</arg>-->
<!-- <arg>-Amapstruct.defaultComponentModel=spring</arg>-->
@@ -13,9 +13,9 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
public @interface Query {
/** Dong ZhaoYang 2017/8/7 基本对象的属性名 */
/** 基本对象的属性名 */
String propName() default "";
/** Dong ZhaoYang 2017/8/7 查询方式 */
/** 查询方式 */
Type type() default Type.EQUAL;
/**
@@ -32,17 +32,17 @@ public @interface Query {
enum Type {
EQUAL
/** Dong ZhaoYang 2017/8/7 大于等于 */
/** 大于等于 */
, GREATER_THAN
/** Dong ZhaoYang 2017/8/7 小于等于 */
/** 小于等于 */
, LESS_THAN
/** Dong ZhaoYang 2017/8/7 中模糊查询 */
/** 中模糊查询 */
, INNER_LIKE
/** Dong ZhaoYang 2017/8/7 左模糊查询 */
/** 左模糊查询 */
, LEFT_LIKE
/** Dong ZhaoYang 2017/8/7 右模糊查询 */
/** 右模糊查询 */
, RIGHT_LIKE
/** Dong ZhaoYang 2017/8/7 小于 */
/** 小于 */
, LESS_THAN_NQ
//** jie 2019/6/4 包含 */
, IN
@@ -17,7 +17,7 @@ import static com.google.common.collect.Lists.newArrayList;
* @author Alawn
*/
@Configuration
//@EnableSwagger2
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
@@ -103,6 +103,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers( HttpMethod.GET, "/","/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
// .antMatchers("/resources/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/users").permitAll()
.antMatchers(HttpMethod.POST,"/api/users/vendors").permitAll()
.antMatchers("/auth/**").permitAll()
.antMatchers("/api/**").authenticated()
// .antMatchers("/basic/**/*").authenticated()
@@ -0,0 +1,39 @@
package net.alawn.bill.constant;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 14:04 2019-06-29
*/
public class AuthorityConstants {
public final static String ADMIN = "admin" ;
public final static String PERMISSION_ALL = "permission:all" ;
public final static String PERMISSION_CREATE = "permission:create" ;
public final static String PERMISSION_UPDATE = "permission:update" ;
public final static String PERMISSION_SELECT = "permission:select" ;
public final static String PERMISSION_DELETE = "permission:delete" ;
public final static String USER_ALL = "user:all" ;
public final static String USER_CREATE = "user:create" ;
public final static String USER_UPDATE = "user:update" ;
public final static String USER_DELETE = "user:delete" ;
public final static String ROLE_ALL = "role:all" ;
public final static String ROLE_CREATE = "role:create" ;
public final static String ROLE_UPDATE = "role:update" ;
public final static String ROLE_DELETE = "role:delete" ;
public final static String BOOK_ALL = "book:all" ;
public final static String BOOK_CREATE = "book:create" ;
public final static String BOOK_UPDATE = "book:update" ;
public final static String BOOK_DELETE = "book:delete" ;
public final static String POST_ALL = "post:all" ;
public final static String POST_CREATE = "post:create" ;
public final static String POST_UPDATE = "post:update" ;
public final static String POST_DELETE = "post:delete" ;
public final static String TITLE_ALL = "title:all" ;
public final static String TITLE_CREATE = "title:create" ;
public final static String TITLE_UPDATE = "title:update" ;
public final static String TITLE_DELETE = "title:delete" ;
public final static String MERCHANT_ALL = "merchant:all" ;
public final static String MERCHANT_CREATE = "merchant:create" ;
public final static String MERCHANT_UPDATE = "merchant:update" ;
public final static String MERCHANT_DELETE = "merchant:delete" ;
}
@@ -0,0 +1,13 @@
package net.alawn.bill.constant;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 14:04 2019-06-29
*/
public class RoleConstants {
public final static String ADMIN = "admin" ;
public final static String VENDOR = "vendor" ;
public final static String CUSTOMER = "customer" ;
public final static String DEFAULT = CUSTOMER ;
}
@@ -9,6 +9,7 @@ import net.alawn.bill.repository.BookRepo;
import net.alawn.bill.repository.ItemRepo;
import net.alawn.bill.security.JwtUser;
import net.alawn.bill.service.dto.NewBill;
import net.alawn.bill.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@@ -87,12 +88,25 @@ public class BillController {
@RequestMapping(value = "/bill/books",method = RequestMethod.GET)
public ResponseEntity<List<Book>> fetchBooks(){
// public ResponseEntity<Page<Book>> fetchBooks(){
JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
JwtUser jwtUser = (JwtUser) SecurityUtils.getUserDetails();
long userId = jwtUser.getId();
String userName = jwtUser.getUsername();
// for(Object authoritie :jwtUser.getAuthorities()) {
// log.info("authoritie:" + authoritie);
// }
// for(Object role:jwtUser.getRoles()) {
// log.info("role:" + role);
// }
// jwtUser.getRoles().contains();
// if (jwtUser.getAuthorities().contains("admin"))
// {
// jwtUser.getRoles().contains("");
//
// }
Page<Book> books = null;
// List<Book> books = bookRepo.findByUserIdOrderByCreateTimeDesc(userId);
@@ -6,6 +6,7 @@ import net.alawn.bill.repository.MerchantRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -27,12 +28,14 @@ public class MerchantController {
@RequestMapping(value = "/merchants",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity addMerchant(@RequestBody Merchant resources) {
@PreAuthorize("hasAnyAuthority('admin','merchant:all','merchant:create','book:create','book:create')")
public ResponseEntity create(@RequestBody Merchant resources) {
return new ResponseEntity(merchantRepo.saveAndFlush(resources), HttpStatus.CREATED);
}
@RequestMapping(value = "/merchants",method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasAnyAuthority('admin','merchant:all','merchant:select','book:create','book:update')")
public ResponseEntity<List<Merchant>> fetchMerchants() {
return ResponseEntity.ok(merchantRepo.findAllByEnabledIsTrue());
}
@@ -40,6 +43,7 @@ public class MerchantController {
@RequestMapping(value = "/merchants/{id}",method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasAnyAuthority('admin','merchant:all','merchant:select')")
public ResponseEntity<Merchant> getMerchant(@PathVariable long id){
Optional<Merchant> merchant = merchantRepo.findById(id);
if(merchant.isPresent()){
@@ -34,16 +34,14 @@ public class PermissionController {
* @return
*/
@GetMapping(value = "/permissions/tree")
// @PreAuthorize("hasAnyRole('admin','permission:all','permission:create','permission:edit','roles:select','roles:all')")
@PreAuthorize("hasAnyAuthority('admin','permission:all')")
@PreAuthorize("hasAnyAuthority('admin','permission:all','permission:select')")
public ResponseEntity getTree(){
return new ResponseEntity(permissionService.getPermissionTree(permissionService.findByPid(0L)), HttpStatus.OK);
}
// @Log("查询权限")
@GetMapping(value = "/permissions")
// @PreAuthorize("hasAnyRole('admin','permission:all','permission:select')")
@PreAuthorize("hasAnyAuthority('admin','permission:all')")
@PreAuthorize("hasAnyAuthority('admin','permission:all','permission:select')")
public ResponseEntity getPermissions(CommonQueryCriteria criteria){
List<PermissionDTO> permissionDTOS = permissionService.queryAll(criteria);
Object obj = permissionService.buildTree(permissionDTOS);
@@ -54,7 +52,8 @@ public class PermissionController {
// @Log("新增权限")
@PostMapping(value = "/permissions")
@PreAuthorize("hasAnyRole('admin','permission:all','permission:create')")
@PreAuthorize("hasAnyAuthority('admin','permission:all','permission:create')")
// @PreAuthorize("hasAnyAuthority('admin','permission:all','permission:create')")
public ResponseEntity create(@Validated @RequestBody Permission resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
@@ -64,7 +63,7 @@ public class PermissionController {
// @Log("修改权限")
@PutMapping(value = "/permissions")
@PreAuthorize("hasAnyRole('admin','permission:all','permission:edit')")
@PreAuthorize("hasAnyAuthority('admin','permission:all','permission:update')")
public ResponseEntity update(@Validated(Permission.Update.class) @RequestBody Permission resources){
permissionService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
@@ -72,7 +71,7 @@ public class PermissionController {
// @Log("删除权限")
@DeleteMapping(value = "/permissions/{id}")
@PreAuthorize("hasAnyRole('admin','permission:all','permission:delete')")
@PreAuthorize("hasAnyAuthority('admin','permission:all','permission:delete')")
public ResponseEntity delete(@PathVariable Long id){
permissionService.delete(id);
return new ResponseEntity(HttpStatus.OK);
@@ -7,6 +7,7 @@ import net.alawn.bill.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -27,6 +28,7 @@ public class PostController {
@RequestMapping(value = "/posts",method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAnyAuthority('admin','post:all','post:create','book:create','book:edit')")
public ResponseEntity create(@RequestBody Post post) {
// public ResponseEntity<Post> create(@RequestBody NewPost newPost) {
// JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
@@ -42,7 +44,8 @@ public class PostController {
@RequestMapping(value = "/posts",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Post>> fetchPosts() {
@PreAuthorize("hasAnyAuthority('admin','post:all','post:select','book:create','book:edit')")
public ResponseEntity<List<Post>> fetch() {
// JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// long userId = authUser.getId();
List<Post> posts = postRepo.findByUserId(SecurityUtils.getUserId());
@@ -51,7 +54,8 @@ public class PostController {
@RequestMapping(value = "/posts/{id}",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Post> getPost(@PathVariable long id){
@PreAuthorize("hasAnyAuthority('admin','post:all','post:select')")
public ResponseEntity<Post> get(@PathVariable long id){
log.info("post id:" + id);
/** 登记 Post */
@@ -0,0 +1,113 @@
package net.alawn.bill.controller;
import cn.hutool.core.lang.Dict;
import net.alawn.bill.entity.po.Role;
import net.alawn.bill.exception.BadRequestException;
import net.alawn.bill.service.RoleService;
import net.alawn.bill.service.dto.CommonQueryCriteria;
import net.alawn.bill.service.dto.RoleSmallDTO;
import net.alawn.bill.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Zheng Jie
* @date 2018-12-03
*/
@RestController
@RequestMapping("api")
public class RoleController {
@Autowired
private RoleService roleService;
private static final String ENTITY_NAME = "role";
/**
* 获取单个role
* @param id
* @return
*/
@GetMapping(value = "/roles/{id}")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:select')")
public ResponseEntity getRoles(@PathVariable Long id){
return new ResponseEntity(roleService.findById(id), HttpStatus.OK);
}
/**
* 返回全部的角色,新增用户时下拉选择
* @return
*/
@GetMapping(value = "/roles/all")
@PreAuthorize("hasAnyAuthority('admin','role:all','user:all','user:create','user:edit')")
public ResponseEntity getAll(@PageableDefault(value = 2000, sort = {"level"}, direction = Sort.Direction.ASC) Pageable pageable){
return new ResponseEntity(roleService.queryAll(pageable), HttpStatus.OK);
}
// @Log("查询角色")
@GetMapping(value = "/roles")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:select')")
public ResponseEntity getRoles(CommonQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(roleService.queryAll(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/roles/level")
public ResponseEntity getLevel(){
List<Integer> levels = roleService.findByUsers_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList());
return new ResponseEntity(Dict.create().set("level", Collections.min(levels)), HttpStatus.OK);
}
// @Log("新增角色")
@PostMapping(value = "/roles")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:create')")
public ResponseEntity create(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(roleService.create(resources), HttpStatus.CREATED);
}
// @Log("修改角色")
@PutMapping(value = "/roles")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:update')")
public ResponseEntity update(@Validated(Role.Update.class) @RequestBody Role resources){
roleService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
// @Log("修改角色权限")
@PutMapping(value = "/roles/permission")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:update')")
public ResponseEntity updatePermission(@RequestBody Role resources){
roleService.updatePermission(resources,roleService.findById(resources.getId()));
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
// @Log("修改角色菜单")
@PutMapping(value = "/roles/menu")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:update')")
public ResponseEntity updateMenu(@RequestBody Role resources){
roleService.updateMenu(resources,roleService.findById(resources.getId()));
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
// @Log("删除角色")
@DeleteMapping(value = "/roles/{id}")
@PreAuthorize("hasAnyAuthority('admin','role:all','role:delete')")
public ResponseEntity delete(@PathVariable Long id){
roleService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
@@ -5,6 +5,7 @@ import net.alawn.bill.entity.po.Title;
import net.alawn.bill.repository.TitleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -27,19 +28,22 @@ public class TitleController {
@RequestMapping(value = "/titles",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Title> addTitle(@RequestBody Title resources) {
@PreAuthorize("hasAnyAuthority('admin','title:all','title:create','book:create','book:edit')")
public ResponseEntity<Title> create(@RequestBody Title resources) {
return ResponseEntity.ok(titleRepo.saveAndFlush(resources));
}
@RequestMapping(value = "/titles",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Title>> addTitle() {
@PreAuthorize("hasAnyAuthority('admin','title:all','title:select','book:create','book:edit')")
public ResponseEntity<List<Title>> fetch() {
return ResponseEntity.ok(titleRepo.findAll());
}
@RequestMapping(value = "/titles/{id}",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Title> getTitle(@PathVariable long id){
@PreAuthorize("hasAnyAuthority('admin','title:all','title:select')")
public ResponseEntity<Title> get(@PathVariable long id){
/** 登记 Title */
Optional<Title> title = titleRepo.findById(id);
if(title.isPresent()) {
@@ -1,8 +1,10 @@
package net.alawn.bill.controller;
import lombok.extern.slf4j.Slf4j;
import net.alawn.bill.constant.RoleConstants;
import net.alawn.bill.entity.po.User;
import net.alawn.bill.exception.BadRequestException;
import net.alawn.bill.repository.RoleRepo;
import net.alawn.bill.security.JwtUser;
import net.alawn.bill.service.RoleService;
import net.alawn.bill.service.UserService;
@@ -41,6 +43,9 @@ public class UserController {
@Autowired
private RoleService roleService;
@Autowired
private RoleRepo roleRepo;
/**
* 添加用户
* @param resources
@@ -49,9 +54,29 @@ public class UserController {
* @throws HttpRequestMethodNotSupportedException
*/
@RequestMapping(value = "/users", method = RequestMethod.POST)
// @PreAuthorize("hasAnyRole('admin','user:all','user:create')")
public ResponseEntity create(@Validated @RequestBody User resources) throws AuthenticationException, HttpRequestMethodNotSupportedException {
// return authService.register(addedUser);
/**
* 普通用户注册默认称为客户
*/
resources.addRole(roleRepo.findByName(RoleConstants.CUSTOMER));
return new ResponseEntity(userService.create(resources), HttpStatus.CREATED);
}
/**
* 添加供应商
* @param resources
* @return
* @throws AuthenticationException
* @throws HttpRequestMethodNotSupportedException
*/
@RequestMapping(value = "/users/vendors", method = RequestMethod.POST)
public ResponseEntity createVendor(@Validated @RequestBody User resources) throws AuthenticationException, HttpRequestMethodNotSupportedException {
/**
* 供应商注册
*/
resources.addRole(roleRepo.findByName(RoleConstants.VENDOR));
return new ResponseEntity(userService.create(resources), HttpStatus.CREATED);
}
@@ -61,7 +86,7 @@ public class UserController {
* @return
*/
@RequestMapping(value = "/users", method = RequestMethod.PUT)
@PreAuthorize("hasAnyRole('admin','user:all','user:edit')")
@PreAuthorize("hasAnyAuthority('admin','user:all','user:update')")
public ResponseEntity update(@Validated(User.Update.class) @RequestBody User resources){
checkLevel(resources);
userService.update(resources);
@@ -75,7 +100,7 @@ public class UserController {
* @return
*/
@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
@PreAuthorize("hasAnyRole('admin','user:all','user:delete')")
@PreAuthorize("hasAnyAuthority('admin','user:all','user:delete')")
public ResponseEntity delete(@PathVariable Long id){
// Integer currentLevel = Collections.min(roleService.findByUser_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
// Integer optLevel = Collections.min(roleService.findByUser_Id(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
@@ -94,7 +119,7 @@ public class UserController {
* @return
*/
@RequestMapping(value = "/users", method = RequestMethod.GET)
// @PreAuthorize("hasAnyRole('admin','user:all','user:select')")
@PreAuthorize("hasAnyAuthority('admin','user:all','user:select')")
public ResponseEntity getUsers(UserQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
// Set<Long> deptSet = new HashSet<>();
@@ -135,6 +160,7 @@ public class UserController {
* @return
*/
@RequestMapping(value = "/users/updatePassword",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('admin','user:all','user:update')")
public ResponseEntity updatePass(@RequestBody User user){
UserDetails userDetails = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
@@ -10,9 +10,8 @@ import net.alawn.bill.enums.State;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
@@ -54,7 +54,7 @@ public class Merchant extends EntityCommon {
* 启用状态
*/
@Column
@Builder.Default
// @Builder.Default
private boolean enabled = true;
public @interface Update{}
@@ -2,6 +2,7 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
@@ -26,6 +27,7 @@ import java.util.Set;
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
@ApiModel
//public class Permission{
public class Permission extends EntityCommon {
@@ -33,7 +33,6 @@ public class Post extends EntityCommon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotNull(groups = {Update.class})
// @ApiModelProperty(hidden = true)
protected Long id;
// public Post(long id) {
@@ -2,11 +2,13 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@Data
@@ -18,6 +20,7 @@ import java.util.Set;
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
@ApiModel
public class Role extends EntityCommon {
//public class Role{
@@ -46,7 +49,7 @@ public class Role extends EntityCommon {
joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "permission_id",referencedColumnName = "id")},
foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
private Set<Permission> permissions;
private Set<Permission> permissions = new HashSet<>();
public @interface Update{}
@@ -30,7 +30,6 @@ public class Title extends EntityCommon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotNull(groups = {Update.class})
// @ApiModelProperty(hidden = true)
private Long id;
private String name;
@@ -11,8 +11,10 @@ import org.springframework.util.StringUtils;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
@@ -41,6 +43,7 @@ public class User extends EntityCommon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotNull(groups = {Update.class})
private Long id;
// public User(long id) {
@@ -82,7 +85,7 @@ public class User extends EntityCommon {
/** 上一次重置密码时间 */
private Date lastPasswordResetDate;
@Builder.Default
// @Builder.Default
private boolean enabled = true;
// @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
@@ -92,7 +95,16 @@ public class User extends EntityCommon {
@JoinTable(name = "t_bill_users_roles",
joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")})
private Set<Role> roles;
private Set<Role> roles = new HashSet<>();
public void addRole(Role role) {
this.roles.add(role);
}
public void removeRole(Role role) {
this.roles.remove(role);
}
/**
@@ -11,7 +11,8 @@ import org.mapstruct.factory.Mappers;
* @author Alawn
* @date 2018-11-23
*/
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
//@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface PermissionMapper extends EntityMapper<PermissionDTO, Permission> {
PermissionMapper INSTANCE = Mappers.getMapper( PermissionMapper.class );
@@ -11,7 +11,8 @@ import org.mapstruct.factory.Mappers;
* @author Alawn
* @date 2018-11-23
*/
@Mapper(componentModel = "spring", uses = {PermissionMapper.class, }, unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(uses = {PermissionMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
//@Mapper(componentModel = "spring", uses = {PermissionMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface RoleMapper extends EntityMapper<RoleDTO, Role> {
RoleMapper INSTANCE = Mappers.getMapper( RoleMapper.class );
}
@@ -11,7 +11,8 @@ import org.mapstruct.factory.Mappers;
* @author Alawn
* @date 2019-06-21
*/
@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
//@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface RoleSmallMapper extends EntityMapper<RoleSmallDTO, Role> {
RoleSmallMapper INSTANCE = Mappers.getMapper( RoleSmallMapper.class );
@@ -14,7 +14,8 @@ import org.mapstruct.factory.Mappers;
* @date 2018-11-23
*/
@Mapper(componentModel = "spring",uses = {RoleMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(uses = {RoleMapper.class,RoleSmallMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
//@Mapper(componentModel = "spring",uses = {RoleMapper.class,,RoleSmallMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper extends EntityMapper<UserDTO, User> {
UserMapper INSTANCE = Mappers.getMapper( UserMapper.class );
}
@@ -1,7 +1,6 @@
package net.alawn.bill.service.dto;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.sql.Timestamp;
@@ -12,7 +11,6 @@ import java.util.List;
* @date 2019-06-21
*/
@Data
@ToString
public class PermissionDTO implements Serializable{
private Long id;
@@ -2,14 +2,12 @@ package net.alawn.bill.service.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Builder
@Data
public class UserDTO implements Serializable {
@@ -4,6 +4,7 @@ import net.alawn.bill.entity.po.Role;
import net.alawn.bill.exception.EntityExistException;
import net.alawn.bill.mapper.RoleMapper;
import net.alawn.bill.mapper.RoleSmallMapper;
import net.alawn.bill.repository.PermissionRepo;
import net.alawn.bill.repository.RoleRepo;
import net.alawn.bill.service.RoleService;
import net.alawn.bill.service.dto.CommonQueryCriteria;
@@ -33,6 +34,10 @@ public class RoleServiceImpl implements RoleService {
@Autowired
private RoleRepo roleRepo;
@Autowired
private PermissionRepo permissionRepo;
// @Resource
// private RoleMapper roleMapper;
//
@@ -66,7 +71,9 @@ public class RoleServiceImpl implements RoleService {
if(roleRepo.findByName(resources.getName()) != null){
throw new EntityExistException(Role.class,"username",resources.getName());
}
// return roleMapper.toDto(roleRepo.save(resources));
// /** 所有角色初始一个权限浏览的Authority,以至于Permissions不为Null */
// resources.getPermissions().add(permissionRepo.findByPerms(AuthorityConstants.PERMISSION_SELECT));
return RoleMapper.INSTANCE.toDto(roleRepo.save(resources));
}
@@ -32,6 +32,7 @@ public class UserServiceImpl implements UserService {
@Autowired
UserRepo userRepo;
// @Autowired
// UserMapper userMapper;
@@ -39,6 +40,7 @@ public class UserServiceImpl implements UserService {
public UserDTO findById(long id) {
Optional<User> user = userRepo.findById(id);
ValidationUtils.isNull(user,"User","id",id);
// return userMapper.toDto(user.get());
// return userMapper.toDto(user.get());
return UserMapper.INSTANCE.toDto(user.get());
}
@@ -118,7 +120,7 @@ public class UserServiceImpl implements UserService {
if (user == null) {
throw new EntityNotFoundException(User.class, "name", userName);
} else {
// UserDTO dto = userMapper.toDto(user);
// return userMapper.toDto(user);
return UserMapper.INSTANCE.toDto(user);
}
}