Commit 67b7c94b authored by Fred's avatar Fred

集成数据字典

parent 33914b41
package com.govmade.common.exception;
/**
* 自定义异常
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月6日
*/
public class RRException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public RRException(String msg) {
super(msg);
this.msg = msg;
}
public RRException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
package com.govmade.common.exception;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.govmade.common.utils.R;
/**
* 异常处理器
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月6日
*/
@RestControllerAdvice
public class RRExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 处理自定义异常
*/
@ExceptionHandler(RRException.class)
public R handleRRException(RRException e){
R r = new R();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
}
@ExceptionHandler(DuplicateKeyException.class)
public R handleDuplicateKeyException(DuplicateKeyException e){
logger.error(e.getMessage(), e);
return R.error("数据库中已存在该记录");
}
@ExceptionHandler(AuthorizationException.class)
public R handleAuthorizationException(AuthorizationException e){
logger.error(e.getMessage(), e);
return R.error("没有权限,请联系管理员授权");
}
@ExceptionHandler(Exception.class)
public R handleException(Exception e){
logger.error(e.getMessage(), e);
return R.error();
}
}
package com.govmade.common.oauth2;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;
import com.govmade.common.utils.HttpContextUtils;
import com.govmade.common.utils.R;
import cn.hutool.json.JSONUtil;
/**
* token
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017-05-20 13:22
*/
public class OAuth2Filter extends AuthenticatingFilter {
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
// 获取请求token
String token = getRequestToken((HttpServletRequest) request);
if (StringUtils.isBlank(token)) {
return null;
}
return new OAuth2Token(token);
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
return true;
}
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
// 获取请求token,如果token不存在,直接返回401
String token = getRequestToken((HttpServletRequest) request);
if (StringUtils.isBlank(token)) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
String json = JSONUtil.toJsonStr(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
httpResponse.getWriter().print(json);
return false;
}
return executeLogin(request, response);
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
ServletResponse response) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
try {
// 处理登录失败的异常
Throwable throwable = e.getCause() == null ? e : e.getCause();
R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());
String json = JSONUtil.toJsonStr(r);
httpResponse.getWriter().print(json);
} catch (IOException e1) {
}
return false;
}
/**
* 获取请求的token
*/
private String getRequestToken(HttpServletRequest httpRequest) {
// 从header中获取token
String token = httpRequest.getHeader("token");
// 如果header中不存在token,则从参数中获取token
if (StringUtils.isBlank(token)) {
token = httpRequest.getParameter("token");
}
return token;
}
}
package com.govmade.common.oauth2;
import java.util.Map;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.collect.Maps;
import com.govmade.common.utils.Constant;
import com.govmade.modules.system.entity.UserEntity;
import com.govmade.modules.system.service.UserService;
/**
* 认证
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月6日
*/
@Component
public class OAuth2Realm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 授权(验证权限时调用)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
UserEntity ue = (UserEntity) principals.getPrimaryPrincipal();
Long userId = ue.getId();
// 用户权限列表
// Set<String> permsSet = shiroService.getUserPermissions(userId);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.setStringPermissions(permsSet);
return info;
}
/**
* 认证(登录时调用)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
Map<String, Object> params = Maps.newHashMap();
params.put("username", username);
UserEntity ue = userService.queryOne(params);
// 账号不存在
if (null == ue) {
throw new UnknownAccountException("账号或密码不正确");
}
// 密码错误
if (!password.equals(ue.getPassword())) {
throw new IncorrectCredentialsException("账号或密码不正确");
}
// 账号锁定
if (Constant.DeleteState.DELETE.getValue() == ue.getState()) {
throw new LockedAccountException("账号已被锁定,请联系管理员");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(ue, username, getName());
return info;
}
}
package com.govmade.common.oauth2;
import org.apache.shiro.authc.AuthenticationToken;
/**
* token
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017-05-20 13:22
*/
public class OAuth2Token implements AuthenticationToken {
private String token;
public OAuth2Token(String token){
this.token = token;
}
@Override
public String getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
package com.govmade.common.oauth2;
import java.security.MessageDigest;
import java.util.UUID;
import com.govmade.common.exception.RRException;
/**
* 生成token
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017-05-20 14:41
*/
public class TokenGenerator {
public static String generateValue() {
return generateValue(UUID.randomUUID().toString());
}
private static final char[] hexCode = "0123456789abcdef".toCharArray();
public static String toHexString(byte[] data) {
if(data == null) {
return null;
}
StringBuilder r = new StringBuilder(data.length*2);
for ( byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public static String generateValue(String param) {
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(param.getBytes());
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
} catch (Exception e) {
throw new RRException("生成Token失败", e);
}
}
}
......@@ -33,9 +33,34 @@ public class Constant {
*/
BUTTON(2);
private int value;
private Integer value;
MenuType(int value) {
MenuType(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
}
/**
* 删除状态
*
*/
public enum DeleteState {
/**
* 删除
*/
DELETE(0),
/**
* 正常
*/
NORMAL(1);
private Integer value;
private DeleteState(Integer value) {
this.value = value;
}
......
package com.govmade.common.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getDomain(){
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
}
public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
}
......@@ -68,4 +68,12 @@ public abstract class BaseEntity<ID extends Serializable> implements Serializabl
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
package com.govmade.modules.system.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.govmade.common.utils.Constant;
import com.govmade.common.utils.PageUtils;
import com.govmade.common.utils.R;
import com.govmade.modules.basic.controller.AbstractController;
import com.govmade.modules.system.entity.DictEntity;
import com.govmade.modules.system.service.DictService;
import com.govmade.modules.system.service.UserService;
/**
* 系统管理 - 字典设置
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月7日
*/
@RestController
@RequestMapping("/system/dict")
public class DictController extends AbstractController {
@Autowired
private DictService dictService;
/**
* 用户列表
*/
@GetMapping("/list")
public R list(Map<String, Object> params) {
List<DictEntity> dictList = dictService.queryChilds("city_level");
return R.ok().put("childs", dictList);
}
}
......@@ -55,10 +55,10 @@ public class UserController extends AbstractController {
public R list(Map<String, Object> params) {
// 只有超级管理员,才能查看所有用户列表
if (getUserId() != Constant.SUPER_ADMIN) {
if (getUserId() == Constant.SUPER_ADMIN) {
params.put("createBy", getUserId());
} else {
params.put("deptId", getUser().getDeptId()); // 部门管理员,查看本部门用户列表
//params.put("deptId", getUser().getDeptId()); // 部门管理员,查看本部门用户列表
}
PageUtils page = userService.queryPage(params);
......
package com.govmade.modules.system.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.govmade.modules.system.entity.DictEntity;
/**
* 系统管理 - 字典设置
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月7日
*/
@Mapper
public interface DictDao extends BaseMapper<DictEntity> {
List<DictEntity> selectChilds(@Param("pValue") String pValue);
}
package com.govmade.modules.system.entity;
import com.baomidou.mybatisplus.annotations.TableName;
import com.govmade.modules.basic.entity.BaseEntity;
/**
* 系统管理 -
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月7日
*/
@TableName("system_dicts")
public class DictEntity extends BaseEntity<Long> {
private static final long serialVersionUID = 1L;
private Long pid; // 父级ID
private String name; // 字典名
private String value; // 字典值
private Integer type; // 类型
private Integer weight; // 权重
private String remark; // 备注
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
package com.govmade.modules.system.service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.service.IService;
import com.govmade.common.utils.PageUtils;
import com.govmade.modules.system.entity.DictEntity;
import com.govmade.modules.system.entity.UserEntity;
/**
* 系统管理 - 字典设置
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月7日
*/
public interface DictService extends IService<DictEntity> {
PageUtils queryPage(Map<String, Object> params);
DictEntity queryOne(Map<String, Object> params);
List<DictEntity> queryChilds(String value);
}
......@@ -39,4 +39,6 @@ public interface UserService extends IService<UserEntity> {
boolean updatePassword(Long userId, String password, String newPassword);
Integer checkUser(String username);
UserEntity queryOne(Map<String, Object> params);
}
package com.govmade.modules.system.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.govmade.common.utils.PageUtils;
import com.govmade.common.utils.Query;
import com.govmade.modules.system.dao.DictDao;
import com.govmade.modules.system.entity.DictEntity;
import com.govmade.modules.system.service.DictService;
import cn.hutool.core.util.StrUtil;
/**
* 系统管理 - 字典设置
*
* @author Fred
* @email fangtaosh@qq.com
* @date 2018年8月7日
*/
@Service("DictService")
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
// TODO Auto-generated method stub
String username = (String) params.get("username");
Long createBy = (Long) params.get("createBy");
Page<DictEntity> page = this.selectPage(new Query<DictEntity>(params).getPage(), new EntityWrapper<DictEntity>()
.eq(StrUtil.isNotBlank(username), "username", username).eq(createBy != null, "create_by", createBy));
return new PageUtils(page);
}
@Override
public DictEntity queryOne(Map<String, Object> params) {
String value = (String) params.get("value");
return (DictEntity) this
.selectOne(new EntityWrapper<DictEntity>().eq(StrUtil.isNotBlank(value), "value", value));
}
@Override
public List<DictEntity> queryChilds(String pValue) {
List<DictEntity> childs = baseMapper.selectChilds(pValue);
return childs;
}
}
......@@ -32,7 +32,7 @@ public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements
Long createBy = (Long) params.get("createBy");
Page<UserEntity> page = this.selectPage(new Query<UserEntity>(params).getPage(), new EntityWrapper<UserEntity>()
.eq(StrUtil.isNotBlank(username), "username", username).eq(createBy != null, "create_by", createBy));
.like(StrUtil.isNotBlank(username), "username", username).eq(createBy != null, "create_by", createBy));
return new PageUtils(page);
}
......@@ -62,4 +62,11 @@ public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements
public Integer checkUser(String username) {
return super.selectCount(new EntityWrapper<UserEntity>().eq("username", username));
}
@Override
public UserEntity queryOne(Map<String, Object> params) {
String username = (String) params.get("username");
return (UserEntity) this
.selectOne(new EntityWrapper<UserEntity>().eq(StrUtil.isNotBlank(username), "username", username));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.govmade.modules.system.dao.DictDao">
<select id="selectChilds" resultType="DictEntity">
select value,name from
system_dicts where pid = (select id from system_dicts where value = #{pValue})
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.renren.modules.sys.dao.SysUserDao">
<mapper namespace="com.govmade.modules.system.dao.UserDao">
<select id="queryByUserName" resultType="io.renren.modules.sys.entity.SysUserEntity">
<select id="queryByUserName" resultType="UserEntity">
select * from sys_user where username = #{username}
</select>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment