puzhibing
2023-11-28 7b726d5ff439e7b8bb66369ecc5881e370286bc8
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
package com.stylefeng.guns.modular.system.service.impl;
 
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dao.AppUserMapper;
import com.stylefeng.guns.modular.system.model.AppUser;
import com.stylefeng.guns.modular.system.service.IAppUserService;
import com.stylefeng.guns.modular.system.util.RedisUtil;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import com.stylefeng.guns.modular.system.util.UUIDUtil;
import com.stylefeng.guns.modular.system.util.weChat.WXCore;
import com.stylefeng.guns.modular.system.util.weChat.WeChatUtil;
import com.stylefeng.guns.modular.system.warpper.req.RegisterAccountReq;
import com.stylefeng.guns.modular.system.warpper.res.AppletLoginRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
 
/**
 * @author zhibing.pu
 * @Date 2023/11/7 11:07
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {
 
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private RedisUtil redisUtil;
 
 
    /**
     * 通过token获取用户信息
     * @return
     */
    @Override
    public AppUser getAppUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        if(ToolUtil.isNotEmpty(authorization) && authorization.contains("Bearer")){
            String token = authorization.substring(7);
            //通过token获取用户id
            Integer appUserId = getAppUserIdFromToken(token);
            return this.selectById(appUserId);
        }
        return null;
    }
 
 
 
 
 
 
    /**
     * 小程序登录
     * @param jscode
     * @return
     */
    @Override
    public ResultUtil<AppletLoginRes> appletLogin(String jscode) {
        try {
            //调用微信获取用户小程序openid
            Map<String, Object> map = weChatUtil.code2Session(jscode);
            if(null == map){
                return ResultUtil.error("获取微信身份信息失败");
            }
            String openid = map.get("openid").toString();
            AppUser appUser = this.selectOne(new EntityWrapper<AppUser>()
                    .eq("wechat_openid", openid)
                    .eq("audit_status", 2)
                    .eq("status", 1));
            AppletLoginRes appletLoginRes = new AppletLoginRes();
            if(null != appUser){
                String token = JwtTokenUtil.generateToken(appUser.getPhone());
                appletLoginRes.setToken(token);
            }
            return ResultUtil.success(appletLoginRes);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    /**
     * 小程序注册账号
     * @param req
     * @return
     */
    @Override
    public ResultUtil<AppletLoginRes> registerAccount(RegisterAccountReq req) {
        try {
            //调用微信获取用户小程序openid
            Map<String, Object> map = weChatUtil.code2Session(req.getJscode());
            if(null == map){
                return ResultUtil.error("获取微信身份信息失败");
            }
            String openid = map.get("openid").toString();
            AppUser appUser = this.selectOne(new EntityWrapper<AppUser>()
                    .eq("wechat_openid", openid)
                    .eq("audit_status", 2)
                    .eq("status", 1));
            AppletLoginRes appletLoginRes = new AppletLoginRes();
            if(null == appUser){
                String sessionKey = map.get("sessionKey").toString();
                //解密手机号
                String phone = WXCore.decrypt(req.getEncryptedPhoneData(), sessionKey, req.getPhone_iv());
                appUser = this.selectOne(new EntityWrapper<AppUser>()
                        .eq("phone", phone)
                        .eq("audit_status", 2)
                        .eq("status", 1));
                if(null == appUser){
                    //注册新账号
                    addNewAppUser(openid, phone);
                }else{
                    appUser.setWechatOpenid(openid);
                    this.updateById(appUser);
                }
            }
            //生成token
            String token = JwtTokenUtil.generateToken(appUser.getPhone());
            appletLoginRes.setToken(token);
            //存入缓存中
            addTokenToRedis(token, appUser.getId());
            return ResultUtil.success(appletLoginRes);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    /**
     * 添加新用户到数据库
     * @param openid    微信openid
     * @param phone     手机号
     */
    private void addNewAppUser(String openid, String phone){
        AppUser appUser = new AppUser();
        appUser.setCode(UUIDUtil.getNumberRandom(16));
        appUser.setUserType(1);
        appUser.setPhone(phone);
        appUser.setWechatOpenid(openid);
        appUser.setAuditStatus(2);
        appUser.setStatus(1);
        appUser.setInsertTime(new Date());
        this.insert(appUser);
    }
 
 
    /**
     * 将用户标识存入缓存中用于后期接口的身份校验
     * @param token
     * @param id
     */
    private void addTokenToRedis(String token, Integer id){
        String key = token;
        int length = token.length();
        if(length > 16){
            key = token.substring(4, 12);
        }
        //30天有效期
        redisUtil.setStrValue(key, id.toString(), 2592000);
    }
 
 
    /**
     * 通过token获取用户id
     * @param token
     * @return
     */
    private Integer getAppUserIdFromToken(String token){
        String key = token;
        int length = token.length();
        if(length > 16){
            key = token.substring(4, 12);
        }
        String value = redisUtil.getValue(key);
        if(ToolUtil.isEmpty(value)){
            return 0;
        }
        return Integer.valueOf(value);
    }
}