zjh
2025-03-10 ac120ff7d3239da85c05d0ec7f8d8e416d557432
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
package com.ltkj.framework.web.service;
 
import javax.annotation.Resource;
 
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ltkj.common.constant.CacheConstants;
import com.ltkj.common.core.domain.entity.SysDept;
import com.ltkj.common.enums.DataSourceType;
import com.ltkj.common.exception.CustomException;
import com.ltkj.common.exception.user.CaptchaException;
import com.ltkj.common.exception.user.CaptchaExpireException;
import com.ltkj.common.exception.user.SecretKeyException;
import com.ltkj.common.utils.*;
import com.ltkj.common.utils.sign.RsaUtils;
import com.ltkj.db.DataSourceConfig;
import com.ltkj.db.DataSourceContextHolder;
import com.ltkj.framework.config.JwtUtils;
import com.ltkj.framework.config.UserHoder;
import com.ltkj.hosp.domain.DictHosp;
import com.ltkj.hosp.domain.TjCustomer;
import com.ltkj.hosp.service.IDictHospService;
import com.ltkj.hosp.service.ITjCustomerService;
import com.ltkj.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ltkj.common.constant.Constants;
import com.ltkj.common.core.domain.entity.SysUser;
import com.ltkj.common.core.domain.model.LoginUser;
import com.ltkj.common.core.redis.RedisCache;
import com.ltkj.common.exception.ServiceException;
import com.ltkj.common.exception.user.UserPasswordNotMatchException;
import com.ltkj.common.utils.ip.IpUtils;
import com.ltkj.framework.manager.AsyncManager;
import com.ltkj.framework.manager.factory.AsyncFactory;
import com.ltkj.framework.security.context.AuthenticationContextHolder;
 
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 登录校验方法
 *
 * @author ltkj
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;
 
    @Resource
    private AuthenticationManager authenticationManager;
 
    @Autowired
    private RedisCache redisCache;
 
    @Autowired
    private ISysUserService userService;
    @Resource
    private ITjCustomerService customerService;
 
    @Resource
    private ISysMenuService menuService;
    @Resource
    private IDictHospService hospService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysParametersDisposeService parametersDisposeService;
    @Autowired
    private ISysConfigService configService;
 
    // 是否允许账户多终端同时登录(true允许 false不允许)
    @Value("${token.soloLogin}")
    private boolean soloLogin;
 
    @Value("${token.secret_key}")
    private String secret;
 
    @Value("${token.secret_key_login}")
    private boolean secretKeyLogin;
    @Autowired
    private DataSourceConfig dataSourceConfig;
 
 
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password, Boolean type,String code,String uuid,String hospId) {
 
        DataSourceContextHolder.setDataSourceKey(DataSourceType.MASTER.name());
        LambdaQueryWrapper<DictHosp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictHosp::getCode,hospId);
        DictHosp hosp = hospService.getOne(wrapper);
 
        DataSourceContextHolder.setDataSourceKey(hosp.getDbname());
        String aSwitch = configService.selectConfigByKey("captcha_switch");
        if(null !=aSwitch && aSwitch.equalsIgnoreCase("Y")){
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
 
        // 用户验证
        Authentication authentication = null;
        try {
            //登录密码解密
            String s = RsaUtils.decryptByPrivateKey(password);
//            String s = password;
            if(username.equals("10001")){
                s=username+s;
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,s);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.setHospDB(hosp.getDbname());
        loginUser.setHospId(hospId);
        tokenService.setLoginUser(loginUser);
 
        recordLoginInfo(Long.valueOf(loginUser.getUserId()));
        //校验商家过期否
        if (secretKeyLogin)
        {
            Long userId =loginUser.getUser().getUserId();
            SysUser user = userService.getById(userId);
            if(null !=user && null !=user.getDeptId()){
                    SysDept sysDept = deptService.getById(user.getDeptId());
                    if (null != sysDept) {
                        DictHosp dictHosp = hospService.getById(sysDept.getHospId());
                        if(null !=dictHosp){
                            loginUser.setHospName(dictHosp.getHospAreaName());
                            if(!SecurityUtils.isAdmin(user.getUserId())){
                                if(dictHosp.getSecretKey() != null && dictHosp.getExpirationTime() != null){
                                    if (!SecurityUtils.matchesMallMerchantSecretKey(secret,dictHosp.getHospAreaId(),dictHosp.getHospAreaName(),
                                            dictHosp.getExpirationTime(),dictHosp.getSecretKey()) || new Date().after(DateUtil.endOfDay(dictHosp.getExpirationTime()))) {
                                        throw new SecretKeyException("商家已过期请续费使用");
                                    }
                                    long between = DateUtil.between(new Date(), DateUtil.endOfDay(dictHosp.getExpirationTime()), DateUnit.DAY);
                                    if(between<=30){
                                        loginUser.setMessage("还有 "+between+" 天到期 请注意续费! 以免影响正常使用!");
                                    }else {
                                        loginUser.setMessage(null);
                                    }
                                }else {
                                    throw new SecretKeyException("请缴费使用");
                                }
                        }
                    }
                }
 
            }else {
                throw new CustomException("请绑定商家");
            }
 
        }
 
//       限制账户不允许多终端登录
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录,清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                if (!type) {
                    return null;
                } else {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }
        }
        UserHoder.setLoginUser(loginUser);
        // 生成token
        return tokenService.createToken(loginUser);
    }
 
    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
 
 
    /**
     * 客户登录验证
     *
     * @param username 手机号
     * @param password 密码
     * @return 结果
     */
    public String Cuslogin(String username, String password, Boolean type,String code,String uuid) {
 
        String aSwitch = configService.selectConfigByKey("captcha_switch");
        if(null !=aSwitch && aSwitch.equalsIgnoreCase("Y")){
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
 
 
        LoginUser loginUser = loadCusByCusname(username, password);
        if (loginUser == null) {
            return "用户名或密码错误";
        }
//       限制账户不允许多终端登录
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录,清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                if (!type) {
                    return null;
                } else {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }
 
    public LoginUser loadCusByCusname(String username, String password) {
        LambdaQueryWrapper<TjCustomer> wq = new LambdaQueryWrapper<>();
        wq.eq(TjCustomer::getCusPhone, username);
        List<TjCustomer> customerList = customerService.list(wq);
        if (null == customerList || customerList.size() == 0) {
            //throw new ServiceException("登录用户:" + username + " 不存在");
            throw new ServiceException("账号或密码错误,请检查!");
        }
        for (TjCustomer tjCustomer : customerList) {
            try {
                password = RsaUtils.decryptByPrivateKey(password);
                boolean b = SecurityUtils.matchesPassword(password, tjCustomer.getCusPassword());
                if (b) {
                    return createLoginCus(tjCustomer);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
 
    public LoginUser createLoginCus(TjCustomer customer) {
        LoginUser loginCus = new LoginUser();
        SysUser user1 = new SysUser();
        user1.setNickName(customer.getCusName());
        loginCus.setUser(user1);
        loginCus.setUserId("cus" + customer.getCusId());
        loginCus.setPermissions(menuService.selectMenuPermsByRoleId(customer.getRole()));
        return loginCus;
    }
}