shichongfu
2023-04-25 ce0b49552668d3331055e2b1a1447a743dc54939
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package com.product.admin.controller;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.product.admin.config.CmnConst;
import com.product.admin.config.SystemCode;
import com.product.admin.service.LoginInitParameterService;
import com.product.admin.service.LoginPunchRecordService;
import com.product.admin.service.SystemMenusService;
import com.product.admin.util.ResultInfo;
import com.product.auth.service.EmailAuthService;
import com.product.common.lang.StringUtils;
import com.product.core.cache.DataPoolCacheImpl;
import com.product.core.config.CoreConst;
import com.product.core.config.Global;
import com.product.core.controller.support.AbstractBaseController;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.rsa.GenerateRSAKey;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.service.OnlineDocumentEditService;
import com.product.module.sys.config.SystemErrorCode;
import com.product.module.sys.entity.SystemUser;
import com.product.module.sys.service.UserService;
import com.product.module.sys.version.ApiVersion;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
@RequestMapping
@Controller
public class LoginController extends AbstractBaseController {
    @Autowired
    UserService userService;
    @Autowired
    SystemMenusService systemMenusService;
    @Autowired
    public BaseDao baseDao;
    @Autowired
    EmailAuthService emailAuthService;
    @Autowired
    LoginPunchRecordService loginPunchRecordService;
 
    @Autowired
    OnlineDocumentEditService onlineDocumentEditService;
 
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLogin() {
        logger.info("进入login页面");
        return "login";
    }
 
    @Autowired
    LoginInitParameterService loginInitParameterService;
 
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
 
        Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
        Object userName = null;
        Object pwd = null;
        Object client_type = null;
        Object version = null;
        Object versionUuid = null;
        Object mobile_mac = null;
        RequestParameterEntity reqp = (RequestParameterEntity) bean;
        try {
            if (reqp != null) {
                if (reqp.getFormData() != null) {
                    userName = reqp.getFormData().getObject(CmnConst.USER_ACCOUNT);
                    pwd = reqp.getFormData().getObject(CmnConst.USER_PWD);
                    //nginx代理不支持header中参数含下划线的问题 头部取中划线的
                    client_type = reqp.getOther().get(CoreConst.SYSTEM_CLIENT_TYPE_);
                    version = reqp.getOther().get(CoreConst.SYSTEM_CLIENT_VERSION_);
                    //在主体中取下划线的
                    if (client_type == null)
                        client_type = reqp.getFormData().getObject(CoreConst.SYSTEM_CLIENT_TYPE);//客户端类型保存的是web
                    if (version == null)
                        version = reqp.getFormData().getValue(CoreConst.SYSTEM_CLIENT_VERSION);//版本号
                }
            }
            if (userName == null || pwd == null || StringUtils.isBlank(userName.toString()) || StringUtils.isBlank(pwd.toString())) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_NULL.getText());
            }
            if (version == null) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getText() + CoreConst.SYSTEM_CLIENT_VERSION_);
            } else if (client_type == null) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getText() + CoreConst.SYSTEM_CLIENT_TYPE_);
            } else {
                DataTableEntity table = DataPoolCacheImpl.getInstance().getCacheData("系统版本号", new String[]{client_type.toString(), version.toString()});
                if (table != null && table.getRows() > 0)
                    versionUuid = table.getObject(0, "uuid");
            }
            mobile_mac = reqp.getOther().get(CoreConst.FIELD_MOBILE_MAC);
            SystemUser user = userService.getSystemUserByName(userName.toString());
            if (user != null) {
                //移动设置注册验证
                //是否启用绑定移动端MAC
                if (Global.getPropertyToBoolean("mobile.mac.valid.isEnable", "false") && CoreConst.CLIENT_TYPE_APP.equals(client_type)) {//app端
                    String umac = user.getCurrentStaff().getString("mobile_mac");
                    if (
                            StringUtils.isEmpty(mobile_mac)//必须上传mac地址
                                    || StringUtils.isEmpty(umac)//必须上传mac地址
                                    //|| table.getInt(0,"is_enable")==0 //没有启用
                                    || !mobile_mac.equals(umac)//与库中存的不一致
                    ) {//非法移动设备访问
 
                        throw new BaseException(SystemCode.LOGIN_VALID_FAIL_NOT_MAC.getValue(), SystemCode.LOGIN_VALID_FAIL_NOT_MAC.getText() + mobile_mac);
                    }
                }
                if (user.getStatus() == 0) {
                    //是否有锁定截止时间,如果有,是否过期,过期清除锁定信息,可以登录,否则都不能登录
                    Date d = userService.loginUserStatusProcess(user);
                    //如果没有过锁定截止时间,则返回截止时间,返回给前端
                    if (d != null) {
                        return userService.loginLockBack(d);
                    }
                }
                boolean islogin = userService.loginValid(user, pwd.toString());
                if (islogin) {
                    user.setVersion(version.toString());
                    user.setClientType(client_type.toString());
                    user.setVersionUuid(versionUuid == null ? null : versionUuid.toString());
                    //图形码验证
                    //生成Token
                    userService.createTokenInfor(user);
                    String token = user.getToken_info();
                    //生成刷新Token的Token
                    String refreshToken = userService.createTokenInforRefresh(userName.toString());
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put(CoreConst.ACCESS_TOKEN, token);
                    dataMap.put(CoreConst.REFRESH_TOKEN, refreshToken);
                    response.setHeader(CoreConst.ACCESS_TOKEN, token);
                    response.setHeader(CoreConst.REFRESH_TOKEN, refreshToken);
                    //返回登录用户的语言代码
                    //返回公司是否启用邮件二次认证
                    dataMap.put(com.product.auth.config.CmnConst.IS_ENABLE_AUTH, user.isAgainAuth());
                    dataMap.put("user", userInfo(user));
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put(CoreConst.API_RETURN_KEY_CODE, CoreConst.API_RETURN_VALUE_CODE_200);
                    resultMap.put(CoreConst.API_RETURN_KEY_MSG, CoreConst.API_RETURN_VALUE_MSG_SUCCESS);
                    resultMap.put(CoreConst.API_RETURN_KEY_STATUS, CoreConst.API_RETURN_VALUE_STATUS_SUCCESS);
                    resultMap.put(CoreConst.API_RETURN_KEY_DATA, dataMap);
                    String json = JSON.toJSONString(resultMap);
                    user.setRefreshToken(refreshToken);
 
                    //token与用户关联,放入缓存中
                    DataPoolCacheImpl.getInstance().setSessionUser(user);
 
                    //清除登录失败信息
                    userService.loginSuccessProcess(user);
                    SpringMVCContextHolder.getSystemLogger().writeLog("登录成功", reqp);
                    return json;
                } else {
                    session.setAttribute("user", null);
                    String error = userService.loginFailProcess(user);
                    reqp.getFormData().setValue("user_id", user.getUser_id());
                    reqp.getFormData().setValue("org_level_uuid", user.getOrg_level_uuid());
                    reqp.getFormData().setValue("account_name", user.getUser_account());
                    reqp.getFormData().setValue("log_type", "错误日志");
                    SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText(), reqp);
                    if (error == null) {
                        return this.error(SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText());
                    } else {
                        return error;
                    }
                }
            } else {
 
                SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText(), reqp);
                return this.error(SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText());
            }
        } catch (BaseException e1) {
            SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + e1.getMessageInfo(), reqp);
            return this.error(e1);
        } catch (Exception e1) {
            e1.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + e1.getMessage(), reqp);
            return this.error(SystemErrorCode.SYSTEM_LOGIN_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ERROR.getText() + e1.getMessage());
        }
 
    }
 
    @ResponseBody
    @PostMapping("/user-system-param/{version}")
    @ApiVersion(1)
    public String getLoginInitParameters() {
        try {
            return loginInitParameterService.getLoginParameter();
        } catch (BaseException e) {
            e.printStackTrace();
            return error(e);
        } catch (Exception e) {
            e.printStackTrace();
            return error(SystemCode.GET_LOGIN_PARAM_FAIL.getValue(), SystemCode.GET_LOGIN_PARAM_FAIL.getText());
        }
    }
 
 
    /**
     * 用户名密码加密码后验证
     *
     * @param request
     * @param response
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String doLoginV1(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
 
        Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
        Object userName = null;
        Object pwd = null;
        Object client_type = null;
        Object version = null;
        Object versionUuid = null;
        Object mobile_mac = null;
        String userId = null;
        RequestParameterEntity reqp = (RequestParameterEntity) bean;
        try {
            if (reqp != null) {
                if (reqp.getFormData() != null) {
                    userName = reqp.getFormData().getObject(CmnConst.USER_ACCOUNT);
                    //是否启用登录用户名密码的非对称加密
                    boolean isEnable = Global.getPropertyToBoolean("login.ecc.isEnable", "false");
                    if (userName != null && isEnable) {
                        //用户名解密
                        userName = GenerateRSAKey.decrypt_str(userName.toString());
                        reqp.getFormData().setValue(CmnConst.USER_ACCOUNT, userName);
                    }
                    pwd = reqp.getFormData().getObject("user_pwd");
 
                    if (pwd != null && isEnable) {
                        //密码解密
                        pwd = GenerateRSAKey.decrypt_str(pwd.toString());
                        reqp.getFormData().setValue("user_pwd", pwd);
                    }
                    //nginx代理不支持header中参数含下划线的问题 头部取中划线的
                    client_type = reqp.getOther().get(CoreConst.SYSTEM_CLIENT_TYPE_);
                    version = reqp.getOther().get(CoreConst.SYSTEM_CLIENT_VERSION_);
                    if (client_type == null)
                        client_type = reqp.getFormData().getObject(CoreConst.SYSTEM_CLIENT_TYPE);//客户端类型保存的是web
                    if (version == null)
                        version = reqp.getFormData().getValue(CoreConst.SYSTEM_CLIENT_VERSION);//版本号
                }
            }
            if (userName == null || pwd == null || StringUtils.isBlank(userName.toString()) || StringUtils.isBlank(pwd.toString())) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_NULL.getText());
            }
            if (version == null) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getText() + CoreConst.SYSTEM_CLIENT_VERSION_);
            } else if (client_type == null) {
                return this.error(SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_PARA_ERROR.getText() + CoreConst.SYSTEM_CLIENT_TYPE_);
            } else {
                DataTableEntity table = DataPoolCacheImpl.getInstance().getCacheData("系统版本号", new String[]{client_type.toString(), version.toString()});
                if (table != null && table.getRows() > 0)
                    versionUuid = table.getObject(0, "uuid");
            }
            mobile_mac = reqp.getOther().get(CoreConst.FIELD_MOBILE_MAC);
 
            SystemUser user = userService.getSystemUserByName(userName.toString());
            if (user != null) {
                userId = user.getUser_id() + "";
                //移动设置注册验证
                //是否启用绑定移动端MAC
                if (Global.getPropertyToBoolean("mobile.mac.valid.isEnable", "false")
                        && CoreConst.CLIENT_TYPE_APP.equals(client_type)) {//app端
                    String umac = user.getCurrentStaff().getString("mobile_mac");
                    if (
                            StringUtils.isEmpty(mobile_mac)//必须上传mac地址
                                    || StringUtils.isEmpty(umac)//必须上传mac地址
                                    //|| table.getInt(0,"is_enable")==0 //没有启用
                                    || !mobile_mac.equals(umac)//与库中存的不一致
                    ) {//非法移动设备访问
 
                        throw new BaseException(SystemCode.LOGIN_VALID_FAIL_NOT_MAC.getValue(), SystemCode.LOGIN_VALID_FAIL_NOT_MAC.getText() + mobile_mac);
                    }
                }
                if (user.getStatus() == 0) {
                    //是否有锁定截止时间,如果有,是否过期,过期清除锁定信息,可以登录,否则都不能登录
                    Date d = userService.loginUserStatusProcess(user);
                    //如果没有过锁定截止时间,则返回截止时间,返回给前端
                    if (d != null) {
                        return userService.loginLockBack(d);
                    }
                }
                boolean islogin = userService.loginValid(user, pwd.toString());
                if (islogin) {
                    user.setVersion(version.toString());
                    user.setClientType(client_type.toString());
                    user.setVersionUuid(versionUuid == null ? null : versionUuid.toString());
                    //图形码验证
                    //生成Token
                    userService.createTokenInfor(user);
                    String token = user.getToken_info();
                    //生成刷新Token的Token
                    String refreshToken = userService.createTokenInforRefresh(userName.toString());
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put(CoreConst.ACCESS_TOKEN, token);
                    dataMap.put(CoreConst.REFRESH_TOKEN, refreshToken);
                    response.setHeader(CoreConst.ACCESS_TOKEN, token);
                    response.setHeader(CoreConst.REFRESH_TOKEN, refreshToken);
 
                    //返回公司是否启用邮件二次认证
//                    if(Global.getPropertyToBoolean("mail.auth.isEnable", "false")) {
                    dataMap.put(com.product.auth.config.CmnConst.IS_ENABLE_AUTH, user.isAgainAuth());
//                    }
 
                    //登录生成打卡信息
//                    loginPunchRecordService.autoCreatePunchInfo();
 
                    //返回前端消息服务器的ip地址
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put(CoreConst.API_RETURN_KEY_CODE, CoreConst.API_RETURN_VALUE_CODE_200);
                    resultMap.put(CoreConst.API_RETURN_KEY_MSG, CoreConst.API_RETURN_VALUE_MSG_SUCCESS);
                    resultMap.put(CoreConst.API_RETURN_KEY_STATUS, CoreConst.API_RETURN_VALUE_STATUS_SUCCESS);
                    resultMap.put(CoreConst.API_RETURN_KEY_DATA, dataMap);
                    String json = JSON.toJSONString(resultMap);
                    user.setRefreshToken(refreshToken);
                    //token与用户关联,放入缓存中
                    DataPoolCacheImpl.getInstance().setSessionUser(user);
                    //清除登录失败信息
                    userService.loginSuccessProcess(user);
                    SpringMVCContextHolder.getSystemLogger().writeLog("登录成功", reqp);
                    return json;
                } else {
                    session.setAttribute("user", null);
                    String error = userService.loginFailProcess(user);
                    reqp.getFormData().setValue("user_id", user.getUser_id());
                    reqp.getFormData().setValue("org_level_uuid", user.getOrg_level_uuid());
                    reqp.getFormData().setValue("account_name", user.getUser_account());
                    reqp.getFormData().setValue("log_type", "错误日志");
                    SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText(), reqp);
                    if (error == null) {
                        return this.error(SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText());
                    } else {
                        return error;
                    }
 
                }
            } else {
                reqp.getFormData().setValue("account_name", userName);
                reqp.getFormData().setValue("log_type", "错误日志");
                SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:用户信息为空", reqp);
                return this.error(SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ACCOUNT_PWD_ERROR.getText());
            }
        } catch (BaseException e1) {
            reqp.getFormData().setValue("account_name", userName);
            reqp.getFormData().setValue("log_type", "错误日志");
            SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + e1.getMessageInfo(), reqp);
            e1.printStackTrace();
            return this.error(e1);
        } catch (Exception e1) {
            reqp.getFormData().setValue("account_name", userName);
            reqp.getFormData().setValue("log_type", "错误日志");
            SpringMVCContextHolder.getSystemLogger().writeLog("登录失败:" + e1.getMessage(), reqp);
            e1.printStackTrace();
            return this.error(SystemErrorCode.SYSTEM_LOGIN_ERROR.getValue(), SystemErrorCode.SYSTEM_LOGIN_ERROR.getText() + e1.getMessage());
        } finally {
            if (userId != null) {
                //清空正在编辑的缓存
                onlineDocumentEditService.clearBeingEditDocumentStatus(userId);
            }
        }
    }
 
    /**
     * 登录返回用户信息
     *
     * @param user
     * @return json 对象
     */
    private JSONObject userInfo(SystemUser user) throws BaseException {
        return loginInitParameterService.getUserInfo(user, null);
    }
 
    /**
     * 更新当前登录用户信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "update-user-info/{version}", method = RequestMethod.POST)
    @ApiVersion(1)
    public String updateLoginUserInfo(HttpServletRequest request) {
        try {
            SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
            // xupencheng updateTime 2020年11月30日10:19:43 调用用户信息 判断类型更新user状态
            if (currentUser != null && !StringUtils.isEmpty(currentUser.getUpdateType())) {
                if (com.product.admin.config.CmnConst.UPDATE_MENU_USER.equals(currentUser.getUpdateType())) {
                    currentUser.setUpdateType(com.product.admin.config.CmnConst.UPDATE_MENU);
                } else if (CmnConst.UPDATE_USER.equals(currentUser.getUpdateType())) {
                    currentUser.setUpdateType(null);
                }
            }
            Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
            RequestParameterEntity reqp = (RequestParameterEntity) bean;
            if (reqp != null) {
                FieldSetEntity fse = reqp.getFormData();
                if (fse != null) {
                    String org_level_uuid = fse.getString("org_level_uuid");
                    if (!StringUtils.isEmpty(org_level_uuid) && currentUser != null) {
                        currentUser.changeCompany(org_level_uuid);
                    }
                }
            }
            DataPoolCacheImpl.getInstance().setSessionUser(currentUser);
            JSONObject userInfo = loginInitParameterService.getUserInfo(currentUser, null);
            return ResultInfo.success(userInfo);
        } catch (BaseException e) {
            return this.error(e);
        } catch (Exception e) {
            e.printStackTrace();
            return error(SystemCode.SYSTEM_UPDATE_USER_INFO_FIAL.getValue(),
                    SystemCode.SYSTEM_UPDATE_USER_INFO_FIAL.getText());
        }
    }
 
}