package com.gear.customer.swx.biz.impl; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.gear.common.constant.SwxConstons; import com.gear.common.core.redis.RedisCache; import com.gear.common.exception.CustomerException; import com.gear.common.utils.RandomGeneratorUtil; import com.gear.common.utils.email.Emailer; import com.gear.common.utils.email.SendEmailUtils; import com.gear.common.utils.emailsq.SpreadEmail; import com.gear.common.utils.http.HttpUtils; import com.gear.common.utils.jwt.JWTTokenUtils; import com.gear.common.utils.sign.Md5Utils; import com.gear.common.utils.slemail.SLSendEimailUtils; import com.gear.common.utils.validator.EmailValidator; import com.gear.customer.swx.biz.SwxBizUserLogin; import com.gear.customer.swx.vo.request.SendCodeVo; import com.gear.customer.swx.vo.response.SwxUserInfoVo; import com.gear.customer.swx.vo.request.SwxUserLoginVo; import com.gear.customer.swx.vo.request.SwxUserRegisterVo; import com.gear.swx.domain.SwxSettings; import com.gear.swx.domain.SwxUser; import com.gear.swx.service.ISwxSettingsService; import com.gear.swx.service.ISwxUserService; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.logging.log4j.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.CollectionUtils; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Component public class SwxBizUserLoginImpl implements SwxBizUserLogin { private static final Logger log = LoggerFactory.getLogger(SwxBizUserLoginImpl.class); @Autowired private ISwxUserService swxUserService; @Autowired private ISwxSettingsService swxSettingsService; @Autowired private RedisCache redisCache; @Override public SwxUserInfoVo login(SwxUserLoginVo swxUserLoginVo) { QueryWrapper queryWrapper = new QueryWrapper<>(); if(Strings.isEmpty(swxUserLoginVo.getPhone()) && Strings.isEmpty(swxUserLoginVo.getUserName())){ throw new CustomerException("10001"); } if(!Strings.isEmpty(swxUserLoginVo.getPhone())){ //检查手机号是否存在 if(checkUserNameOrPhone(SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_PHONE, swxUserLoginVo.getPhone())){ throw new CustomerException("10002"); } queryWrapper.lambda().eq(SwxUser::getPhone, swxUserLoginVo.getPhone()); } if(!Strings.isEmpty(swxUserLoginVo.getUserName())){ //检查手机号是否存在 if(checkUserNameOrPhone(SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_USERNAME, swxUserLoginVo.getUserName())){ throw new CustomerException("10003"); } queryWrapper.lambda().eq(SwxUser::getUserName, swxUserLoginVo.getUserName()); } SwxUser swxUser = swxUserService.getOne(queryWrapper); String passMd5 = Md5Utils.hash(swxUserLoginVo.getPassword()); if(!swxUser.getPassword().equals(passMd5)){ throw new CustomerException("10004"); } if(! (swxUser.getStatus() == SwxConstons.NOMARL_STATUS_YES)){ throw new CustomerException("10005"); } //创建token String token = JWTTokenUtils.createToken(swxUser.getId(),swxUser.getPhone(),"SWX"); SwxUserInfoVo info = new SwxUserInfoVo(); BeanUtils.copyProperties(swxUser,info); SwxSettings swxSettings = swxSettingsService.getOne(new QueryWrapper().lambda().eq(SwxSettings::getParamKey,"virtual_account")); if(swxSettings != null && ((Integer.parseInt(swxSettings.getParamValue()))==SwxConstons.NOMARL_STATUS_YES)){ info.setVirtuallyAmount(new BigDecimal(1000000)); info.setVirtuallyStatus(SwxConstons.NOMARL_STATUS_YES); info.setVirtuallyBondAmount(new BigDecimal(0)); //redis放入一个虚拟账户 if(!redisCache.hasKey("SWX-CUSTOMER-VERTURAL-"+swxUser.getId())){ redisCache.setCacheObject("SWX-CUSTOMER-VERTURAL-"+swxUser.getId(),info,604800L, TimeUnit.SECONDS); } } info.setToken(token); return info; } @Override public String register(SwxUserRegisterVo swxUserRegisterVo)throws CustomerException { //查询密码是否相同 if(Strings.isEmpty(swxUserRegisterVo.getPassword()) || !swxUserRegisterVo.getPassword().equals(swxUserRegisterVo.getRePaossword()) || Strings.isEmpty(swxUserRegisterVo.getPhone()) || Strings.isEmpty(swxUserRegisterVo.getCode())){ throw new CustomerException("10004"); } // if (!EmailValidator.isValidEmail(swxUserRegisterVo.getPhone())){ // throw new CustomerException("10088"); // } //查询用户名和手机号是否存在 if(!checkUserNameOrPhone(SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_USERNAME, swxUserRegisterVo.getUserName())){ throw new CustomerException("10006"); } if(!checkUserNameOrPhone(SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_PHONE, swxUserRegisterVo.getPhone())){ throw new CustomerException("10007"); } //获取验证码 if (!redisCache.hasKey(swxUserRegisterVo.getPhone()+"Code")){ throw new CustomerException("10090"); } //如果输入的验证码不相符 if(!swxUserRegisterVo.getCode().equals(redisCache.getCacheObject(swxUserRegisterVo.getPhone()+"Code"))){ throw new CustomerException("10091"); } //将密码进行加密 String md5Pass = Md5Utils.hash(swxUserRegisterVo.getPassword()); SwxUser swxUser = new SwxUser(); swxUser.setUserName(swxUserRegisterVo.getUserName()); swxUser.setPhone(swxUserRegisterVo.getPhone()); swxUser.setPassword(md5Pass); swxUser.setInvetedUser(swxUserRegisterVo.getInvetedUser()); swxUserService.save(swxUser); return "20005"; } @Override public Boolean checkUserNameOrPhone(Integer type, String value) { if (type == SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_PHONE){ List list = swxUserService.list(new QueryWrapper().lambda().eq(SwxUser::getPhone,value)); if(!CollectionUtils.isEmpty(list)){ return false; } } if(type == SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_USERNAME){ List list = swxUserService.list(new QueryWrapper().lambda().eq(SwxUser::getUserName,value)); if(!CollectionUtils.isEmpty(list)){ return false; } } return true; } @Override public SwxUserInfoVo loginByGoogle(SwxUserRegisterVo swxUserRegisterVo) throws CustomerException{ //根据code获取对应信息 String code = swxUserRegisterVo.getCode(); log.info("谷歌登录获取code为: "+code); try{ // 创建 Google 授权码流对象 GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), GsonFactory.getDefaultInstance(), "583303732132-iove6htpggh848fi1ij107d7eb6pbg2d.apps.googleusercontent.com", "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", Arrays.asList("openid", "email", "profile")) .setAccessType("offline") .build(); // 交换授权码为访问令牌 TokenResponse tokenResponse = flow.newTokenRequest(code) // .setRedirectUri("https://www.saxtrader.net/api/loginCallback/google") // .setRedirectUri("https://www.galaxytrader.cloud/api/loginCallback/google") .setRedirectUri("https://www.galaxydigitalgold.xyz/api/loginCallback/google") .execute(); String accessToken = tokenResponse.getAccessToken(); log.info("token为"+accessToken); String url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken; String userInfo = HttpUtils.sendGet(url, null, "utf-8"); JSONObject jsonObject = JSONObject.parseObject(userInfo); String email = jsonObject.getString("email"); log.info("用户的邮箱为:"+email); //查询数据库中是否存在该邮箱 SwxUser swxUser = swxUserService.getOne(new QueryWrapper().lambda().eq(SwxUser::getPhone,email)); //如果有的话,证明已经存在该用户,直接进行登录 SwxUserInfoVo info = new SwxUserInfoVo(); if (swxUser != null){ BeanUtils.copyProperties(swxUser,info); }else{ //如果没有的话,则进行注册,并返回用户信息 swxUser = new SwxUser(); //生成随机密码 String passStr = RandomGeneratorUtil.generateRandomString(8); String md5Pass = Md5Utils.hash(passStr); swxUser.setUserName(email); swxUser.setPhone(email); swxUser.setPassword(md5Pass); if (!Strings.isEmpty(swxUserRegisterVo.getInvetedUser())){ swxUser.setInvetedUser(swxUserRegisterVo.getInvetedUser()); } swxUserService.save(swxUser); } String token = JWTTokenUtils.createToken(swxUser.getId(),swxUser.getPhone(),"SWX"); SwxSettings swxSettings = swxSettingsService.getOne(new QueryWrapper().lambda().eq(SwxSettings::getParamKey,"virtual_account")); if(swxSettings != null && ((Integer.parseInt(swxSettings.getParamValue()))==SwxConstons.NOMARL_STATUS_YES)){ info.setVirtuallyAmount(new BigDecimal(1000000)); info.setVirtuallyStatus(SwxConstons.NOMARL_STATUS_YES); info.setVirtuallyBondAmount(new BigDecimal(0)); //redis放入一个虚拟账户 if(!redisCache.hasKey("SWX-CUSTOMER-VERTURAL-"+swxUser.getId())){ redisCache.setCacheObject("SWX-CUSTOMER-VERTURAL-"+swxUser.getId(),info,604800L, TimeUnit.SECONDS); } } info.setToken(token); return info; }catch (Exception e){ log.info("获取谷歌第三方登录异常:"+e.getMessage()); throw new CustomerException("10030"); } } @Override public String sendCode(SendCodeVo vo) { if(Strings.isEmpty(vo.getEmail()) || Strings.isEmpty(vo.getType())){ throw new CustomerException("10088"); } // if (!EmailValidator.isValidEmail(vo.getEmail())){ // throw new CustomerException("10088"); // } if (redisCache.hasKey(vo.getEmail()+"Code")){ throw new CustomerException("10089"); } if (!checkUserNameOrPhone(1,vo.getEmail())){ throw new CustomerException("10092"); } try{ //根据vo类型加载模版文件 Configuration freemarkerConfig = new Configuration(Configuration.VERSION_2_3_31); freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates/email"); Template template = freemarkerConfig.getTemplate(vo.getType()+".ftl"); //获取验证码 String code = RandomGeneratorUtil.generateRandomNumber(6); Map map =new HashMap<>(); map.put("code",code); String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); //验证码放入redis中 redisCache.setCacheObject(vo.getEmail()+"Code",code,300L,TimeUnit.SECONDS); // SLSendEimailUtils.sendEmail(vo.getEmail(),"Registration verification code",code); SpreadEmail.sendEmail(vo.getEmail(), "Registration verification code", code); return "20005"; }catch (Exception e){ throw new CustomerException("10088"); } } }