微信API 用户表变更

This commit is contained in:
2023-01-31 14:57:56 +08:00
parent 519ee7b744
commit ae5e9ce31a
18 changed files with 225 additions and 178 deletions

View File

@@ -2,6 +2,8 @@ package com.quinn.common;
public interface QuinnConstant {
String APP_STR = "quInn";
String LINK_SUFFIX = ".";
String LINK_URL = "/";

View File

@@ -10,6 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@@ -18,6 +19,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserServiceImpl userService;
@Autowired
WxTokenFilter wxTokenFilter;
//请求授权验证
@Override
protected void configure(HttpSecurity http) throws Exception {
@@ -39,7 +43,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/blog/**").authenticated()
.antMatchers("/source/**").authenticated()
.antMatchers("/user/**").authenticated()
.antMatchers("/wx/**").authenticated()
.antMatchers("/wx/**").permitAll()
.antMatchers("/*").authenticated();
// 登录配置
@@ -55,6 +59,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
http.headers().frameOptions().disable(); // 图片跨域
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
http.logout().logoutSuccessUrl("/");
http.addFilterBefore(wxTokenFilter, UsernamePasswordAuthenticationFilter.class);
//拦截后使用https 8443 可以装tomcat证书使用
// http.requiresChannel().anyRequest().requiresSecure();

View File

@@ -0,0 +1,29 @@
package com.quinn.config;
import com.quinn.utils.SecurityUtil;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.RemoteException;
@Component
public class WxTokenFilter extends HttpFilter {
private final String TOKEN = "access_token";
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request.getRequestURI().startsWith("/wx/")){
String token = request.getParameter(TOKEN);
// if (!SecurityUtil.checkToken(token)){
// throw new RemoteException("token检验失败");
// }
}
chain.doFilter(request,response);
}
}

View File

@@ -1,110 +0,0 @@
package com.quinn.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quinn.common.EmailType;
import com.quinn.dto.req.QueryTaskListReq;
import com.quinn.dto.req.SearchPage;
import com.quinn.dto.req.SendCode;
import com.quinn.dto.res.AboutDTO;
import com.quinn.dto.res.ResponseDTO;
import com.quinn.intergration.SendBMail;
import com.quinn.pojo.About;
import com.quinn.pojo.Invite;
import com.quinn.service.AboutService;
import com.quinn.service.InviteService;
import com.quinn.utils.QuinnUtils;
import com.quinn.vo.MyPageParam;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author limqsh
* @since 2022-05-01
*/
@RestController("/wx")
public class WxController extends BaseModelController {
@Resource
AboutService aboutService;
@Resource
InviteService inviteService;
@Resource
SendBMail sendBMail;
@PostMapping("about/us")
public ResponseDTO userIndexBlog(SearchPage searchPage){
Page<About> pageParam = new Page<>(searchPage.getPage(), searchPage.getPageSize());
aboutService.page(pageParam,new QueryWrapper<About>().orderByDesc("gmt_create"));
// 结果
List<About> sayList = pageParam.getRecords();
List<AboutDTO> aboutDTOS = new ArrayList<>();
if (!CollectionUtils.isEmpty(sayList)){
sayList.forEach(x->{
AboutDTO aboutDTO = new AboutDTO();
aboutDTO.setId(x.getId());
aboutDTO.setTitle(x.getTitle());
aboutDTO.setContent(x.getContent());
aboutDTO.setGmtCreate(QuinnUtils.getViewStrFromDate(x.getGmtCreate()));
aboutDTOS.add(aboutDTO);
});
}
MyPageParam myPageParam = new MyPageParam(searchPage.getPage(),searchPage.getPageSize());
myPageParam.setTotal((int) pageParam.getTotal());
return ResponseDTO.ok().setPage(myPageParam).setData(aboutDTOS);
}
@PostMapping("send/register/code")
public ResponseDTO sendCode(SendCode sendCode){
Invite email = inviteService.getOne(new QueryWrapper<Invite>().eq("apply_email", sendCode.getEmail()));
if (email != null){
return ResponseDTO.ok().setData("该邮箱已经获取过注册码");
}
String code = inviteService.getCode();
Invite invite = new Invite();
invite.setUid(QuinnUtils.getUuid());
invite.setApplyEmail(sendCode.getEmail());
invite.setCode(code);
invite.setGmtCreate(QuinnUtils.getTime());
inviteService.save(invite);
boolean sendFlag = sendBMail.sendOneParamMail(EmailType.REGISTER,code, sendCode.getEmail());
if (!sendFlag){
return ResponseDTO.ok().setData("发送失败,请确认邮箱是否正确!");
}
return ResponseDTO.ok().setData("success");
}
@PostMapping("about/us")
public ResponseDTO queryTask(QueryTaskListReq queryTaskListReq){
Page<About> pageParam = new Page<>(queryTaskListReq.getPage(), queryTaskListReq.getPageSize());
aboutService.page(pageParam,new QueryWrapper<About>().orderByDesc("gmt_create"));
// 结果
List<About> sayList = pageParam.getRecords();
List<AboutDTO> aboutDTOS = new ArrayList<>();
if (!CollectionUtils.isEmpty(sayList)){
sayList.forEach(x->{
AboutDTO aboutDTO = new AboutDTO();
aboutDTO.setId(x.getId());
aboutDTO.setTitle(x.getTitle());
aboutDTO.setContent(x.getContent());
aboutDTO.setGmtCreate(QuinnUtils.getViewStrFromDate(x.getGmtCreate()));
aboutDTOS.add(aboutDTO);
});
}
MyPageParam myPageParam = new MyPageParam(queryTaskListReq.getPage(),queryTaskListReq.getPageSize());
myPageParam.setTotal((int) pageParam.getTotal());
return ResponseDTO.ok().setPage(myPageParam).setData(aboutDTOS);
}
}

View File

@@ -0,0 +1,35 @@
package com.quinn.controller.wx;
import com.quinn.dto.req.SearchPage;
import com.quinn.dto.res.ResponseDTO;
import com.quinn.service.AccountCheckService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* <p>
* 前端控制器
* </p>
*
* @author limqsh
* @since 2022-05-01
*/
@RestController
@RequestMapping("/wx")
public class WxSettingsController {
@Resource
private AccountCheckService accountCheckService;
@PostMapping("user/login")
public ResponseDTO userIndexBlog(SearchPage searchPage){
ResponseDTO result = ResponseDTO.ok();
result.setData(accountCheckService.getUserId("openid"));
return result;
}
}

View File

@@ -7,6 +7,6 @@ import java.io.Serializable;
@Data
public class BaseReq implements Serializable {
private String userToken;
private String access_token;
}

View File

@@ -1,11 +0,0 @@
package com.quinn.dto.req;
import com.quinn.common.TaskType;
import lombok.Data;
@Data
public class QueryTaskListReq extends SearchPage {
private TaskType taskType;
}

View File

@@ -1,12 +0,0 @@
package com.quinn.dto.req;
import lombok.Data;
import java.io.Serializable;
@Data
public class SendCode implements Serializable {
String email;
}

View File

@@ -1,35 +0,0 @@
package com.quinn.dto.res;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author limqsh
* @since 2022-05-01
*/
@Data
public class AboutDTO implements Serializable {
private String id;
private String title;
private String content;
private String gmtCreate;
}

View File

@@ -51,7 +51,7 @@ public class CodeGenerator {
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("qn_user_message");//设置要映射的表名
strategy.setInclude("qn_user");//设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix("qn_");//设置表前缀不生成

View File

@@ -9,8 +9,10 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
* </p>
*
* @author limqsh
* @since 2020-06-28
* @since 2023-01-30
*/
public interface UserMapper extends BaseMapper<User> {
String getUserByOpenid(String openid);
}

View File

@@ -2,4 +2,8 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.quinn.mapper.UserMapper">
<select id="getUserByOpenid" resultType="string">
SELECT UID FROM QN_USER WHERE OPENID = #{openid}
</select>
</mapper>

View File

@@ -17,7 +17,7 @@ import lombok.experimental.Accessors;
* </p>
*
* @author limqsh
* @since 2020-06-28
* @since 2023-01-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@@ -35,7 +35,7 @@ public class User implements Serializable {
@ApiModelProperty(value = "用户编号")
private String uid;
@ApiModelProperty(value = "角色")
@ApiModelProperty(value = "角色编号")
private String role;
@ApiModelProperty(value = "用户名")
@@ -47,14 +47,17 @@ public class User implements Serializable {
@ApiModelProperty(value = "头像")
private String avatar;
@ApiModelProperty(value = "重置密码钥匙")
private String resetKey;
@ApiModelProperty(value = "登录时间")
private Date loginDate;
@ApiModelProperty(value = "创建时间")
private Date gmtCreate;
@ApiModelProperty(value = "重置密码钥匙")
private String resetKey;
@ApiModelProperty(value = "微信ID")
private String openid;
}

View File

@@ -0,0 +1,15 @@
package com.quinn.service;
/**
* <p>
* 服务类
* </p>
*
* @author limqsh
* @since 2020-06-28
*/
public interface AccountCheckService {
String getUserId(String openid);
}

View File

@@ -9,7 +9,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
* </p>
*
* @author limqsh
* @since 2020-06-28
* @since 2023-01-30
*/
public interface UserService extends IService<User> {

View File

@@ -0,0 +1,42 @@
package com.quinn.service.impl;
import com.quinn.common.RoleType;
import com.quinn.intergration.AttrIcon;
import com.quinn.mapper.UserMapper;
import com.quinn.pojo.User;
import com.quinn.service.AccountCheckService;
import com.quinn.utils.QuinnUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
@Component
public class AccountCheckServiceImpl implements AccountCheckService {
@Resource
UserMapper userMapper;
@Override
public String getUserId(String openid) {
String uid = userMapper.getUserByOpenid(openid);
if (StringUtils.isEmpty(uid)){
// 没有这个用户,需要构建用户对象
User user = new User();
uid = QuinnUtils.getUuid();
user.setUid(uid); // 用户唯一id
user.setRole(RoleType.NORMAL.name());
user.setUsername(uid);
// 密码加密
String bCryptPassword = new BCryptPasswordEncoder().encode("123456");
user.setAvatar(AttrIcon.INSTANCE.generateImgUrl("123456"));
user.setPassword(bCryptPassword);
user.setGmtCreate(QuinnUtils.getTime());
user.setLoginDate(QuinnUtils.getTime());
user.setOpenid(openid);
// 保存对象!
userMapper.insert(user);
}
return uid;
}
}

View File

@@ -1,6 +1,10 @@
package com.quinn.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@@ -9,7 +13,10 @@ import java.util.UUID;
public class QuinnUtils {
private static final Logger log = LoggerFactory.getLogger(QuinnUtils.class);
private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final static SimpleDateFormat sdfm = new SimpleDateFormat( "yyyyMMddHHmmss");
private final static SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMdd");
private final static SimpleDateFormat sdfv = new SimpleDateFormat( "yyyy-MM-dd");
@@ -25,6 +32,10 @@ public class QuinnUtils {
return sdf.format(date);
}
public static String getTokenDate (Date date) {
return sdfm.format(date);
}
public static String getViewStrFromDate(Date date){
return sdfv.format(date);
}
@@ -78,4 +89,18 @@ public class QuinnUtils {
}
}
//计算两个时间相差的秒数
public static long diffSeconds(String startTime, String endTime) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
long diff = 0;
try {
long eTime = df.parse(endTime).getTime();
long sTime = df.parse(startTime).getTime();
diff = (eTime - sTime) / 1000;
}catch (ParseException e) {
log.error("解析token日期失败");
}
return diff;
}
}

View File

@@ -0,0 +1,53 @@
package com.quinn.utils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* AES加密解密
*/
public class SecurityUtil {
private final static Map<Character, Character> match = new HashMap();
static {
// const map = ['E','q','u','i','n','W','A','b','C','d']
match.put('E','0');
match.put('q','1');
match.put('u','2');
match.put('i','3');
match.put('n','4');
match.put('W','5');
match.put('A','6');
match.put('b','7');
match.put('C','8');
match.put('d','9');
}
public static boolean checkToken(String token) {
String tokenDate = QuinnUtils.getTokenDate(new Date());
String year = tokenDate.substring(0, 4);
Pattern pattern = Pattern.compile("\\d+");//创建匹配数字字符的模式
Matcher matcher = pattern.matcher(token);
matcher.find();
int start = matcher.start();
String indent = token.substring(0,start) + token.substring(start+2);
indent = indent.replaceAll("f","");
indent = indent.replaceAll("g","");
indent = indent.replaceAll("h","");
indent = indent.replaceAll("j","");
indent = indent.replaceAll("k","");
indent = indent.replaceAll("l","");
char[] chars = indent.toCharArray();
StringBuffer sb = new StringBuffer();
for (char aChar : chars) {
Character character = match.get(aChar);
sb.append(character);
}
long l = QuinnUtils.diffSeconds(year + sb.toString(), tokenDate);
return l < 30;
}
}