kaiyu
2020-09-17 613dd76a3aded439f1002d904d85d8332ddb03d1
登陆获取信息分离,webToken添加redis
2 files added
7 files modified
372 ■■■■■ changed files
src/main/java/com/moral/common/exception/WebAuthException.java 7 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/exceptionHandler/WebAuthExceptionHandler.java 11 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/interceptor/WebInterceptor.java 15 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/util/RedisHashUtil.java 124 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/util/WebTokenUtils.java 15 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/controller/WebController.java 112 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/service/AccountService.java 4 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/service/impl/AccountServiceImpl.java 83 ●●●● patch | view | raw | blame | history
src/main/resources/application.yml 1 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/exception/WebAuthException.java
@@ -1,5 +1,12 @@
package com.moral.common.exception;
/**
* @Description: Web授权自定义异常
        * @Param:
        * @return:
        * @Author: 陈凯裕
        * @Date: 2020/9/16
        */
public class WebAuthException extends RuntimeException {
    public WebAuthException() {
        super();
src/main/java/com/moral/common/exceptionHandler/WebAuthExceptionHandler.java
@@ -6,14 +6,21 @@
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: Web授权异常处理器
        * @Param:
        * @return:
        * @Author: 陈凯裕
        * @Date: 2020/9/16
        */
@RestControllerAdvice
public class WebAuthExceptionHandler {
    @ExceptionHandler(WebAuthException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String,Object> handlerWebAuthException(WebAuthException e){
    public Map<String,Object> handlerWebAuthException(WebAuthException e, HttpServletResponse response){
        Map<String,Object> result = new HashMap<>();
        result.put("msg",e.getMessage());
        result.put("accountId", -1);
src/main/java/com/moral/common/interceptor/WebInterceptor.java
@@ -7,6 +7,8 @@
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.moral.common.exception.WebAuthException;
import com.moral.common.util.RedisHashUtil;
import com.moral.common.util.WebTokenUtils;
import com.moral.common.webAnno.PassToken;
import com.moral.common.webAnno.UserLoginToken;
import com.moral.entity.Account;
@@ -35,13 +37,15 @@
    @Resource
    AccountService accountService;
    @Resource
    RedisHashUtil redisHashUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        String token = request.getHeader("token");
        Enumeration<String> headerNames = request.getHeaderNames();
        //如果不是映射到方法则直接通过
        if(!(o instanceof HandlerMethod)){
            return true;
@@ -68,9 +72,7 @@
                //获取ID
                String id = "";
                try {
                    Map<String, Claim> claims = JWT.decode(token).getClaims();
                    Claim accountId = claims.get("aid");
                    id = accountId.asString();
                    id = WebTokenUtils.getIdBytoken(token);
                }catch (JWTDecodeException e){
                    throw new WebAuthException("401,token无效");
                }
@@ -90,6 +92,11 @@
                    throw new WebAuthException("401,token过期或者无效");
                }
                //判断token是否在退出黑名单
                String redisToken = (String)redisHashUtil.getMapVal("webToken",id);
                if(token.equals(redisToken))
                    throw new WebAuthException("401,token过期");
                return true;
            }
        }
src/main/java/com/moral/common/util/RedisHashUtil.java
New file
@@ -0,0 +1,124 @@
package com.moral.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.*;
@Repository
public class RedisHashUtil {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 存储单个值至map中
     * @param redisKey redisKey中的key
     * @param mapKey  map所对应的key
     * @param value map所对应的值
     */
    public void addMapOne(String redisKey,String mapKey,Object value) {
        redisTemplate.opsForHash().put(redisKey, mapKey,value);
    }
    /**
     * 存储整个map至redis
     * @param key redis中存储的key
     * @param map 需缓存的Map
     */
    public void addMapAll(String key, Map map) {
        redisTemplate.opsForHash().putAll(key, map);
    }
    /**
     * 获取整个HashMap
     * @param redisKey redis中存储的key
     * @return 整个Map
     */
    public Map<String,Object> getMapAll(String redisKey) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(redisKey);
        Map<String, Object> retEntries = new HashMap<>();
        for(Map.Entry<Object , Object> temp:entries.entrySet()){
            Object key = temp.getKey();
            Object value = temp.getValue();
            retEntries.put(String.valueOf(key) , value);
        }
        return retEntries;
    }
    /**
     * 获取redis中hash的所有value
     * @param redisKey
     * @return
     */
    public List<Object> getMapValues(String redisKey) {
        return redisTemplate.opsForHash().values(redisKey);
    }
    /**
     * 删除Map中的某个键值对
     * @param redisKey
     * @param mapKey
     * @return 返回影响数量
     */
    public Long deleteMapVal(String redisKey , Object ... mapKey) {
        return redisTemplate.opsForHash().delete(redisKey , mapKey);
    }
    /**
     * 确定hashkey是否存在
     * @param redisKey redis存储的key
     * @param mapKey 需要确定的map对象key
     * @return
     */
    public boolean hasKey(String redisKey , String mapKey) {
        return    redisTemplate.opsForHash().hasKey(redisKey , mapKey);
    }
    /**
     * 获取Map中具体的值
     * @param redisKey redis存储的key
     * @param mapKey 获取的map对象key
     * @return
     */
    public Object getMapVal(String redisKey, String mapKey) {
        return redisTemplate.opsForHash().get(redisKey,mapKey);
    }
    /**
     * 从哈希中获取给定key的值
     * @param redisKey redis存储的key
     * @param mapKeys 需要去出的key的集合
     * @return 值列表
     */
    public List<Object> multiGetHash(String redisKey , List<Object> mapKeys) {
        return  redisTemplate.opsForHash().multiGet(redisKey , mapKeys);
    }
    /**
     * 获取所有map中的key
     * @param redisKey
     * @return
     */
    public Set<String> getHashKeys(String redisKey) {
        Set<Object> keys = redisTemplate.opsForHash().keys(redisKey);
        Set<String> retKeys = new HashSet<>();
        for (Object key : keys) {
            retKeys.add(String.valueOf(key));
        }
        return retKeys;
    }
    /**
     * 获取所有map中的key的数量
     * @param redisKey redis中的key
     * @return key的数量
     */
    public int getHashSize(String redisKey) {
        Set<Object> keys = redisTemplate.opsForHash().keys(redisKey);
        if(keys == null){
            return 0;
        }
        return keys.size();
    }
}
src/main/java/com/moral/common/util/WebTokenUtils.java
New file
@@ -0,0 +1,15 @@
package com.moral.common.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import java.util.Map;
public class WebTokenUtils {
    public static final String getIdBytoken(String token){
        Map<String, Claim> claims = JWT.decode(token).getClaims();
        Claim accountId = claims.get("aid");
        return accountId.asString();
    }
}
src/main/java/com/moral/controller/WebController.java
@@ -1,6 +1,10 @@
package com.moral.controller;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.moral.common.exception.WebAuthException;
import com.moral.common.util.BeanUtils;
import com.moral.common.util.RedisHashUtil;
import com.moral.common.util.WebTokenUtils;
import com.moral.common.webAnno.UserLoginToken;
import com.moral.entity.AreaNames;
import com.moral.entity.Organization;
@@ -8,13 +12,13 @@
import com.moral.service.DictionaryDataService;
import com.moral.service.OrganizationService;
import com.moral.service.WebTokenService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.moral.util.LatLngTransformation;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -34,11 +38,99 @@
    OrganizationService organizationService;
    @Resource
    WebTokenService webTokenService;
    @Resource
    RedisHashUtil redisHashUtil;
    @RequestMapping("login")
    public Map<String, Object> login(HttpServletRequest request){
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        if (!(parameters.containsKey("account") && parameters.containsKey("password"))) {
            resultMap.put("msg", "用户名及密码不允许为空!");
            resultMap.put("accountId", -1);
        } else {
            resultMap = accountService.webLogin(parameters);
            String accountId = String.valueOf(resultMap.get("accountId"));
            if (!accountId.equals("-1")) {
                redisHashUtil.deleteMapVal("webToken",accountId);
                resultMap.put("token", webTokenService.getToken(accountId));
            }
        }
        return resultMap;
    }
    @UserLoginToken
    @PostMapping("logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = request.getHeader("token");
        String id =  WebTokenUtils.getIdBytoken(token);
        redisHashUtil.addMapOne("webToken", String.valueOf(id),token);
        resultMap.put("msg", "退出成功!");
        return resultMap;
    }
    @UserLoginToken
    @GetMapping("getAccountInfo")
    public Map<String, Object> getAccountInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        String id = "";
        try {
            id = WebTokenUtils.getIdBytoken(token);
        } catch (JWTDecodeException e) {
            throw new WebAuthException("401,token无效");
        }
        Map<String, Object> resultMap = accountService.getAccountInfoById(id);
        Object orgId = resultMap.get("orgId");
        if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
            StringBuilder areaNamesBuilder = new StringBuilder("中国");
            //判断是否为本公司开发者
            if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                //不是本公司开发者则获取用户所属地区
                Organization organization = organizationService.getOrganizationById((Integer) orgId);
                if (organization.getAreaNames() != null) {
                    Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
                    List<String> names = areaNameMap.entrySet().stream().filter(item -> {
                        return item.getValue() != null;
                    }).map(item -> {
                        return item.getValue();
                    }).collect(Collectors.toList());
                    AreaNames areaNames = organization.getAreaNames();
                    areaNamesBuilder.append("/");
                    areaNamesBuilder.append(String.join("/", names));
                }
                // 企业用户
                if (organization.getRank() != null && organization.getRank() == 0) {
                    resultMap.put("type", "enterprise");
                } else {
                    resultMap.put("type", "government");
                }
                Number mapAreaCode = null;
                if (organization.getVillageCode() != null) {
                    mapAreaCode = organization.getVillageCode();
                } else if (organization.getTownCode() != null) {
                    mapAreaCode = organization.getTownCode();
                } else if (organization.getAreaCode() != null) {
                    mapAreaCode = organization.getAreaCode();
                } else if (organization.getCityCode() != null) {
                    mapAreaCode = organization.getCityCode();
                } else if (organization.getProvinceCode() != null) {
                    mapAreaCode = organization.getProvinceCode();
                }
                resultMap.put("mapAreaCode", mapAreaCode.toString());
            }
            resultMap.put("mapPath", areaNamesBuilder.toString());
            String accountId = String.valueOf(resultMap.get("accountId"));
            resultMap.put("token", webTokenService.getToken(accountId));
        }
        return resultMap;
    }
    //弃用
    @UserLoginToken
    @RequestMapping("getAccountInfoTest")
    public Map<String, Object> getAccountInfoTest(@RequestBody Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        System.out.println(parameters);
        if (!(parameters.containsKey("account") && parameters.containsKey("password"))) {
            resultMap.put("msg", "用户名及密码不允许为空!");
            resultMap.put("accountId", -1);
@@ -84,8 +176,8 @@
                    resultMap.put("mapAreaCode", mapAreaCode.toString());
                }
                resultMap.put("mapPath", areaNamesBuilder.toString());
                String accountId= String.valueOf(resultMap.get("accountId"));
                resultMap.put("token",webTokenService.getToken(accountId));
                String accountId = String.valueOf(resultMap.get("accountId"));
                resultMap.put("token", webTokenService.getToken(accountId));
            }
        }
        return resultMap;
@@ -93,7 +185,7 @@
    @UserLoginToken
    @GetMapping("test")
    public String add(){
    public String add() {
        return "test success!";
    }
}
src/main/java/com/moral/service/AccountService.java
@@ -37,4 +37,8 @@
    List<Role> getRolesByAccountName(String accountName);
    Map<String, Object> getMenuListsByAccountName(String accountName);
    Map<String, Object> webLogin(Map<String, Object> parameters);
    Map<String, Object> getAccountInfoById(String accountId);
}
src/main/java/com/moral/service/impl/AccountServiceImpl.java
@@ -57,29 +57,48 @@
    @Resource
    private OrganizationMapper organizationMapper;
    @Override
    public Map<String, Object> screenLogin(Map<String, Object> parameters) {
    public Map<String, Object> getAccountInfoById(String accountId) {
        Map<String, Object> result = new HashMap<String, Object>();
        Account account = new Account();
        account.setAccountName((String) parameters.get("account"));
        String rawPassword = (String) parameters.get("password");
//        account.setPassword(encoder.encode((String) parameters.get("password")));
        account.setId(Integer.parseInt(accountId));
        account = accountMapper.selectOne(account);
        boolean isValid = account == null ? false : encoder.matches(rawPassword, account.getPassword());
        if (!isValid) {
            result.put("msg", "用户名及密码输入错误!");
        if (ObjectUtils.isEmpty(account)) {
            result.put("msg", "token无效");
            result.put("accountId", -1);
        } else {
            if (IS_DELETE_FALSE.equals(account.getIsDelete())) {
                result.put("msg", "登录成功!");
            result = judgeAccountInfo(account);
            if (!String.valueOf(result.get("accountId")).equals("-1")) {
                List<Menu> menuList = accountMapper.getScreenMenuListsByAccountName(account.getAccountName());
                result.put("msg", "获取成功!");
                result.put("accountId", account.getId());
                result.put("orgId", account.getOrganizationId());
                result.put("data", menuList);
                setOrgIdsByAccount(result);
            } else {
                result.put("msg", "您的账号已禁用,请联系管理员!");
            }
        }
        return result;
    }
    @Override
    public Map<String, Object> webLogin(Map<String, Object> parameters) {
        Map<String, Object> result = new HashMap<String, Object>();
        Account account = new Account();
        account.setAccountName((String) parameters.get("account"));
        String rawPassword = (String) parameters.get("password");
        account = accountMapper.selectOne(account);
        boolean isValid = account == null ? false : encoder.matches(rawPassword, account.getPassword());
        if (!isValid) {
            result.put("msg", "用户名及密码输入错误!");
            result.put("accountId", -1);
        } else {
            result = judgeAccountInfo(account);
        }
        return result;
    }
    @Override
    public Map<String, Object> screenLoginNew(Map<String, Object> parameters) {
@@ -98,6 +117,7 @@
        boolean isValid = account == null ? false : encoder.matches(rawPassword, account.getPassword());
        if (!isValid) {
            result.put("msg", "用户名及密码输入错误!");
            result.put("accountId", -1);
        } else {
            if (IS_DELETE_FALSE.equals(account.getIsDelete())) {
                if (existRole != null) {
@@ -109,6 +129,30 @@
                } else {
                    result.put("msg", "账户没有权限!");
                }
            } else {
                result.put("msg", "您的账号已禁用,请联系管理员!");
            }
        }
        return result;
    }
    @Override
    public Map<String, Object> screenLogin(Map<String, Object> parameters) {
        Map<String, Object> result = new HashMap<String, Object>();
        Account account = new Account();
        account.setAccountName((String) parameters.get("account"));
        String rawPassword = (String) parameters.get("password");
//        account.setPassword(encoder.encode((String) parameters.get("password")));
        account = accountMapper.selectOne(account);
        boolean isValid = account == null ? false : encoder.matches(rawPassword, account.getPassword());
        if (!isValid) {
            result.put("msg", "用户名及密码输入错误!");
        } else {
            if (IS_DELETE_FALSE.equals(account.getIsDelete())) {
                result.put("msg", "登录成功!");
                result.put("accountId", account.getId());
                result.put("orgId", account.getOrganizationId());
                setOrgIdsByAccount(result);
            } else {
                result.put("msg", "您的账号已禁用,请联系管理员!");
            }
@@ -322,4 +366,21 @@
        return mapList;
    }
    private Map<String, Object> judgeAccountInfo(Account account) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer existRole = accountMapper.getScreenRoleByAccountName(account.getAccountName());
        if (!IS_DELETE_FALSE.equals(account.getIsDelete())) {
            result.put("msg", "您的账号已禁用,请联系管理员!");
            result.put("accountId", -1);
        } else if (ObjectUtils.isEmpty(existRole)) {
            result.put("msg", "账户没有权限!");
            result.put("accountId", -1);
        } else {
            result.put("msg", "登录成功!");
            result.put("accountId", account.getId());
        }
        return result;
    }
}
src/main/resources/application.yml
@@ -65,6 +65,7 @@
      min-idle: 0
#  data:
#    mongodb:
#      uri: mongodb://47.96.171.62:27017/monitor