增加角色权限

This commit is contained in:
LuoYe_MyWork 2020-06-19 17:21:25 +08:00
parent fe77f2d7f2
commit 544415cac1
11 changed files with 27 additions and 283 deletions

View File

@ -36,32 +36,28 @@ public class WebExceptionAspect {
/**
* 拦截web层异常记录异常日志并返回友好信息到前端
*
* @param e
* 异常对象
* @param e 异常对象
*/
@AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e")
public void handleThrowing(JoinPoint joinPoint, Exception e) {
//e.printStackTrace();
/*if (null != user){
log.error("发现异常!操作用户手机号:"+user.getMobile());
}*/
logger.error("发现异常!方法:"+ joinPoint.getSignature().getName()+"--->异常",e);
long time = System.currentTimeMillis();
logger.error("发现异常!方法:{} --->异常 {}, 异常ID: {}", joinPoint.getSignature().getName(), e, time);
//这里输入友好性信息
if (!StringUtils.isEmpty(e.getMessage())){
logger.error("异常",e.getMessage());
writeContent(500,e.getMessage());
}else {
writeContent(500,"十分抱歉,出现异常!程序猿小哥正在紧急抢修...");
// writeContent(500, "十分抱歉,出现异常!程序猿小哥正在紧急抢修...", time);
if (!StringUtils.isEmpty(e.getMessage())) {
logger.error("异常", e.getMessage());
writeContent(500, e.getMessage(),time);
} else {
writeContent(500, "十分抱歉,出现异常!程序猿小哥正在紧急抢修...", time);
}
}
/**
* 将内容输出到浏览器
*
* @param content
* 输出内容
* @param content 输出内容
*/
public static void writeContent(Integer code,String content) {
public static void writeContent(Integer code, String content, long time) {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getResponse();
response.setCharacterEncoding("UTF-8");
@ -72,10 +68,10 @@ public class WebExceptionAspect {
try {
writer = response.getWriter();
jsonGenerator = (new ObjectMapper()).getFactory().createGenerator(writer);
jsonGenerator.writeObject(ResultUtil.error(code,content));
jsonGenerator.writeObject(ResultUtil.error(code, time, content));
} catch (IOException e1) {
e1.printStackTrace();
}finally {
} finally {
writer.flush();
writer.close();
}

View File

@ -1,65 +0,0 @@
package io.qyi.e5.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Iterator;
/**
* 决策管理器
*
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-06-15 16:11
**/
@Slf4j
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
if (collection == null) {
return;
}
System.out.println(o.toString()); // object is a URL.
log.info("object is a URL. {}", o.toString());
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator<ConfigAttribute> iterator = collection.iterator();
while (iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
log.info("访问 " + o.toString() + " 需要的权限是:" + needPermission);
if (needPermission == null) {
break;
}
//用户所拥有的权限authentication
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority ga : authorities) {
if (needPermission.equals(ga.getAuthority())) {
return;
}
}
}
//没有权限
throw new AccessDeniedException(" 无权限! ");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}

View File

@ -1,68 +0,0 @@
package io.qyi.e5.config.security;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-06-17 16:25
**/
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
private HashMap<String, Collection<ConfigAttribute>> map =null;
/**
* 加载权限表中所有权限
*/
public void loadResourceDefine(){
map = new HashMap<>();
Collection<ConfigAttribute> array;
ConfigAttribute cfg;
List<Map<String, String>> permissions = new LinkedList<>();
for(Map<String, String> permission : permissions) {
array = new ArrayList<>();
cfg = new SecurityConfig("ADMIN");
//此处只添加了用户的名字其实还可以添加更多权限的信息例如请求方法到ConfigAttribute的集合中去此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数
array.add(cfg);
//用权限的getUrl() 作为map的key用ConfigAttribute的集合作为 value
map.put("/admin/test", array);
}
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if(map ==null) loadResourceDefine();
//object 中包含用户请求的request 信息
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
AntPathRequestMatcher matcher;
String resUrl;
for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next();
matcher = new AntPathRequestMatcher(resUrl);
if(matcher.matches(request)) {
return map.get(resUrl);
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return false;
}
}

View File

@ -58,12 +58,11 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
// 创建已认证的用户密码认证对象
public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id,String Authority, Collection<? extends GrantedAuthority> authorities) {
public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.name = name;
this.avatar_url = avatar_url;
this.github_id = github_id;
this.Authority = Authority;
super.setAuthenticated(true);
}

View File

@ -28,7 +28,7 @@ import java.util.UUID;
**/
@RestController
@RequestMapping("/admin")
public class TestController {
public class AdminController {
@Autowired
RabbitTemplate rabbitTemplate;
@ -45,6 +45,7 @@ public class TestController {
public void send() {
Task.sendTaskOutlookMQ(19658189);
}
@GetMapping("/sendAll")
public String sendAll() {
Task.sendTaskOutlookMQALL();

View File

@ -9,7 +9,6 @@ package io.qyi.e5.service.task;
public interface ITask {
void sendTaskOutlookMQ(int github_id);
void sendTaskOutlookMQALL();
void executeE5(int github_id);
boolean executeE5(int github_id);
}

View File

@ -72,13 +72,13 @@ public class TaskImpl implements ITask {
}
@Override
public void executeE5(int github_id) {
public boolean executeE5(int github_id) {
Outlook Outlook = outlookService.getOne(new QueryWrapper<Outlook>().eq("github_id", github_id));
if (Outlook == null) {
logger.warn("未找到此用户,github_id: {}", github_id);
return;
return false;
}
outlookService.getMailList(Outlook);
return outlookService.getMailList(Outlook);
}
/**

View File

@ -31,6 +31,13 @@ public class ResultUtil extends Throwable {
result.setMsg(msg);
return result;
}
public static Result error(Integer code, long time, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(time);
return result;
}
public static Result success(ResultEnum resultEnum, Object object) {
Result result = new Result();
result.setCode(resultEnum.getCode());

View File

@ -1,13 +0,0 @@
package io.qyi.e5;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class E5ApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -1,46 +0,0 @@
package io.qyi.e5.string;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-04-20 00:38
**/
public class MyThread implements Runnable {
private Random random = null;
public MyThread() {
random = new Random();
}
@Override
public void run() {
try {
System.out.println("任务执行开始:" + new Date());
/**使用随机延时[0-3]秒来模拟执行任务*/
int sleepNumber = random.nextInt(3);
TimeUnit.SECONDS.sleep(2);
System.out.println("任务执行完毕:" + new Date());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(2);
System.out.println("开始任务");
for (int i = 0; i < 4; i++) {
//延时3秒执行
service.schedule(new MyThread(), 3, TimeUnit.SECONDS);
}
System.out.println("结束任务");
}
}

View File

@ -1,66 +0,0 @@
package io.qyi.e5.string;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-03-05 17:09
**/
public class dome01 {
@Test
public void test01() {
String[] s = new String[]{"CompactToken validation", "Access token has expired.", "Access token validation failure"};
String msg = "Access token has expired.";
System.out.println(s[1]);
System.out.println(msg.indexOf(s[1]));
}
@Test
public void test() {
JsonObject jsonObject = new Gson().fromJson("", JsonObject.class);
JsonArray data = jsonObject.getAsJsonArray("data");
for (JsonElement j : data) {
int pid = j.getAsJsonObject().get("pid").getAsInt();
}
for (int i = 0; i < data.size(); i++) {
JsonObject JsonObject = data.get(i).getAsJsonObject();
JsonObject.get("pid").getAsInt();
}
}
@Test
public void r(){
for (int i = 0; i < 30; i++) {
System.out.println(getRandom(3600,7200));
}
}
@Test
public void ScheduledExecutor(){
}
public String getRandom(int start, int end){
Random r = new Random();
String Expiration = String.valueOf((r.nextInt(end-start +1) + start) );
return Expiration;
}
}