liujie
2023-05-22 9f2315d92cc93f8f431805a10ea9ce3f79fa7eb2
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
package com.stylefeng.guns.modular.api;
 
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.PaymentIntent;
import com.stripe.net.Webhook;
import com.stripe.param.PaymentIntentUpdateParams;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.system.dao.TCompanyMapper;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.TCompany;
import com.stylefeng.guns.modular.system.model.TUser;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.model.UserInfo;
import com.stylefeng.guns.modular.system.service.ITUserService;
import com.stylefeng.guns.modular.system.utils.EmailUtil;
import com.stylefeng.guns.modular.system.utils.RedisUtil;
import com.stylefeng.guns.modular.system.utils.tips.SuccessTip;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
 
/**
 * 接口控制器提供
 *
 * @author stylefeng
 * @Date 2018/7/20 23:39
 */
@RestController
@Api(tags = "登录")
@RequestMapping("/gunsApi")
public class ApiController extends BaseController {
 
 
    @Resource
    private TCompanyMapper companyMapper;
 
    @Resource
    private ITUserService userService;
 
    @Autowired
    private RedisUtil redisUtil;
    /**
     * api登录接口,通过账号密码获取token
     */
 
    @PostMapping("/companyLogin")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String")
    })
    public Object companyLogin(@RequestParam("username") String username,
                       @RequestParam("password") String password) {
 
 
        //获取数据库中的账号密码,准备比对
        List<TUser> user = userService.selectList(new EntityWrapper<TUser>().eq("account",username));
        if (user.size()==0) {
            return new ErrorTip(500, "Account password error!");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
//        String credentials = user.getPassword();
//        String salt = user.getSalt();
//        ByteSource credentialsSalt = new Md5Hash(salt);
//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
//                new ShiroUser(), credentials, credentialsSalt, "");
 
        //校验用户账号密码
//        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
//        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
//        md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);
//        boolean passwordTrueFlag = md5CredentialsMatcher.doCredentialsMatch(
//                usernamePasswordToken, simpleAuthenticationInfo);
        String encrypt = MD5Util.encrypt(password);
        if (!encrypt.equals(user.get(0).getPassword())) {
            return new ErrorTip(500, "Account password error!");
        } else {
            TUser tUser = user.get(0);
            HashMap<String, Object> result = new HashMap<>();
            result.put("token", JwtTokenUtil.generateToken(String.valueOf(tUser.getId())));
            result.put("user", tUser);
            // 1需要完善信息
            if(tUser.getPhone()==null){
                result.put("userInfo", 1);
            }else {
                result.put("userInfo", 2);
            }
 
            return result;
        }
    }
 
 
 
 
    private ShiroUser shiroUser(User user) {
        ShiroUser shiroUser = new ShiroUser();
 
        shiroUser.setId(user.getId());
        shiroUser.setAccount(user.getAccount());
        shiroUser.setDeptId(user.getDeptid());
        shiroUser.setDeptName(ConstantFactory.me().getDeptName(user.getDeptid()));
        shiroUser.setName(user.getName());
 
        Integer[] roleArray = Convert.toIntArray(user.getRoleid());
        List<Integer> roleList = new ArrayList<Integer>();
        List<String> roleNameList = new ArrayList<String>();
        for (int roleId : roleArray) {
            roleList.add(roleId);
            roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
        }
        shiroUser.setRoleList(roleList);
        shiroUser.setRoleNames(roleNameList);
 
        return shiroUser;
    }
 
    /**
     * 测试接口是否走鉴权
     */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public Object test() {
        return SUCCESS_TIP;
    }
 
 
    @PostMapping("/forget")
    @ApiOperation(value = "忘记密码", notes = "忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String"),
    })
    public Object forget(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         @RequestParam("code") String code) {
        List<TUser> user = userService.selectList(new EntityWrapper<TUser>().eq("account",username));
        String value = redisUtil.getValue(username);
        if(!code.equals(value)){
            return new ErrorTip(5001, "Verification code error!");
        }
        if (user.size()==0){
            return new ErrorTip(500, "账号不存在!");
        }
        user.get(0).setPassword(MD5Util.encrypt(password));
        userService.updateById(user.get(0));
        return new SuccessTip();
    }
 
 
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyName", value = "companyName", required = true, dataType = "String"),
            @ApiImplicitParam(name = "email", value = "email", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "password", required = true, dataType = "String"),
    })
    public Object register(@RequestParam("companyName") String companyName,
                         @RequestParam("email") String email,
                         @RequestParam("code") String code,
                           @RequestParam("password") String password) {
        String value = redisUtil.getValue(email);
        if(!code.equals(value)){
            return new ErrorTip(5001, "Verification code error!");
        }
        TUser tUser = new TUser();
        tUser.setCompanyName(companyName);
        tUser.setAccount(email);
        tUser.setEmail(email);
        tUser.setPassword(SecureUtil.md5(password));
        userService.insert(tUser);
        return new SuccessTip();
    }
 
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "用户邮箱", required = true, dataType = "String"),
    })
    public Object sendCode(@RequestParam("email") String email) {
        String randomNumber = getRandomString(6);
        redisUtil.setStrValue(email,randomNumber,300);
        try {
            EmailUtil.sendMailGMail(email, randomNumber);
            return new com.stylefeng.guns.core.base.tips.SuccessTip();
        }catch (Exception e){
            e.printStackTrace();
            return new ErrorTip(500,"ERROR");
        }
    }
 
    private  String getRandomString(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
 
        for(int i = 0; i < length; ++i) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
 
        return sb.toString();
    }
 
 
    /**
     * 支付回调处理方法。
     *
     * @param payload 事件负载数据(JSON 格式字符串)
     * @param sigHeader Stripe 签名头信息
     */
    @RequestMapping(value = "returnUrl")
    public void handlePaymentWebhook(String payload, String sigHeader) {
        // 从 Stripe 获取 Webhook 私钥
        String webhookSecret = "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";
 
        try {
            // 验证签名并解析负载数据
            PaymentIntent paymentIntent = (PaymentIntent) Webhook.constructEvent(payload, sigHeader, webhookSecret).getData().getObject();
            // 处理付款意向状态
            if (paymentIntent.getStatus().equals("succeeded")) {
                // 如果付款已成功,请在此处添加成功后的逻辑
 
                // 将付款意向状态更新为已处理
                PaymentIntentUpdateParams updateParams =
                        PaymentIntentUpdateParams.builder()
                                .setMetadata(
                                        new HashMap<String, String>() {{
                                            put("handled", "true");
                                        }})
                                .build();
                paymentIntent.update(updateParams);
            }
        } catch (SignatureVerificationException e) {
            // 如果签名无效,则记录并丢弃此事件
            e.printStackTrace();
        } catch (Exception e) {
            // 在处理任何其他异常情况时,应该记录错误并尽快通知管理员
            e.printStackTrace();
        }
    }
}