实现权限相关的获取

dev-active
lensfrex 2 years ago
parent bb90b69df0
commit fd91bd15ca
Signed by: lensfrex
GPG Key ID: 0F69A0A2FBEE98A0
  1. 9
      pom.xml
  2. 4
      src/main/java/net/lensfrex/dscape/ServerMain.java
  3. 84
      src/main/java/net/lensfrex/dscape/auth/StpInterfaceImpl.java
  4. 2
      src/main/java/net/lensfrex/dscape/dao/entity/ComputeHistory.java
  5. 52
      src/main/java/net/lensfrex/dscape/dao/entity/RolePermission.java
  6. 52
      src/main/java/net/lensfrex/dscape/dao/entity/UserRole.java
  7. 15
      src/main/java/net/lensfrex/dscape/dao/mapper/RolePermissionMapper.java
  8. 15
      src/main/java/net/lensfrex/dscape/dao/mapper/UserRoleMapper.java
  9. 22
      src/main/java/net/lensfrex/dscape/dao/service/RolePermissionService.java
  10. 19
      src/main/java/net/lensfrex/dscape/dao/service/UserRoleService.java
  11. 51
      src/main/java/net/lensfrex/dscape/dao/service/impl/RolePermissionServiceImpl.java
  12. 37
      src/main/java/net/lensfrex/dscape/dao/service/impl/UserRoleServiceImpl.java
  13. 15
      src/main/java/net/lensfrex/dscape/dto/request/UserLoginRequestBody.java
  14. 8
      src/main/java/net/lensfrex/dscape/web/controllers/Error.java
  15. 2
      src/main/java/net/lensfrex/dscape/web/controllers/compute/ComputeController.java
  16. 2
      src/main/java/net/lensfrex/dscape/web/controllers/history/HistoryController.java
  17. 21
      src/main/java/net/lensfrex/dscape/web/controllers/user/UserController.java
  18. 4
      src/main/java/net/lensfrex/dscape/web/controllers/user/admin/AdminController.java
  19. 18
      src/main/java/net/lensfrex/dscape/web/service/user/UserService.java
  20. 15
      src/main/resources/application.yml
  21. 20
      src/test/java/net/lensfrex/dscape/test/TestMain.java

@ -127,6 +127,15 @@
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -4,9 +4,11 @@ import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
@SpringBootApplication @SpringBootApplication
@MapperScan("net.lensfrex.dscape.module.dao.mappers") @MapperScan("net.lensfrex.dscape.dao.mapper")
public class ServerMain extends SpringBootServletInitializer { public class ServerMain extends SpringBootServletInitializer {
public static void main(String[] args) { public static void main(String[] args) {

@ -1,19 +1,97 @@
package net.lensfrex.dscape.auth; package net.lensfrex.dscape.auth;
import cn.dev33.satoken.stp.StpInterface; import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.lensfrex.dscape.dao.entity.RolePermission;
import net.lensfrex.dscape.dao.entity.UserRole;
import net.lensfrex.dscape.dao.service.RolePermissionService;
import net.lensfrex.dscape.dao.service.UserRoleService;
import net.lensfrex.dscape.dao.service.impl.UserRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Slf4j
@Component @Component
public class StpInterfaceImpl implements StpInterface { public class StpInterfaceImpl implements StpInterface {
private final UserRoleService userRoleService;
private final RolePermissionService rolePermissionService;
private final RedisTemplate<String, String> redis;
@Autowired
public StpInterfaceImpl(RedisTemplate<String, String> redis,
UserRoleService userRoleService,
RolePermissionService rolePermissionService) {
this.userRoleService = userRoleService;
this.rolePermissionService = rolePermissionService;
this.redis = redis;
}
@Override @Override
public List<String> getPermissionList(Object loginId, String loginType) { public List<String> getPermissionList(Object loginId, String loginType) {
return null; String uid = (String) loginId;
List<String> userRoles = this.getRoleList(loginId, loginType);
List<String> rolePermissions = new ArrayList<>();
for (String role : userRoles) {
String redisRolePermissionKey = "dscape:auth:role.permission:" + role;
if (Boolean.FALSE.equals(redis.hasKey(redisRolePermissionKey))) {
log.debug("角色 " + uid + " 的权限信息缓存不存在,从数据库中查找并放入缓存");
rolePermissions.addAll(rolePermissionService.getPermissions(role));
if (rolePermissions.isEmpty()) {
return rolePermissions;
}
redis.opsForList().leftPushAll(redisRolePermissionKey, rolePermissions);
} else {
List<String> cachedUserRole = redis.opsForList().range(redisRolePermissionKey, 0, -1);
if (cachedUserRole == null) {
return rolePermissions;
}
rolePermissions.addAll(cachedUserRole);
}
}
return rolePermissions;
} }
@Override @Override
public List<String> getRoleList(Object loginId, String loginType) { public List<String> getRoleList(Object loginId, String loginType) {
return null; String uid = (String) loginId;
String redisUserRoleKey = "dscape:auth:user.role:" + uid;
List<String> userRoleList = new ArrayList<>(2);
if (Boolean.FALSE.equals(redis.hasKey(redisUserRoleKey))) {
log.debug("用户 " + uid + " 的角色信息缓存不存在,从数据库中查找并放入缓存");
userRoleList.addAll(userRoleService.getRoles(uid));
if (userRoleList.isEmpty()) {
return userRoleList;
}
redis.opsForList().leftPushAll(redisUserRoleKey, userRoleList);
} else {
List<String> cachedUserRole = redis.opsForList().range(redisUserRoleKey, 0, -1);
if (cachedUserRole == null) {
return userRoleList;
}
userRoleList.addAll(cachedUserRole);
}
return userRoleList;
} }
} }

@ -15,10 +15,10 @@ public class ComputeHistory implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
/** /**
* id * id
*/ */
@TableId(type = IdType.AUTO)
private Integer id; private Integer id;
/** /**

@ -0,0 +1,52 @@
package net.lensfrex.dscape.dao.entity;
import lombok.Data;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
/**
* @description role_permission
* @author lensfrex
* @date 2022-08-17
*/
@Data
public class RolePermission implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
/**
* id
*/
private Long id;
/**
* 角色id
*/
private Integer role;
/**
* 权限id
*/
private Integer permission;
/**
* create_time
*/
private LocalDateTime createTime;
/**
* edit_time
*/
private LocalDateTime editTime;
/**
* is_deleted
*/
private int isDeleted;
public RolePermission() {}
}

@ -0,0 +1,52 @@
package net.lensfrex.dscape.dao.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
/**
* @description user_role
* @author lensfrex
* @date 2022-08-17
*/
@Data
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 角色id
*/
private Integer role;
/**
* 用户uid
*/
private String uid;
/**
* create_time
*/
private LocalDateTime createTime;
/**
* edit_time
*/
private LocalDateTime editTime;
/**
* is_deleted
*/
private int isDeleted;
public UserRole() {}
}

@ -0,0 +1,15 @@
package net.lensfrex.dscape.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import net.lensfrex.dscape.dao.entity.RolePermission;
import java.util.List;
/**
* @description role_permissionMapper
* @author lensfrex
* @date 2022-08-17
*/
@Mapper
public interface RolePermissionMapper extends BaseMapper<RolePermission> {
}

@ -0,0 +1,15 @@
package net.lensfrex.dscape.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import net.lensfrex.dscape.dao.entity.UserRole;
import java.util.List;
/**
* @description user_roleMapper
* @author lensfrex
* @date 2022-08-17
*/
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
}

@ -0,0 +1,22 @@
package net.lensfrex.dscape.dao.service;
import net.lensfrex.dscape.dao.entity.RolePermission;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* @description role_permission服务层
* @author lensfrex
* @date 2022-08-17
*/
@Service
public interface RolePermissionService extends IService<RolePermission> {
@Select("select permission from role_permission where role = #{role} and is_deleted = 0")
List<String> getPermissions(String role);
@Select("select permission from role_permission where role = #{role} and is_deleted = 0")
List<String> getPermissions(List<String> roles);
}

@ -0,0 +1,19 @@
package net.lensfrex.dscape.dao.service;
import net.lensfrex.dscape.dao.entity.UserRole;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* @description user_role服务层
* @author lensfrex
* @date 2022-08-17
*/
@Service
public interface UserRoleService extends IService<UserRole> {
@Select("select role from user_role where uid = '#{uid}' and is_deleted != 1")
List<String> getRoles(String uid);
}

@ -0,0 +1,51 @@
/*
* Class created by lensfrex.
*/
package net.lensfrex.dscape.dao.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.lensfrex.dscape.dao.entity.RolePermission;
import net.lensfrex.dscape.dao.mapper.RolePermissionMapper;
import net.lensfrex.dscape.dao.service.RolePermissionService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {
@Override
public List<String> getPermissions(String role) {
QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
wrapper.lambda()
.select(RolePermission::getPermission)
.eq(RolePermission::getRole, role)
.eq(RolePermission::getIsDeleted, 0);
return this.getPermissions(wrapper);
}
@Override
public List<String> getPermissions(List<String> roles) {
QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
wrapper.lambda()
.select(RolePermission::getPermission)
.in(RolePermission::getRole, roles)
.eq(RolePermission::getIsDeleted, 0);
return this.getPermissions(wrapper);
}
private List<String> getPermissions(QueryWrapper<RolePermission> wrapper) {
List<RolePermission> rolePermissionList = this.list(wrapper);
List<String > permissions = new ArrayList<>();
rolePermissionList.forEach(rolePermission -> permissions.add(rolePermission.getPermission().toString()));
return permissions;
}
}

@ -0,0 +1,37 @@
/*
* Class created by lensfrex.
*/
package net.lensfrex.dscape.dao.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.lensfrex.dscape.dao.entity.UserRole;
import net.lensfrex.dscape.dao.mapper.UserRoleMapper;
import net.lensfrex.dscape.dao.service.UserRoleService;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
@Override
public List<String> getRoles(String uid) {
QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
wrapper.lambda()
.select(UserRole::getRole)
.eq(UserRole::getUid, uid)
.eq(UserRole::getIsDeleted, 0);
List<UserRole> userRoleList = this.list(wrapper);
List<String> roles = new ArrayList<>();
userRoleList.forEach(userRole -> roles.add(userRole.getRole().toString()));
return roles;
}
}

@ -0,0 +1,15 @@
package net.lensfrex.dscape.dto.request;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class UserLoginRequestBody {
private String password;
@JsonProperty("user_name")
private String userName;
}

@ -10,9 +10,9 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice @ControllerAdvice
public class Error extends AbstractMethodError { public class Error extends AbstractMethodError {
@ExceptionHandler({ RuntimeException.class }) // @ExceptionHandler({ RuntimeException.class })
public Response error() { // public Response error() {
return Response.error(50000, "服务器内部错误...."); // return Response.error(50000, "服务器内部错误....");
} // }
} }

@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@RequestMapping("/compute") @RequestMapping("/compute")
public class Compute { public class ComputeController {
@GetMapping(value = "/status/{tid}", produces = "application/json") @GetMapping(value = "/status/{tid}", produces = "application/json")
public Response status(@PathVariable String tid, public Response status(@PathVariable String tid,
@RequestHeader String token) { @RequestHeader String token) {

@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@RequestMapping("/history") @RequestMapping("/history")
public class History { public class HistoryController {
@GetMapping(value = "/list/{uid}", produces = "application/json") @GetMapping(value = "/list/{uid}", produces = "application/json")
public Response<Object> list(@PathVariable String uid, public Response<Object> list(@PathVariable String uid,

@ -4,20 +4,35 @@
package net.lensfrex.dscape.web.controllers.user; package net.lensfrex.dscape.web.controllers.user;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import net.lensfrex.dscape.dto.request.UserLoginRequestBody;
import net.lensfrex.dscape.dto.response.general.Response; import net.lensfrex.dscape.dto.response.general.Response;
import net.lensfrex.dscape.dto.response.general.ResponseCode; import net.lensfrex.dscape.dto.response.general.ResponseCode;
import net.lensfrex.dscape.web.service.user.UserService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@JsonSerialize(using = ToStringSerializer.class) @JsonSerialize(using = ToStringSerializer.class)
@RestController @RestController
@RequestMapping("/user") @RequestMapping("/user")
public class User { public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(value = "/login" , produces = "application/json") @PostMapping(value = "/login" , produces = "application/json")
public Response login(@RequestBody String body) { public Response<SaTokenInfo> login(@RequestBody UserLoginRequestBody requestBody) {
return Response.error(ResponseCode.API_NOT_IMPLEMENT); return Response.success(userService.login(requestBody));
}
@GetMapping(value = "/checkLogin" , produces = "application/json")
public Response<Boolean> testLogin(@RequestBody UserLoginRequestBody requestBody) {
return Response.success(StpUtil.isLogin());
} }
@PostMapping(value = "/register", produces = "application/json") @PostMapping(value = "/register", produces = "application/json")

@ -4,14 +4,13 @@
package net.lensfrex.dscape.web.controllers.user.admin; package net.lensfrex.dscape.web.controllers.user.admin;
import cn.dev33.satoken.stp.StpUtil;
import net.lensfrex.dscape.dto.response.general.Response; import net.lensfrex.dscape.dto.response.general.Response;
import net.lensfrex.dscape.dto.response.general.ResponseCode; import net.lensfrex.dscape.dto.response.general.ResponseCode;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@RequestMapping("/user/admin") @RequestMapping("/user/admin")
public class Admin { public class AdminController {
@PostMapping(value = "/add", produces = "application/json") @PostMapping(value = "/add", produces = "application/json")
public Response<Object> addUser(@RequestBody String body, public Response<Object> addUser(@RequestBody String body,
@RequestHeader String token) { @RequestHeader String token) {
@ -24,7 +23,6 @@ public class Admin {
return Response.error(ResponseCode.API_NOT_IMPLEMENT); return Response.error(ResponseCode.API_NOT_IMPLEMENT);
} }
@GetMapping(value = "/application/list", produces = "application/json") @GetMapping(value = "/application/list", produces = "application/json")
public Response listApplication( public Response listApplication(
@RequestParam String offset, @RequestParam String limit, @RequestParam String page, @RequestParam String offset, @RequestParam String limit, @RequestParam String page,

@ -0,0 +1,18 @@
/*
* Class created by lensfrex.
*/
package net.lensfrex.dscape.web.service.user;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import net.lensfrex.dscape.dto.request.UserLoginRequestBody;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public SaTokenInfo login(UserLoginRequestBody requestBody) {
StpUtil.login(requestBody.getUserName());
return StpUtil.getTokenInfo();
}
}

@ -14,7 +14,18 @@ spring:
url: jdbc:mariadb://localhost:3306/dscape?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai url: jdbc:mariadb://localhost:3306/dscape?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: "dscape_user" username: "dscape_user"
password: asdfasdf password: asdfasdf
redis:
client-name: dscape
host: 127.0.0.1
port: 49153
username: default
password: bd2fbffa5
lettuce:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
mybatis-plus: mybatis-plus:
configuration: configuration:
@ -22,7 +33,7 @@ mybatis-plus:
default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler
sa-token: sa-token:
token-name: dscape_token token-name: dscape-token
timeout: 259200 timeout: 259200
activity-timeout: -1 activity-timeout: -1
is-concurrent: true is-concurrent: true

@ -0,0 +1,20 @@
/*
* Class created by lensfrex.
*/
package net.lensfrex.dscape.test;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@Slf4j
@SpringBootTest
public class TestMain {
@Test
public void testPermission() {
StpUtil.getPermissionList("114514asdf").forEach(System.out::println);
}
}
Loading…
Cancel
Save