fix:冲突解决

This commit is contained in:
haoxr 2021-06-09 07:57:42 +08:00
parent 9a3eb91ae7
commit fc65748924
26 changed files with 244 additions and 380 deletions

View File

@ -11,7 +11,12 @@ import org.springframework.web.bind.annotation.*;
public interface MemberFeignClient {
@PostMapping("/app-api/v1/members")
Result add(@RequestBody UmsMember user);
Result add(@RequestBody UmsMember member);
@PostMapping("/app-api/v1/members/{id}")
Result update(@PathVariable Long id,@RequestBody UmsMember member);
/**
* 获取会员信息
@ -24,7 +29,7 @@ public interface MemberFeignClient {
* 获取认证会员信息
*/
@GetMapping("/app-api/v1/members/openid/{openid}")
Result<AuthMemberDTO> getUserByOpenid(@PathVariable String openid);
Result<UmsMember> getByOpenid(@PathVariable String openid);
/**
* 修改会员积分

View File

@ -24,13 +24,13 @@ public class UmsMember extends BaseEntity {
private Integer gender;
private String nickname;
private String nickName;
private String mobile;
private LocalDate birthday;
private String avatar;
private String avatarUrl;
private String openid;
@ -45,7 +45,14 @@ public class UmsMember extends BaseEntity {
@TableField(exist = false)
private List<UmsAddress> addressList;
// @TableField(exist = false)
private Long balance;
private String city;
private String country;
private String language;
private String province;
}

View File

@ -1,18 +0,0 @@
package com.youlai.mall.ums.pojo.vo;
import lombok.Data;
@Data
public class MemberVO {
private Long id;
private String nickname;
private String avatar;
private Long balance;
}

View File

@ -9,7 +9,6 @@ import com.youlai.common.web.util.JwtUtils;
import com.youlai.mall.ums.pojo.domain.UmsMember;
import com.youlai.mall.ums.pojo.dto.AuthMemberDTO;
import com.youlai.mall.ums.pojo.dto.MemberDTO;
import com.youlai.mall.ums.pojo.vo.MemberVO;
import com.youlai.mall.ums.service.IUmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
@ -31,13 +30,13 @@ public class MemberController {
@ApiOperation(value = "获取会员信息")
@ApiImplicitParam(name = "id", value = "会员ID", required = true, paramType = "path", dataType = "Long")
@GetMapping("/{id}")
public Result getMemberById(
public Result getById(
@PathVariable Long id
) {
MemberDTO memberDTO = new MemberDTO();
UmsMember user = iUmsUserService.getOne(
new LambdaQueryWrapper<UmsMember>()
.select(UmsMember::getId, UmsMember::getNickname, UmsMember::getMobile, UmsMember::getBalance)
.select(UmsMember::getId, UmsMember::getNickName, UmsMember::getMobile, UmsMember::getBalance)
.eq(UmsMember::getId, id)
);
if (user != null) {
@ -49,17 +48,15 @@ public class MemberController {
@ApiOperation(value = "根据openid获取会员信息")
@ApiImplicitParam(name = "openid", value = "微信身份唯一标识", required = true, paramType = "path", dataType = "String")
@GetMapping("/openid/{openid}")
public Result getMemberByOpenid(
public Result getByOpenid(
@PathVariable String openid
) {
UmsMember user = iUmsUserService.getOne(new LambdaQueryWrapper<UmsMember>()
UmsMember member = iUmsUserService.getOne(new LambdaQueryWrapper<UmsMember>()
.eq(UmsMember::getOpenid, openid));
if (user == null) {
if (member == null) {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
AuthMemberDTO authMemberDTO = new AuthMemberDTO();
BeanUtil.copyProperties(user, authMemberDTO);
return Result.success(authMemberDTO);
return Result.success(member);
}
@ApiOperation(value = "新增会员")
@ -70,6 +67,14 @@ public class MemberController {
return Result.judge(status);
}
@ApiOperation(value = "新增会员")
@ApiImplicitParam(name = "member", value = "实体JSON对象", required = true, paramType = "body", dataType = "UmsMember")
@PutMapping("/{id}")
public Result add(@PathVariable Long id,@RequestBody UmsMember user) {
boolean status = iUmsUserService.updateById(user);
return Result.judge(status);
}
@ApiOperation(value = "获取当前请求的会员信息")
@GetMapping("/me")
public Result getMemberInfo() {
@ -78,9 +83,9 @@ public class MemberController {
if (user == null) {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
MemberVO memberVO = new MemberVO();
BeanUtil.copyProperties(user, memberVO);
return Result.success(memberVO);
MemberDTO memberDTO = new MemberDTO();
BeanUtil.copyProperties(user, memberDTO);
return Result.success(memberDTO);
}

View File

@ -1,4 +1,4 @@
package com.youlai.auth.enums;
package com.youlai.auth.common.enums;
import lombok.Getter;

View File

@ -1,4 +1,4 @@
package com.youlai.auth.enums;
package com.youlai.auth.common.enums;
import lombok.Getter;

View File

@ -1,4 +1,4 @@
package com.youlai.auth.exception;
package com.youlai.auth.common.exception;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;

View File

@ -0,0 +1,43 @@
package com.youlai.auth.common.jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.stereotype.Component;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.Map;
import java.util.Set;
/**
* 描述: [类型描述]
* 创建时间: 2021-06-08
* @author hxr
* @version 1.0.0
* @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Component
public class JwtGenerator {
@Autowired
private KeyPair keyPair;
public String createAccessToken(Set<String> authorities, Map<String, String> additional) {
String payload = new JwtPayloadBuilder()
.exp(12 * 3600) // 默认12小时
.authorities(authorities)
.additional(additional)
.builder();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RsaSigner signer = new RsaSigner(privateKey);
String accessToken = JwtHelper.encode(payload, signer).getEncoded();
return accessToken;
}
}

View File

@ -1,9 +1,8 @@
package com.youlai.auth.jwt;
package com.youlai.auth.common.jwt;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@ -13,57 +12,46 @@ import java.util.Map;
import java.util.Set;
/**
* 构建 jwt payload
**/
* 描述: [类型描述]
* 创建时间: 2021/6/8
* @author hxr
* @version 1.0.0
* @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public class JwtPayloadBuilder {
private Map<String, Object> payload = new HashMap<>();
/**
* 附加的属性
*/
private Map<String, String> additional;
/**
* jwt签发者
**/
private String iss;
/**
* jwt所面向的用户
**/
private String sub;
/**
* 接收jwt的一方
**/
private String aud;
/**
* jwt的过期时间这个过期时间必须要大于签发时间
**/
private LocalDateTime exp;
/**
* jwt的签发时间
**/
private LocalDateTime iat = LocalDateTime.now();
/**
* 权限集
*/
private Set<String> authorities = new HashSet<>();
/**
* jwt的唯一身份标识主要用来作为一次性token,从而回避重放攻击
**/
private String jti = IdUtil.simpleUUID();
public JwtPayloadBuilder iss(String iss) {
this.iss = iss;
return this;
}
/**
* jwt的签发时间
**/
private LocalDateTime iat = LocalDateTime.now();
/**
* jwt的过期时间这个过期时间必须要大于签发时间
**/
private LocalDateTime exp;
/**
* 权限集
*/
private Set<String> authorities = new HashSet<>();
/**
* 附加的属性
*/
private Map<String, String> additional;
public JwtPayloadBuilder sub(String sub) {
this.sub = sub;
return this;
}
public JwtPayloadBuilder aud(String aud) {
this.aud = aud;
public JwtPayloadBuilder exp(int seconds) {
this.exp = this.iat.plusSeconds(seconds);
return this;
}
@ -72,31 +60,21 @@ public class JwtPayloadBuilder {
return this;
}
public JwtPayloadBuilder expDays(int days) {
Assert.isTrue(days > 0, "jwt expireDate must after now");
this.exp = this.iat.plusDays(days);
return this;
}
public JwtPayloadBuilder additional(Map<String, String> additional) {
this.additional = additional;
return this;
}
public String builder() {
payload.put("iss", this.iss);
payload.put("sub", this.sub);
payload.put("aud", this.aud);
payload.put("exp", this.exp.toEpochSecond(ZoneOffset.of("+8")));
payload.put("jti", jti);
payload.put("iat", this.iat.toEpochSecond(ZoneOffset.of("+8")));
payload.put("jti", this.jti);
if (!CollectionUtils.isEmpty(additional)) {
payload.put("exp", this.exp.toEpochSecond(ZoneOffset.of("+8")));
if (CollectionUtil.isNotEmpty(additional)) {
payload.putAll(additional);
}
payload.put("authorities", this.authorities.toArray());
return JSONUtil.toJsonStr(JSONUtil.parse(payload));
return JSONUtil.toJsonStr(payload);
}
}

View File

@ -1,29 +0,0 @@
package com.youlai.auth.config;
import com.youlai.auth.jwt.JwtProperties;
import com.youlai.auth.jwt.JwtTokenGenerator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* JwtConfiguration
*/
@EnableConfigurationProperties(JwtProperties.class)
@ConditionalOnProperty(prefix = "jwt.config", name = "enabled")
@Configuration
public class JwtConfiguration {
/**
* Jwt token generator.
*
* @param jwtProperties the jwt properties
* @return the jwt token generator
*/
@Bean
public JwtTokenGenerator jwtTokenGenerator(JwtProperties jwtProperties) {
return new JwtTokenGenerator(jwtProperties);
}
}

View File

@ -1,4 +1,4 @@
package com.youlai.auth.config.swagger;
package com.youlai.auth.config;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;

View File

@ -1,4 +1,4 @@
package com.youlai.auth.config.weapp;
package com.youlai.auth.config;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
@ -28,7 +28,6 @@ public class WeAppConfig {
return config;
}
@Bean
public WxMaService wxMaService(WxMaConfig wxMaConfig) {
WxMaService service = new WxMaServiceImpl();

View File

@ -3,9 +3,8 @@ package com.youlai.auth.controller;
import cn.hutool.json.JSONObject;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.youlai.auth.enums.OAuthClientEnum;
import com.youlai.auth.jwt.JwtTokenPair;
import com.youlai.auth.service.WeAppService;
import com.youlai.auth.common.enums.OAuthClientEnum;
import com.youlai.auth.service.impl.WeAppServiceImpl;
import com.youlai.common.constant.AuthConstants;
import com.youlai.common.result.Result;
import com.youlai.common.web.util.JwtUtils;
@ -35,7 +34,7 @@ import java.util.concurrent.TimeUnit;
public class OAuthController {
private TokenEndpoint tokenEndpoint;
private WeAppService weAppService;
private WeAppServiceImpl weAppServiceImpl;
private RedisTemplate redisTemplate;
private KeyPair keyPair;
@ -46,7 +45,7 @@ public class OAuthController {
@ApiImplicitParam(name = "client_secret", defaultValue = "123456", value = "Oauth2客户端秘钥", required = true),
@ApiImplicitParam(name = "refresh_token", value = "刷新token"),
@ApiImplicitParam(name = "username", defaultValue = "admin", value = "登录用户名"),
@ApiImplicitParam(name = "password", defaultValue = "123456", value = "登录密码"),
@ApiImplicitParam(name = "password", defaultValue = "123456", value = "登录密码")
})
@PostMapping("/token")
public Object postAccessToken(
@ -65,7 +64,7 @@ public class OAuthController {
OAuthClientEnum client = OAuthClientEnum.getByClientId(clientId);
switch (client) {
case WEAPP: // 微信小程序
return Result.success(weAppService.login(parameters));
return Result.success(weAppServiceImpl.login(parameters));
case TEST: // knife4j接口测试文档使用 client_id/client_secret : client/123456
return tokenEndpoint.postAccessToken(principal, parameters).getBody();
default:
@ -98,4 +97,5 @@ public class OAuthController {
RSAKey key = new RSAKey.Builder(publicKey).build();
return new JWKSet(key).toJSONObject();
}
}

View File

@ -0,0 +1,15 @@
package com.youlai.auth.domain;
/**
* 描述: [类型描述]
* 创建时间: 2021/6/8
*
* @author hxr
* @version 1.0.0
* @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public class OAuthToken {
}

View File

@ -2,8 +2,7 @@ package com.youlai.auth.domain;
import cn.hutool.core.collection.CollectionUtil;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.auth.enums.PasswordEncoderTypeEnum;
import com.youlai.common.constant.AuthConstants;
import com.youlai.auth.common.enums.PasswordEncoderTypeEnum;
import com.youlai.mall.ums.pojo.dto.AuthMemberDTO;
import lombok.Data;
import lombok.NoArgsConstructor;

View File

@ -0,0 +1,30 @@
package com.youlai.auth.domain;
import lombok.Data;
/**
* 描述: [微信用户信息]
* 创建时间: 2021/6/8
*
* @author hxr
* @version 1.0.0
* @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Data
public class UserInfo {
private String avatarUrl;
private String city;
private String country;
private Integer gender;
private String language;
private String nickName;
private String province;
}

View File

@ -1,43 +0,0 @@
package com.youlai.auth.jwt;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* Jwt springboot application.yml 中的配置文件
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jwt.config")
public class JwtProperties {
/**
* 是否可用
*/
private boolean enabled;
/**
* jks 路径
*/
private String keyLocation;
/**
* key alias
*/
private String keyAlias;
/**
* key store pass
*/
private String keyPass;
/**
* jwt签发者
**/
private String iss;
/**
* jwt所面向的用户
**/
private String sub;
/**
* access jwt token 有效天数
*/
private int accessExpDays;
}

View File

@ -1,116 +0,0 @@
package com.youlai.auth.jwt;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.util.Assert;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.Set;
/**
* JwtTokenGenerator
*/
@Slf4j
public class JwtTokenGenerator {
private static final String JWT_EXP_KEY = "exp";
private KeyPair keyPair;
private JwtPayloadBuilder jwtPayloadBuilder = new JwtPayloadBuilder();
private JwtProperties jwtProperties;
/**
* Instantiates a new Jwt token generator.
*
* @param jwtProperties the jwt properties
*/
public JwtTokenGenerator(JwtProperties jwtProperties) {
this.jwtProperties = jwtProperties;
KeyPairFactory keyPairFactory = new KeyPairFactory();
this.keyPair = keyPairFactory.getKeyPair(jwtProperties);
}
/**
* Jwt token pair jwt token pair.
*
* @param aud the aud
* @param authorities the authorities
* @param additional the additional
* @return the jwt token pair
*/
public JwtTokenPair jwtTokenPair(String aud, Set<String> authorities, Map<String, String> additional) {
String accessToken = jwtToken(aud, jwtProperties.getAccessExpDays(), authorities, additional);
JwtTokenPair jwtTokenPair = new JwtTokenPair();
jwtTokenPair.setToken_type("bearer");
jwtTokenPair.setAccess_token(accessToken);
return jwtTokenPair;
}
/**
* Jwt token string.
*
* @param aud the aud
* @param exp the exp
* @param authorities the authorities
* @param additional the additional
* @return the string
*/
private String jwtToken(String aud, int exp, Set<String> authorities, Map<String, String> additional) {
String payload = jwtPayloadBuilder
.iss(jwtProperties.getIss())
.sub(jwtProperties.getSub())
.aud(aud)
.additional(additional)
.authorities(authorities)
.expDays(exp)
.builder();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RsaSigner signer = new RsaSigner(privateKey);
return JwtHelper.encode(payload, signer).getEncoded();
}
/**
* 解码 并校验签名 过期不予解析
*
* @param jwtToken the jwt token
* @return the jwt claims
*/
public JSONObject decodeAndVerify(String jwtToken) {
Assert.hasText(jwtToken, "jwt token must not be bank");
RSAPublicKey rsaPublicKey = (RSAPublicKey) this.keyPair.getPublic();
SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
String claims = jwt.getClaims();
JSONObject jsonObject = JSONUtil.parseObj(claims);
String exp = jsonObject.getStr(JWT_EXP_KEY);
if (isExpired(exp)) {
throw new IllegalStateException("jwt token is expired");
}
return jsonObject;
}
/**
* 判断jwt token是否过期.
*
* @param exp the jwt token exp
* @return the boolean
*/
private boolean isExpired(String exp) {
return LocalDateTime.now().isAfter(LocalDateTime.ofEpochSecond(Long.parseLong(exp), 0, ZoneOffset.ofHours(8)));
}
}

View File

@ -1,16 +0,0 @@
package com.youlai.auth.jwt;
import lombok.Data;
import java.io.Serializable;
/**
* JwtTokenPair
*
**/
@Data
public class JwtTokenPair implements Serializable {
private static final long serialVersionUID = -8518897818107784049L;
private String access_token;
private String token_type;
}

View File

@ -1,19 +0,0 @@
package com.youlai.auth.jwt;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.security.KeyPair;
/**
* KeyPairFactory
**/
public class KeyPairFactory {
public KeyPair getKeyPair(JwtProperties jwtProperties) {
KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource(jwtProperties.getKeyLocation()),
jwtProperties.getKeyPass().toCharArray());
KeyPair keyPair = factory.getKeyPair(jwtProperties.getKeyAlias(), jwtProperties.getKeyPass().toCharArray());
return keyPair;
}
}

View File

@ -1,11 +1,11 @@
package com.youlai.auth.config.oauth2;
package com.youlai.auth.security.config;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.youlai.auth.domain.OAuthUserDetails;
import com.youlai.auth.service.ClientDetailsServiceImpl;
import com.youlai.auth.service.UserDetailsServiceImpl;
import com.youlai.auth.security.service.ClientDetailsServiceImpl;
import com.youlai.auth.security.service.UserDetailsServiceImpl;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;
import lombok.AllArgsConstructor;

View File

@ -1,4 +1,4 @@
package com.youlai.auth.config.oauth2;
package com.youlai.auth.security.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
@ -16,7 +16,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/oauth/public-key","/oauth/logout").permitAll()
.authorizeRequests().antMatchers("/oauth/**").permitAll()
// @link https://gitee.com/xiaoym/knife4j/issues/I1Q5X6 (接口文档knife4j需要放行的规则)
.antMatchers("/webjars/**","/doc.html","/swagger-resources/**","/v2/api-docs").permitAll()
.anyRequest().authenticated()

View File

@ -1,8 +1,7 @@
package com.youlai.auth.service;
package com.youlai.auth.security.service;
import com.youlai.admin.api.OAuthClientFeignClient;
import com.youlai.admin.pojo.entity.SysOauthClient;
import com.youlai.auth.enums.PasswordEncoderTypeEnum;
import com.youlai.auth.common.enums.PasswordEncoderTypeEnum;
import com.youlai.common.result.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
@ -24,7 +23,6 @@ public class ClientDetailsServiceImpl implements ClientDetailsService {
@SneakyThrows
public ClientDetails loadClientByClientId(String clientId) {
try {
Result<SysOauthClient> result = oAuthClientFeignClient.getOAuthClientById(clientId);
if (Result.success().getCode().equals(result.getCode())) {
SysOauthClient client = result.getData();

View File

@ -1,9 +1,9 @@
package com.youlai.auth.service;
package com.youlai.auth.security.service;
import com.youlai.admin.api.UserFeignClient;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.auth.common.enums.OAuthClientEnum;
import com.youlai.auth.domain.OAuthUserDetails;
import com.youlai.auth.enums.OAuthClientEnum;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;
import com.youlai.common.web.util.JwtUtils;
@ -40,13 +40,6 @@ public class UserDetailsServiceImpl implements UserDetailsService {
Result result;
OAuthUserDetails oauthUserDetails = null;
switch (client) {
case WEAPP: // 小程序会员
result = memberFeignClient.getUserByOpenid(username);
if (ResultCode.SUCCESS.getCode().equals(result.getCode())) {
AuthMemberDTO authMemberDTO = (AuthMemberDTO) result.getData();
oauthUserDetails = new OAuthUserDetails(authMemberDTO);
}
break;
default:
result = userFeignClient.getUserByUsername(username);
if (ResultCode.SUCCESS.getCode().equals(result.getCode())) {

View File

@ -0,0 +1,16 @@
package com.youlai.auth.service;
import java.util.Map;
/**
* 描述: [类型描述]
* 创建时间: 2021/6/8
*
* @author hxr
* @version 1.0.0
* @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public interface IAuthService {
Map<String,Object> login(Map<String, String> parameters);
}

View File

@ -1,30 +1,21 @@
package com.youlai.auth.service;
package com.youlai.auth.service.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.util.StrUtil;
import com.youlai.auth.jwt.JwtTokenGenerator;
import com.youlai.auth.jwt.JwtTokenPair;
import com.youlai.auth.enums.PasswordEncoderTypeEnum;
import com.youlai.common.constant.GlobalConstants;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.youlai.auth.common.jwt.JwtGenerator;
import com.youlai.auth.domain.UserInfo;
import com.youlai.auth.service.IAuthService;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;
import com.youlai.common.web.exception.BizException;
import com.youlai.mall.ums.api.MemberFeignClient;
import com.youlai.mall.ums.pojo.domain.UmsMember;
import com.youlai.mall.ums.pojo.dto.AuthMemberDTO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
@ -34,34 +25,59 @@ import java.util.Map;
*/
@Service
@AllArgsConstructor
public class WeAppService {
private WxMaService wxService;
public class WeAppServiceImpl implements IAuthService {
private MemberFeignClient memberFeignClient;
private PasswordEncoder passwordEncoder;
private TokenEndpoint tokenEndpoint;
@Resource
private JwtTokenGenerator jwtTokenGenerator;
private WxMaService wxMaService;
private JwtGenerator jwtGenerator;
/**
* @param parameters code=小程序授权code
* encryptedData=包括敏感数据在内的完整用户信息的加密数据
* iv=加密算法的初始向量
* iv=
* @return
*/
@SneakyThrows
public JwtTokenPair login(Map<String, String> parameters) {
@Override
public Map<String, Object> login(Map<String, String> parameters) {
String code = parameters.get("code");
// String userInfo = parameters.get("userInfo");
String rawData = parameters.get("rawData");
String signature = parameters.get("signature");
WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
String sessionKey = sessionInfo.getSessionKey();
boolean checkResult = wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature);
if (checkResult) {
String openid = sessionInfo.getOpenid();
Result<UmsMember> result = memberFeignClient.getByOpenid(openid);
if (StrUtil.isBlank(code)) {
UmsMember member = null;
Result memberResult;
if (ResultCode.USER_NOT_EXIST.getCode().equals(result.getCode())) {
// 用户不存在注册成为新用户
UserInfo userInfo = JSONUtil.toBean(rawData, UserInfo.class);
member = new UmsMember();
BeanUtil.copyProperties(userInfo, member);
memberResult = memberFeignClient.add(member);
} else if (ResultCode.SUCCESS.getCode().equals(result.getCode()) && result.getData() != null) {
member = result.getData();
UserInfo userInfo = JSONUtil.toBean(rawData, UserInfo.class);
BeanUtil.copyProperties(userInfo, member);
memberResult = memberFeignClient.update(member.getId(), member);
}
}
// String userInfo = parameters.get("userInfo");
/* if (StrUtil.isBlank(code)) {
throw new BizException("code不能为空");
}
WxMaJscode2SessionResult session = null;
WxMaJscode2SessionResult session;
// 根据授权code获取微信用户信息
session = wxService.getUserService().getSessionInfo(code);
session = wxMaService.getUserService().getSessionInfo(code);
String openid = session.getOpenid();
String sessionKey = session.getSessionKey();
@ -72,7 +88,7 @@ public class WeAppService {
String encryptedData = parameters.get("encryptedData");
String iv = parameters.get("iv");
WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
if (userInfo == null) {
throw new BizException("获取用户信息失败");
}
@ -94,7 +110,8 @@ public class WeAppService {
HashSet<String> roles = new HashSet<>();
HashMap<String, String> additional = new HashMap<>();
additional.put("userId", String.valueOf(userId));
return jwtTokenGenerator.jwtTokenPair(openid, roles, additional);
additional.put("userId", String.valueOf(userId));*/
// jwtGenerator.createAccessToken(openid, roles, additional);
return null;
}
}