111
k94314517
2023-08-18 709298cfae022fb0753d27c4d4143e93284fe22e
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
package doumeemes.service.system.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import doumeemes.biz.system.SystemDictDataBiz;
import doumeemes.config.shiro.ShiroToken;
import doumeemes.core.constants.ResponseStatus;
import doumeemes.core.exception.BusinessException;
import doumeemes.core.model.LoginUserInfo;
import doumeemes.core.utils.Constants;
import doumeemes.core.utils.HttpsUtil;
import doumeemes.core.utils.Utils;
import doumeemes.dao.business.model.Company;
import doumeemes.dao.business.model.CompanyUser;
import doumeemes.dao.business.model.Department;
import doumeemes.dao.ext.CompanyExtMapper;
import doumeemes.dao.ext.CompanyUserExtMapper;
import doumeemes.dao.ext.DepartmentExtMapper;
import doumeemes.dao.ext.dto.QueryCompanyUserExtDTO;
import doumeemes.dao.ext.dto.WxLoginDTO;
import doumeemes.dao.ext.vo.CompanyUserExtListVO;
import doumeemes.dao.ext.vo.WxLoginVO;
import doumeemes.dao.system.SystemUserMapper;
import doumeemes.dao.system.dto.LoginDTO;
import doumeemes.dao.system.model.SystemLoginLog;
import doumeemes.dao.system.model.SystemUser;
import doumeemes.service.common.CaptchaService;
import doumeemes.service.ext.CompanyExtService;
import doumeemes.service.ext.CompanyUserExtService;
import doumeemes.service.system.SystemLoginLogService;
import doumeemes.service.system.WxLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
 
/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Rk
 * @create 2023/8/11 10:14
 */
@Slf4j
@Service
public class WxLoginServiceImpl implements WxLoginService {
 
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
 
 
    @Value("${project.version}")
    private String systemVersion;
 
    @Autowired
    private CompanyUserExtMapper companyUserExtMapper;
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private DepartmentExtMapper departmentExtMapper;
 
    @Autowired
    private SystemLoginLogService systemLoginLogService;
    @Autowired
    private CompanyExtMapper companyExtMapper;
 
 
    /**
     * 微信公众号获取TOKEN地址
     */
    public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
 
    /**
     * 微信公众号获取USERINFO信息地址
     */
    public static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
 
 
    @Override
    public WxLoginVO wxLogin(String code, HttpServletRequest request) {
        WxLoginVO wxLoginVO = new WxLoginVO();
        String appId = systemDictDataBiz.queryByCode(Constants.WX_CONFIG,Constants.APPID).getCode();
        String appSecret = systemDictDataBiz.queryByCode(Constants.WX_CONFIG,Constants.APPSECRET).getCode();
        String getTokenUrl = GET_ACCESS_TOKEN_URL.replace("CODE", code).replace("APPID", appId).replace("SECRET", appSecret);
        JSONObject tokenJson = JSONObject.parseObject(HttpsUtil.get(getTokenUrl,true));
        if(Objects.isNull(tokenJson.get("access_token"))){
            throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),tokenJson.getString("errmsg"));
        }
        String accessToken = tokenJson.getString("access_token");
        String openId = tokenJson.getString("openid");
        String getUserInfoUrl = GET_USER_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        JSONObject userInfoJson = JSONObject.parseObject(HttpsUtil.get(getUserInfoUrl,true));
        wxLoginVO.setOpenid(openId);
        wxLoginVO.setUnionid(userInfoJson.getString("unionid"));
        CompanyUser companyUser = companyUserExtMapper.selectOne(new QueryWrapper<CompanyUser>().eq("openid",openId).last(" limit 1 "));
        if(Objects.isNull(companyUser)){
            wxLoginVO.setLoginStatus(Constants.ONE);
            return wxLoginVO;
        }
        Department department = departmentExtMapper.selectById(companyUser.getRootDepartId());
        if(Objects.isNull(department)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到绑定部门信息");
        }
        Company company = companyExtMapper.selectById(department.getCompanyId());
        if(Objects.isNull(company)||company.getStatus().equals(Constants.ONE)){
            wxLoginVO.setLoginStatus(Constants.ONE);
            return wxLoginVO;
        }
        SystemUser systemUser = systemUserMapper.selectById(companyUser.getUserId());
        //查询用户数据
        LoginDTO dto = new LoginDTO();
        dto.setCompanyId(department.getCompanyId());
        dto.setUsername(systemUser.getUsername());
        SystemLoginLog loginLog = new SystemLoginLog();
        loginLog.setLoginUsername(dto.getUsername());
        loginLog.setLoginTime(new Date());
        loginLog.setSystemVersion(systemVersion);
        loginLog.setIp(Utils.User_Client.getIP(request));
        loginLog.setLocation(Utils.Location.getLocationString(loginLog.getIp()));
        loginLog.setPlatform(Utils.User_Client.getPlatform(request));
        loginLog.setClientInfo(Utils.User_Client.getBrowser(request));
        loginLog.setOsInfo(Utils.User_Client.getOS(request));
        loginLog.setServerIp(Utils.Server.getIP());
        // 校验用户名和密码
        Subject subject = SecurityUtils.getSubject();
        ShiroToken token = new ShiroToken(dto.getCompanyId(),dto.getUsername(), null,false,true);
        try {
            subject.login(token);
            LoginUserInfo loginUser = ((LoginUserInfo)subject.getPrincipal());
            loginLog.setUserId(loginUser.getId());
            loginLog.setCompanyId(loginUser.getCompany()!=null?loginUser.getCompany().getId():null);
            loginLog.setCompanyUserId(loginUser.getCompanyUser()!=null?loginUser.getCompanyUser().getId():null);
            loginLog.setSuccess(Boolean.TRUE);
            systemLoginLogService.create(loginLog);
            String session = (String)subject.getSession().getId();
            wxLoginVO.setLoginStatus(Constants.ZERO);
            wxLoginVO.setSession(session);
            return wxLoginVO;
        }catch (BusinessException e) {
            wxLoginVO.setLoginStatus(Constants.ONE);
            return wxLoginVO;
        }catch (AuthenticationException e) {
            BusinessException ee = null;
            loginLog.setSuccess(Boolean.FALSE);
            if(e.getCause()!=null && e.getCause() instanceof  BusinessException){
                ee =   (BusinessException)e.getCause();
                loginLog.setReason(ee.getMessage().length() > 200 ? (ee.getMessage().substring(0, 190) + "...") : ee.getMessage());
                log.error(ee.getMessage(), e);
            }else{
                log.error(ResponseStatus.ACCOUNT_INCORRECT.getMessage(), e);
                loginLog.setReason(e.getMessage().length() > 200 ? (e.getMessage().substring(0, 190) + "...") : e.getMessage());
                ee = new BusinessException(ResponseStatus.ACCOUNT_INCORRECT);
            }
            systemLoginLogService.create(loginLog);
            throw  ee;
        }
    }
 
 
 
    @Override
    public String wxLoginByPassword(WxLoginDTO dto, HttpServletRequest request) {
        SystemLoginLog loginLog = new SystemLoginLog();
        loginLog.setLoginUsername(dto.getUsername());
        loginLog.setLoginTime(new Date());
        loginLog.setSystemVersion(systemVersion);
        loginLog.setIp(Utils.User_Client.getIP(request));
        loginLog.setLocation(Utils.Location.getLocationString(loginLog.getIp()));
        loginLog.setPlatform(Utils.User_Client.getPlatform(request));
        loginLog.setClientInfo(Utils.User_Client.getBrowser(request));
        loginLog.setOsInfo(Utils.User_Client.getOS(request));
        loginLog.setServerIp(Utils.Server.getIP());
        // 校验用户名和密码
        Subject subject = SecurityUtils.getSubject();
        ShiroToken token = new ShiroToken(dto.getCompanyId(),dto.getUsername(), dto.getPassword(),false,false);
        try {
            subject.login(token);
            LoginUserInfo loginUser = ((LoginUserInfo)subject.getPrincipal());
            loginLog.setUserId(loginUser.getId());
            loginLog.setCompanyId(loginUser.getCompany()!=null?loginUser.getCompany().getId():null);
            loginLog.setCompanyUserId(loginUser.getCompanyUser()!=null?loginUser.getCompanyUser().getId():null);
            loginLog.setSuccess(Boolean.TRUE);
            systemLoginLogService.create(loginLog);
            //登录携带微信openid信息
            if(StringUtils.isNotBlank(dto.getOpenid())){
                CompanyUser companyUser = companyUserExtMapper.selectById(loginLog.getCompanyUserId());
                if(StringUtils.isBlank(companyUser.getOpenid())||!companyUser.getOpenid().equals(dto.getOpenid())){
                    //1、绑定微信openid到companyUser表信息
                    companyUser.setOpenid(dto.getOpenid());
                    companyUser.setUnionid(dto.getUnionid());
                    companyUserExtMapper.updateById(companyUser);
                    //2、清空同用户其余companyUser表openid与 unionid
                    companyUserExtMapper.update(null,new UpdateWrapper<CompanyUser>()
                            .ne("ID",companyUser.getId()).set("UNIONID","").set("OPENID","")
                            .eq("USER_ID",companyUser.getUserId())
                    );
                }
            }
            return (String)subject.getSession().getId();
        }catch (AuthenticationException e) {
            BusinessException ee = null;
            loginLog.setSuccess(Boolean.FALSE);
            if(e.getCause()!=null && e.getCause() instanceof  BusinessException){
                ee =   (BusinessException)e.getCause();
                loginLog.setReason(ee.getMessage().length() > 200 ? (ee.getMessage().substring(0, 190) + "...") : ee.getMessage());
                log.error(ee.getMessage(), e);
            }else{
                log.error(ResponseStatus.ACCOUNT_INCORRECT.getMessage(), e);
                loginLog.setReason(e.getMessage().length() > 200 ? (e.getMessage().substring(0, 190) + "...") : e.getMessage());
                ee = new BusinessException(ResponseStatus.ACCOUNT_INCORRECT);
            }
            systemLoginLogService.create(loginLog);
            throw  ee;
        }
    }
 
}