Compare commits

..

3 Commits

Author SHA1 Message Date
e3966a999a Merge remote-tracking branch 'origin/master' 2024-12-15 16:06:57 +08:00
0ee1f57c72 select category 2024-12-15 16:02:40 +08:00
8a78e0ffb9 select category 2024-12-15 15:59:33 +08:00
21 changed files with 386 additions and 15 deletions

3
.gitignore vendored
View File

@@ -4,4 +4,5 @@
*.class
*Test.java
**/test/
resources/application-dev.properties
resources/application-dev.properties
/sky-server/src/main/resources/application-dev.properties

View File

@@ -4,6 +4,7 @@ package com.sky.constant;
* 公共字段自动填充相关常量
*/
public class AutoFillConstant {
/**
* 实体类中的方法名称
*/

View File

@@ -5,19 +5,57 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author SLHAF
*/
@Component
@ConfigurationProperties(prefix = "sky.wechat")
@Data
public class WeChatProperties {
private String appid; //小程序的appid
private String secret; //小程序的秘钥
private String mchid; //商户号
private String mchSerialNo; //商户API证书的证书序列号
private String privateKeyFilePath; //商户私钥文件
private String apiV3Key; //证书解密的密钥
private String weChatPayCertFilePath; //平台证书
private String notifyUrl; //支付成功的回调地址
private String refundNotifyUrl; //退款成功的回调地址
/**
小程序的appid
*/
private String appid;
/**
* 小程序的秘钥
*/
private String secret;
/**
* 商户号
*/
private String mchid;
/**
* 商户API证书的证书序列号
*/
private String mchSerialNo;
/**
* 商户私钥文件
*/
private String privateKeyFilePath;
/**
* 证书解密的密钥
*/
private String apiV3Key;
/**
* 平台证书
*/
private String weChatPayCertFilePath;
/**
* “支付成功”的回调地址
*/
private String notifyUrl;
/**
* “退款成功”的回调地址
*/
private String refundNotifyUrl;
}

View File

@@ -6,6 +6,7 @@ import java.io.Serializable;
/**
* 后端统一返回结果
* @author SLHAF
* @param <T>
*/
@Data

View File

@@ -115,6 +115,11 @@
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

View File

@@ -5,6 +5,9 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author SLHAF
*/
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j

View File

@@ -1,6 +1,7 @@
package com.sky.config;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.interceptor.JwtTokenUserInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@@ -22,6 +23,7 @@ import java.util.List;
/**
* 配置类注册web层相关组件
* @author SLHAF
*/
@Configuration
@Slf4j
@@ -29,17 +31,25 @@ public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
@Autowired
private JwtTokenUserInterceptor jwtTokenUserInterceptor;
/**
* 注册自定义拦截器
*
* @param registry
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
log.info("开始注册自定义拦截器...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login");
registry.addInterceptor(jwtTokenUserInterceptor)
.addPathPatterns("/user/**")
.excludePathPatterns("/user/user/login")
.excludePathPatterns("/user/shop/status");
}
/**
@@ -90,6 +100,7 @@ public class WebMvcConfiguration extends WebMvcConfigurationSupport {
* 设置静态资源映射
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始设置静态资源映射...");
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");

View File

@@ -43,6 +43,7 @@ public class EmployeeController {
@PostMapping("/login")
@ApiOperation(value = "员工登录")
public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
// System.out.println(Thread.currentThread().getName());
log.info("员工登录:{}", employeeLoginDTO);
Employee employee = employeeService.login(employeeLoginDTO);

View File

@@ -10,8 +10,11 @@ import org.springframework.web.bind.annotation.*;
import java.util.Objects;
/**
* @author SLHAF
*/
@RestController("userShopController")
@RequestMapping("/admin/user")
@RequestMapping("/user/shop")
@Api(tags = "店铺操作接口")
@Slf4j
public class ShopController {

View File

@@ -0,0 +1,30 @@
package com.sky.controller.user;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user/category")
@Api(tags = "Category")
@Slf4j
public class UserCategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
public Result<List<Category>> list(Integer type){
log.info("user category list: {}",type);
List<Category> list = categoryService.list(type);
return Result.success(list);
}
}

View File

@@ -0,0 +1,57 @@
package com.sky.controller.user;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Objects;
/**
* @author SLHAF
*/
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("/login")
@ApiOperation("微信登录")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
// System.out.println(Thread.currentThread().getName());
log.info("微信用户登录: {}",userLoginDTO.getCode());
//微信登录
User user = userService.wxLogin(userLoginDTO);
//生成jwt
HashMap<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.USER_ID,user.getId());
String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
UserLoginVO userLoginVO = UserLoginVO.builder()
.id(user.getId())
.openid(user.getOpenid())
.token(token)
.build();
return Result.success(userLoginVO);
}
}

View File

@@ -0,0 +1,6 @@
package com.sky.controller.user;
public class UserSetmealController {
}

View File

@@ -31,9 +31,9 @@ public class JwtTokenAdminInterceptor implements HandlerInterceptor {
* @param response
* @param handler
* @return
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//判断当前拦截到的是Controller的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
//当前拦截到的不是动态方法,直接放行

View File

@@ -0,0 +1,61 @@
package com.sky.interceptor;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* jwt令牌校验的拦截器
*/
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
@Autowired
private JwtProperties jwtProperties;
/**
* 校验jwt
*
* @param request
* @param response
* @param handler
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//判断当前拦截到的是Controller的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
//当前拦截到的不是动态方法,直接放行
return true;
}
//1、从请求头中获取令牌
String token = request.getHeader(jwtProperties.getUserTokenName());
//2、校验令牌
try {
log.info("jwt校验:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
BaseContext.setCurrentId(userId);
log.info("当前用户id{}", userId);
//3、通过放行
return true;
} catch (Exception ex) {
//4、不通过响应 401 状态码
response.setStatus(401);
return false;
}
}
}

View File

@@ -30,4 +30,7 @@ public interface CategoryMapper {
@Select("select * from category where type = #{type}")
List<Category> selectByType(Integer type);
@Select("select * from category")
List<Category> selectCategory();
}

View File

@@ -0,0 +1,23 @@
package com.sky.mapper;
import com.sky.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
/**
* 根据openid查询用户
* @param openid
* @return
*/
@Select("select * from user where openid = #{openid}")
User getByOpenid(String openid);
/**
* 插入数据
* @param user
*/
void insert(User user);
}

View File

@@ -0,0 +1,19 @@
package com.sky.service;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import org.springframework.stereotype.Service;
/**
* @author SLHAF
*/
@Service
public interface UserService {
/**
* 微信登录
* @param userLoginDTO
* @return
*/
User wxLogin(UserLoginDTO userLoginDTO);
}

View File

@@ -126,6 +126,12 @@ public class CategoryServiceImpl implements CategoryService {
*/
@Override
public List<Category> list(Integer type) {
return categoryMapper.selectByType(type);
List<Category> categoryList;
if (type == null){
categoryList = categoryMapper.selectCategory();
}else {
categoryList = categoryMapper.selectByType(type);
}
return categoryList;
}
}

View File

@@ -0,0 +1,79 @@
package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
/**
* @author SLHAF
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
/**
* 微信接口服务地址
*/
public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
@Autowired
private WeChatProperties weChatProperties;
@Autowired
private UserMapper userMapper;
@Override
public User wxLogin(UserLoginDTO userLoginDTO) {
//调用微信接口获取openid
String openid = getOpenid(userLoginDTO.getCode());
//判断openid是否为空为空表示登录失败则抛出异常
if (openid == null) {
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
//判断当前用户是否为新用户
User user = userMapper.getByOpenid(openid);
//如果是新用户,自动完成注册
if (user == null) {
user = User.builder()
.openid(openid)
.createTime(LocalDateTime.now())
.build();
userMapper.insert(user);
}
//返回用户对象
return user;
}
/**
* 调用接口获取用户openid
* @param code
* @return
*/
private String getOpenid(String code) {
HashMap<String, String> map = new HashMap<>();
map.put("appid", weChatProperties.getAppid());
map.put("secret", weChatProperties.getSecret());
map.put("js_code", code);
map.put("grant_type", "authorization_code");
String json = HttpClientUtil.doGet(WX_LOGIN, map);
JSONObject jsonObject = JSON.parseObject(json);
return jsonObject.getString("openid");
}
}

View File

@@ -5,22 +5,34 @@ spring.datasource.druid.driver-class-name=${sky.datasource.driver-class-name}
spring.datasource.druid.url=jdbc:mysql://${sky.datasource.host}:${sky.datasource.port}/${sky.datasource.database}?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.druid.username=${sky.datasource.username}
spring.datasource.druid.password=${sky.datasource.password}
spring.redis.host=${spring.redis.host}
spring.redis.port=${spring.redis.port}
#spring.redis.password=${spring.redis.password}
spring.redis.database=${spring.redis.database}
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.sky.entity
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.com.sky.mapper=debug
logging.level.com.sky.service=info
logging.level.com.sky.controller=info
sky.jwt.admin-secret-key=itcast
sky.jwt.admin-ttl=7200000
sky.jwt.admin-token-name=token
sky.jwt.user-secret-key=itheima
sky.jwt.user-ttl=7200000
sky.jwt.user-token-name=authentication
sky.alioss.endpoint=${sky.alioss.endpoint}
sky.alioss.bucket-name=${sky.alioss.bucket-name}
sky.alioss.access-key-id=${sky.alioss.access-key-id}
sky.alioss.access-key-secret=${sky.alioss.access-key-secret}
spring.servlet.multipart.max-file-size=${spring.servlet.multipart.max-file-size}
spring.servlet.multipart.max-request-size=${spring.servlet.multipart.max-request-size}
spring.servlet.multipart.max-request-size=${spring.servlet.multipart.max-request-size}
sky.wechat.appid=${sky.wechat.appid}
sky.wechat.secret=${sky.wechat.secret}

View File

@@ -0,0 +1,11 @@
<?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.sky.mapper.UserMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into user(openid, name, phone, sex, id_number, avatar, create_time)
values (#{openid}, #{name}, #{phone}, #{sex}, #{idNumber}, #{avatar}, #{createTime})
</insert>
</mapper>