1
lige
2023-09-12 b17a6795e6774805d66cc01d92f8933ae616b83e
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
package com.ltkj.framework.web.service;
 
import javax.annotation.Resource;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ltkj.common.constant.CacheConstants;
import com.ltkj.common.exception.user.CaptchaException;
import com.ltkj.common.exception.user.CaptchaExpireException;
import com.ltkj.common.utils.*;
import com.ltkj.common.utils.sign.RsaUtils;
import com.ltkj.framework.config.JwtUtils;
import com.ltkj.framework.config.UserHoder;
import com.ltkj.hosp.domain.TjCustomer;
import com.ltkj.hosp.service.ITjCustomerService;
import com.ltkj.system.service.ISysMenuService;
import com.ltkj.system.service.SysParametersDisposeService;
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 com.ltkj.system.service.ISysUserService;
 
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;
 
    @Autowired
    private SysParametersDisposeService parametersDisposeService;
 
    // 是否允许账户多终端同时登录(true允许 false不允许)
    @Value("${token.soloLogin}")
    private boolean soloLogin;
 
 
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password, Boolean type,String code,String uuid) {
 
        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 {
            //登录密码解密
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, RsaUtils.decryptByPrivateKey(password));
            //UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            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();
        recordLoginInfo(Long.valueOf(loginUser.getUserId()));
 
//       限制账户不允许多终端登录
        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 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;
    }
}