zj
2025-01-06 0e7b38c2b3af72ea2a7f8a2fcbaad4d78e2c1977
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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<SwxUser> 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<SwxSettings>().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<SwxUser> list = swxUserService.list(new QueryWrapper<SwxUser>().lambda().eq(SwxUser::getPhone,value));
            if(!CollectionUtils.isEmpty(list)){
                return false;
            }
        }
        if(type == SwxConstons.CUSTOMER_REGISTER_CHECK_TYPE_USERNAME){
            List<SwxUser> list = swxUserService.list(new QueryWrapper<SwxUser>().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<SwxUser>().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<SwxSettings>().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<String,Object> 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");
        }
    }
}