Commit ab2aed47 by stylefeng

从新整理项目

parent 279d45e8
package com.stylefeng.guns.rest.common.aop;
import com.stylefeng.guns.core.aop.BaseControllerExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
/**
* 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
*
* @author fengshuonan
* @date 2016年11月12日 下午3:19:56
*/
@ControllerAdvice
public class GlobalExceptionHandler extends BaseControllerExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
}
package com.stylefeng.guns.rest.common.exception;
/**
* 所有业务异常的枚举
*
* @author fengshuonan
* @date 2016年11月12日 下午5:04:51
*/
public enum BizExceptionEnum {
AUTH_REQUEST_ERROR(701, "auth请求验证失败"),
AUTH_ERROR(702, "签名错误,请求失败"),
SERVER_ERROR(802, "服务器错误");
BizExceptionEnum(int code, String message) {
this.friendlyCode = code;
this.friendlyMsg = message;
}
private int friendlyCode;
private String friendlyMsg;
public int getCode() {
return friendlyCode;
}
public void setCode(int code) {
this.friendlyCode = code;
}
public String getMessage() {
return friendlyMsg;
}
public void setMessage(String message) {
this.friendlyMsg = message;
}
}
package com.stylefeng.guns.rest.common.exception;
import com.stylefeng.guns.core.exception.GunsException;
/**
* @author fengshuonan
* @Description 业务异常的封装
* @date 2016年11月12日 下午5:05:10
*/
public class BussinessException extends GunsException {
public BussinessException(BizExceptionEnum bizExceptionEnum) {
super(bizExceptionEnum.getCode(), bizExceptionEnum.getMessage(),"");
}
}
package com.stylefeng.guns.rest.persistence.dao; package com.stylefeng.guns.rest.common.persistence.dao;
import com.stylefeng.guns.rest.persistence.model.User;
import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.stylefeng.guns.rest.common.persistence.model.User;
/** /**
* <p> * <p>
......
<?xml version="1.0" encoding="UTF-8"?> <?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"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.stylefeng.guns.rest.persistence.dao.UserMapper"> <mapper namespace="com.stylefeng.guns.rest.common.persistence.dao.UserMapper">
<!-- 通用查询映射结果 --> <!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.stylefeng.guns.rest.persistence.model.User"> <resultMap id="BaseResultMap" type="com.stylefeng.guns.rest.common.persistence.model.User">
<id column="id" property="id" /> <id column="id" property="id" />
<result column="userName" property="userName" /> <result column="userName" property="userName" />
</resultMap> </resultMap>
......
package com.stylefeng.guns.rest.persistence.model; package com.stylefeng.guns.rest.common.persistence.model;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.activerecord.Model;
import java.io.Serializable; import java.io.Serializable;
/** /**
......
package com.stylefeng.guns.rest.config; package com.stylefeng.guns.rest.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.stylefeng.guns.rest.config.properties.DruidProperties;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -15,29 +12,9 @@ import org.springframework.context.annotation.Configuration; ...@@ -15,29 +12,9 @@ import org.springframework.context.annotation.Configuration;
* @Date 2017年8月23日12:51:41 * @Date 2017年8月23日12:51:41
*/ */
@Configuration @Configuration
@MapperScan(basePackages = {"com.stylefeng.guns.rest.*.dao", "com.stylefeng.guns.rest.persistence.dao"}) @MapperScan(basePackages = {"com.stylefeng.guns.rest.*.dao", "com.stylefeng.guns.rest.common.persistence.dao"})
public class MybatisPlusConfig { public class MybatisPlusConfig {
@Autowired
DruidProperties druidProperties;
/**
* guns的数据源
*/
private DruidDataSource dataSourceGuns() {
DruidDataSource dataSource = new DruidDataSource();
druidProperties.config(dataSource);
return dataSource;
}
/**
* 单数据源连接池配置
*/
@Bean
public DruidDataSource singleDatasource() {
return dataSourceGuns();
}
/** /**
* mybatis-plus分页插件 * mybatis-plus分页插件
*/ */
......
package com.stylefeng.guns.rest.config; package com.stylefeng.guns.rest.config;
import com.stylefeng.guns.rest.filter.JwtAuthenticationTokenFilter; import com.stylefeng.guns.rest.modular.auth.filter.AuthFilter;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -14,7 +14,7 @@ import org.springframework.context.annotation.Configuration; ...@@ -14,7 +14,7 @@ import org.springframework.context.annotation.Configuration;
public class WebConfig { public class WebConfig {
@Bean @Bean
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { public AuthFilter jwtAuthenticationTokenFilter() {
return new JwtAuthenticationTokenFilter(); return new AuthFilter();
} }
} }
package com.stylefeng.guns.rest.config.properties;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
* <p>数据库数据源配置</p>
* <p>说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可</p>
* @author fengshuonan
* @date 2017-05-21 11:18
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {
private String url = "jdbc:mysql://127.0.0.1:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
private String username = "root";
private String password = "root";
private String driverClassName = "com.mysql.jdbc.Driver";
private Integer initialSize = 2;
private Integer minIdle = 1;
private Integer maxActive = 20;
private Integer maxWait = 60000;
private Integer timeBetweenEvictionRunsMillis = 60000;
private Integer minEvictableIdleTimeMillis = 300000;
private String validationQuery = "SELECT 'x'";
private Boolean testWhileIdle = true;
private Boolean testOnBorrow = false;
private Boolean testOnReturn = false;
private Boolean poolPreparedStatements = true;
private Integer maxPoolPreparedStatementPerConnectionSize = 20;
private String filters = "stat";
public void config(DruidDataSource dataSource) {
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setInitialSize(initialSize); //定义初始连接数
dataSource.setMinIdle(minIdle); //最小空闲
dataSource.setMaxActive(maxActive); //定义最大连接数
dataSource.setMaxWait(maxWait); //最长等待时间
// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 配置一个连接在池中最小生存的时间,单位是毫秒
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
// 打开PSCache,并且指定每个连接上PSCache的大小
dataSource.setPoolPreparedStatements(poolPreparedStatements);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
dataSource.setFilters(filters);
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
package com.stylefeng.guns.rest.controller; package com.stylefeng.guns.rest.modular.auth.controller;
import com.stylefeng.guns.rest.auth.JwtTokenUtil; import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.config.properties.JwtProperties; import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.service.IReqValidator; import com.stylefeng.guns.rest.modular.auth.controller.dto.AuthResponse;
import com.stylefeng.guns.rest.transfer.JwtAuthenticationResponse; import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.auth.validator.IReqValidator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device; import org.springframework.mobile.device.Device;
...@@ -15,11 +16,14 @@ import javax.annotation.Resource; ...@@ -15,11 +16,14 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Map; import java.util.Map;
/**
* 请求验证的
*
* @author fengshuonan
* @Date 2017/8/24 14:22
*/
@RestController @RestController
public class AuthenticationRestController { public class AuthController {
@Autowired
private JwtProperties jwtProperties;
@Autowired @Autowired
private JwtTokenUtil jwtTokenUtil; private JwtTokenUtil jwtTokenUtil;
...@@ -34,9 +38,10 @@ public class AuthenticationRestController { ...@@ -34,9 +38,10 @@ public class AuthenticationRestController {
if (validate) { if (validate) {
final String token = jwtTokenUtil.generateToken((String) params.get("userName"), device); final String token = jwtTokenUtil.generateToken((String) params.get("userName"), device);
return ResponseEntity.ok(new JwtAuthenticationResponse(token)); final String randomKey = jwtTokenUtil.getRandomKey();
return ResponseEntity.ok(new AuthResponse(token, randomKey));
} else { } else {
return ResponseEntity.status(400).body("UserName or password is not right!"); throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
} }
} }
} }
package com.stylefeng.guns.rest.transfer; package com.stylefeng.guns.rest.modular.auth.controller.dto;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Created by stephan on 20.03.16. * 认证的请求dto
*
* @author fengshuonan
* @Date 2017/8/24 14:00
*/ */
public class JwtAuthenticationRequest implements Serializable { public class AuthRequest implements Serializable {
private static final long serialVersionUID = -8445943548965154778L; private static final long serialVersionUID = -8445943548965154778L;
private String username; private String username;
private String password; private String password;
public JwtAuthenticationRequest() { public AuthRequest() {
super(); super();
} }
public JwtAuthenticationRequest(String username, String password) { public AuthRequest(String username, String password) {
this.setUsername(username); this.setUsername(username);
this.setPassword(password); this.setPassword(password);
} }
......
package com.stylefeng.guns.rest.transfer; package com.stylefeng.guns.rest.modular.auth.controller.dto;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Created by stephan on 20.03.16. * 认证的响应结果
*
* @author fengshuonan
* @Date 2017/8/24 13:58
*/ */
public class JwtAuthenticationResponse implements Serializable { public class AuthResponse implements Serializable {
private static final long serialVersionUID = 1250166508152483573L; private static final long serialVersionUID = 1250166508152483573L;
/**
* jwt token
*/
private final String token; private final String token;
public JwtAuthenticationResponse(String token) { /**
* 用于客户端混淆md5加密
*/
private final String randomKey;
public AuthResponse(String token, String randomKey) {
this.token = token; this.token = token;
this.randomKey = randomKey;
} }
public String getToken() { public String getToken() {
return this.token; return this.token;
} }
public String getRandomKey() {
return randomKey;
}
} }
package com.stylefeng.guns.rest.filter; package com.stylefeng.guns.rest.modular.auth.filter;
import com.stylefeng.guns.rest.auth.JwtTokenUtil; import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.config.properties.JwtProperties; import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -13,7 +15,13 @@ import javax.servlet.http.HttpServletRequest; ...@@ -13,7 +15,13 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { /**
* 对客户端请求的jwt token验证过滤器
*
* @author fengshuonan
* @Date 2017/8/24 14:04
*/
public class AuthFilter extends OncePerRequestFilter {
private final Log logger = LogFactory.getLog(this.getClass()); private final Log logger = LogFactory.getLog(this.getClass());
...@@ -36,11 +44,11 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { ...@@ -36,11 +44,11 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
boolean flag = jwtTokenUtil.validateToken(authToken); boolean flag = jwtTokenUtil.validateToken(authToken);
if (!flag) { if (!flag) {
logger.error("token验证错误"); logger.error("token验证错误");
throw new RuntimeException("token验证错误"); throw new BussinessException(BizExceptionEnum.AUTH_ERROR);
} }
} else { } else {
logger.warn("错误的header"); logger.warn("错误的header");
throw new RuntimeException("错误的header"); throw new BussinessException(BizExceptionEnum.AUTH_ERROR);
} }
chain.doFilter(request, response); chain.doFilter(request, response);
} }
......
package com.stylefeng.guns.rest.auth; package com.stylefeng.guns.rest.modular.auth.util;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.rest.config.properties.JwtProperties; import com.stylefeng.guns.rest.config.properties.JwtProperties;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException; import io.jsonwebtoken.JwtException;
...@@ -144,4 +145,8 @@ public class JwtTokenUtil implements Serializable { ...@@ -144,4 +145,8 @@ public class JwtTokenUtil implements Serializable {
username.equals(userName) username.equals(userName)
&& !isTokenExpired(token)); && !isTokenExpired(token));
} }
public String getRandomKey(){
return ToolUtil.getRandomString(6);
}
} }
\ No newline at end of file
package com.stylefeng.guns.rest.service; package com.stylefeng.guns.rest.modular.auth.validator;
import java.util.Map; import java.util.Map;
......
package com.stylefeng.guns.rest.service.impl; package com.stylefeng.guns.rest.modular.auth.validator.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.persistence.dao.UserMapper; import com.stylefeng.guns.rest.common.persistence.dao.UserMapper;
import com.stylefeng.guns.rest.persistence.model.User; import com.stylefeng.guns.rest.common.persistence.model.User;
import com.stylefeng.guns.rest.service.IReqValidator; import com.stylefeng.guns.rest.modular.auth.validator.IReqValidator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
......
package com.stylefeng.guns.rest.service.impl; package com.stylefeng.guns.rest.modular.auth.validator.impl;
import com.stylefeng.guns.rest.service.IReqValidator; import com.stylefeng.guns.rest.modular.auth.validator.IReqValidator;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Map; import java.util.Map;
......
package com.stylefeng.guns.rest.controller; package com.stylefeng.guns.rest.modular.example;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
*/ */
@Controller @Controller
@RequestMapping("/hello") @RequestMapping("/hello")
public class NormalController { public class ExampleController {
@RequestMapping("") @RequestMapping("")
public ResponseEntity hello() { public ResponseEntity hello() {
......
...@@ -6,7 +6,7 @@ jwt: ...@@ -6,7 +6,7 @@ jwt:
mybatis-plus: mybatis-plus:
mapper-locations: classpath*:com/stylefeng/guns/rest/**/mapping/*.xml mapper-locations: classpath*:com/stylefeng/guns/rest/**/mapping/*.xml
typeAliasesPackage: com.stylefeng.guns.rest.persistence.model typeAliasesPackage: com.stylefeng.guns.rest.common.persistence.model
global-config: global-config:
id-type: 0 #0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid) id-type: 0 #0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid)
db-column-underline: false db-column-underline: false
......
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