2
13693261870
2022-09-16 653761a31dfeb50dd3d007e892d69c90bf0cdafc
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package com.landtool.lanbase.modules.sys.controller;
 
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.landtool.lanbase.common.Constant;
import com.landtool.lanbase.common.annotation.LogLogininfo;
import com.landtool.lanbase.common.exception.LanbaseException;
import com.landtool.lanbase.common.shiro.ShiroToken;
import com.landtool.lanbase.common.utils.CoderUtils;
import com.landtool.lanbase.common.utils.HttpUtils;
import com.landtool.lanbase.common.utils.RedisUtils;
import com.landtool.lanbase.common.utils.Result;
import com.landtool.lanbase.common.utils.ShiroUtils;
import com.landtool.lanbase.config.SysTemPropertyConfig;
import com.landtool.lanbase.modules.org.entity.OrgUser;
import com.landtool.lanbase.modules.org.service.OrgUserService;
import com.landtool.lanbase.modules.sys.redis.OnlineUserRedis;
import com.landtool.lanbase.modules.sys.service.SysUserTokenService;
 
import springfox.documentation.annotations.ApiIgnore;
 
/**
 * @author lanbase
 * @Description: TODO(登录相关)
 * @date 2017-6-23 15:07
 */
@RestController
@ApiIgnore()
public class SysLoginController extends AbstractController {
 
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    @Autowired
    private Producer producer;
    @Autowired
    private OrgUserService orgUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysTemPropertyConfig sysConfig;
 
    @Autowired
    private OnlineUserRedis onlineUserRedis;
    @Autowired
    private RedisUtils redisUtils;
    /**
     * 在线人数map
     */
    private static ConcurrentHashMap<String,Object> onlineuser=new ConcurrentHashMap<String,Object>();
    
    
    /**
     * 首页
     * 
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public void hutaiadmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("/res/ZiYuanZhongXin/index?Menu=ZYZX&menuId=07");
        // cannot call sendRedirect() after the response has been commited
        // 1、resopnse 重定向后没有return
        // 2、重定向后还有重定向,重复的重定向
        return;
    }
 
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
 
        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
 
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
 
    /**
     * 获取登录错误次数
     */
    @RequestMapping(value = "/sys/getLoginErrorTimes", method = RequestMethod.GET)
    public Result getLoginErrorTimes() {
        Object errorTimes = ShiroUtils.getSessionAttribute(Constant.LOGIN_ERROR_TIMES);
        return Result.ok().put("errorTimes", errorTimes);
    }
 
    /**
     * 登录
     */
    @LogLogininfo("登录")
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public Result login(String username, String password, String captcha) throws IOException {
        Object _login_errors = ShiroUtils.getSessionAttribute(Constant.LOGIN_ERROR_TIMES);
        if (_login_errors == null) {
            _login_errors = 0;
        }
        long errorTimes = Long.valueOf(_login_errors.toString());
 
        // 用户信息
        OrgUser user = orgUserService.queryByUserName(username);
 
        // 账号不存在
        if (user == null) {
            ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES, ++errorTimes);
            return Result.error("账号不存在").put("errorTimes", errorTimes);
        }
 
        // 密码错误
        try {
            if (!user.getPassword().equals(CoderUtils.lantuEncryptMD5(password))) {
                ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES, ++errorTimes);
                return Result.error("密码不正确").put("errorTimes", errorTimes);
            }
        } catch (Exception e) {
    
            e.printStackTrace();
        }
 
        // 验证码
        if (errorTimes >= 3) {
            String kaptcha = getKaptcha(Constants.KAPTCHA_SESSION_KEY);
            if (!captcha.equalsIgnoreCase(kaptcha)) {
                ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES, ++errorTimes);
                return Result.error("验证码不正确").put("errorTimes", errorTimes);
            }
        }
 
        // 账号锁定
        if (Constant.UserStatus.DISABLE.getValue() == user.getUserstatus()) {
            ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES, ++errorTimes);
            return Result.error("账号已被锁定,请联系管理员").put("errorTimes", errorTimes);
        }
 
        // 生成token,并保存到数据库
        Map<String, Object> result = sysUserTokenService.createToken(user.getUserid());
        Result r = Result.ok().put(result);
        return r;
    }
 
    private String getLoginNamefromXml(HttpServletRequest request) throws Exception {
        String username = "";
 
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        username = session.getAttribute("shirousername") == null ? ""
                : session.getAttribute("shirousername").toString();
        logger.debug("4----shirousername:" + session.getAttribute("shirousername") + (session.getId()));
        if (org.springframework.util.StringUtils.isEmpty(username)) {
            String CasHost = sysConfig.getCasHost();// https://cas.nmsmp.com/cas/
            String loginUrl = sysConfig.getLoginUrl(); // http://127.0.0.1:8082/login
 
            String ticket = request.getParameter("ticket");
 
            if (!org.springframework.util.StringUtils.isEmpty(ticket)) {
                String server = getOldQueryString(request);
                String url = CasHost.replace("https", "http");
                String validateurl = url + "serviceValidate?ticket=" + ticket + "&service=" + loginUrl + "?oldurl="
                        + URLEncoder.encode(server);
                ;
 
                logger.debug("2----ServiceValidate:" + validateurl);
 
                String casxml;
                casxml = HttpUtils.get(validateurl);
                logger.debug(casxml);
                Integer index = casxml.indexOf("<cas:user>");
                Integer end = casxml.indexOf("</cas:user>");
 
                if (index > 0) {
                    username = casxml.substring(index + 10, end);
                }
            }
        }
        return username;
    }
 
    @LogLogininfo("登录")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    @ResponseBody
    public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getRemoteUser();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        response.getWriter().write(username + "登陆成功!");
    }
 
    /**
     * oa门户反验证 获取地址上的validatename,调用反验证接口获取结果,为true,则允许登录
     */
 
    public JSONObject portallogin(HttpServletRequest request) {
        String result = "";
        String querystring = request.getQueryString();
        String username = "";
        if (querystring != null) {
            String par[] = querystring.split("&");
            for (int i = 0; i < par.length; i++) {
                String a = par[i].split("=")[0];
                String v = par[i].split("=")[1];
                if (a.equals("validateNumber")) {
                    String validateurl = "http://192.168.4.50/services/PortalLoginService/ValidLoginUser?validateNumber="
                            + v;
                    try {
                        result = HttpUtils.get(validateurl);
                    } catch (Exception e) {
                        logger.info(result);
                        e.printStackTrace();
                    }
                }
                if (a.equals("userName")) {
                    username = v;
                }
            }
            int start = result.indexOf("<ns:return>");
            int end = result.indexOf("</ns:return>");
            if (start != -1 && end != -1) {
                JSONObject json = JSONObject.parseObject(result.substring(start + 11, end));
                json.put("username", username);
 
                return json;
            }
        }
        return null;
 
    }
 
    /**
     * CAS登陆成功后调用此方法创建本系统的token
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @LogLogininfo("登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getRemoteUser();
        if (StringUtils.hasText(username)) {// 已经登录shiro
            String oldUrl = getOldParameterPath(request);
            response.sendRedirect(oldUrl);
            // WebUtils.issueRedirect(request, response, oldUrl);
//        } else {
//
//            // oa门户登录判断
//            JSONObject validateresult = portallogin(request);
//            if (validateresult != null && "true".equals(validateresult.getString("validateResult"))) {
//                String oldUrl = getOldParameterPath(request);
//                Subject subject = SecurityUtils.getSubject();
//                ShiroToken shiroToken = new ShiroToken(validateresult.getString("username"), true);
//                subject.login(shiroToken);
//                WebUtils.issueRedirect(request, response, oldUrl);
            } else {
 
                username = getLoginNamefromXml(request);
//                username="kanglinchong";
//                username="liujin";
//                username="hanzhicong";
 
                if (StringUtils.hasText(username)) {
                    OrgUser user = orgUserService.queryByUserName(username);
                    // 账号不存在
                    if (user == null) {
                        response.getWriter().write("[" + username + "]账号不存在或未注册到系统");
                        return;
                    }
                    Subject subject = SecurityUtils.getSubject();
                    ShiroToken shiroToken = new ShiroToken(username, true);
                    
                    if (!subject.isAuthenticated()) {
                        subject.login(shiroToken);
                        logger.debug("8----loginshiro:");
                    }
                    //这里算用户登录成功 ,存入名称和当前毫秒数kv入在线map add by zsx
                    
                    onlineUserRedis.saveOnlineUser(username,subject.getSession());
                    
                    
                    Session session = subject.getSession(true);
                    session.setAttribute("shirousername", username);
                    // session.setMaxInactiveInterval(sysConfig.getSessionTimeOut());//
                    // 设置Session的超时时间
                    // 单位秒
                    logger.debug("3----shirousername:" + session.getAttribute("shirousername").toString()
                            + (session.getId()));
                    String oldUrl = getOldQueryString(request);
 
                    logger.debug("3----RedirectOldurl:" + oldUrl);
                    // WebUtils.issueRedirect(request, response, oldUrl);
                    response.sendRedirect(oldUrl);
                } else {
                    String CasHost = sysConfig.getCasHost();// https://cas.nmsmp.com/cas/
                    String loginUrl = sysConfig.getLoginUrl(); // http://127.0.0.1:8082/login
                    String oldurl = getOldSessionPath(request);
                    if (StringUtils.hasText(oldurl)) {
                        CasHost += "login?service=" + loginUrl + "?oldurl=" + URLEncoder.encode(oldurl);
                    }
                    logger.debug("1----RedirectCasloginUrl:" + CasHost);
                    response.sendRedirect(CasHost);// 用户名不存在跳转回登录页面
                }
            }
        }
    
 
    private String getOldQueryString(HttpServletRequest request) {
        String server = request.getQueryString();
        String ticket = request.getParameter("ticket");
        if (!org.springframework.util.StringUtils.isEmpty(ticket)) {
            server = server.replace("ticket=" + ticket, "");
            if (server.endsWith("&"))
                server = server.substring(0, server.length() - 1);
        }
        server = server.replace("oldurl=", "");
        return server;
    }
 
    /***
     * 获取原始访问路径
     * 
     * @return
     */
    private String getOldParameterPath(HttpServletRequest request) {
        String oldUrl = request.getParameter("oldurl");
        oldUrl = (oldUrl == null) ? "/" : oldUrl;
        return oldUrl;
    }
 
    /***
     * 获取原始访问路径
     * 
     * @return
     */
    private String getOldSessionPath(HttpServletRequest request) {
        String oldurl = getOldParameterPath(request);
        if (oldurl == "/") {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            SavedRequest req = (SavedRequest) session.getAttribute(WebUtils.SAVED_REQUEST_KEY);
            oldurl = (req == null) ? "" : req.getRequestUrl();
        }
        return oldurl;
    }
 
    /**
     * CAS登陆成功后调用此方法创建本系统的token 返回jsonp
     * 
     * @param request
     * @param response
     * @return
     */
    @LogLogininfo("登录")
    @RequestMapping(value = "/sys/caslogin2", method = RequestMethod.GET)
    @ResponseBody
    public String caslogin2(HttpServletRequest request, HttpServletResponse response) {
        String callbackFunName = request.getParameter("callback"); // js回调函数名称
        if (callbackFunName == null || callbackFunName.isEmpty()) {
            callbackFunName = "casloginCallback";
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        return "";// getJsonp(caslogin(request, response), callbackFunName);
    }
 
    /**
     * 转化为jsonp字符串
     * 
     * @param map
     * @param callbackFunName
     * @return
     */
    private String getJsonp(Map<String, Object> map, String callbackFunName) {
        String jsonp = JSONUtils.toJSONString(map);
        return callbackFunName + "(" + jsonp + ")";
    }
 
    /**
     * 退出
     * 
     * @throws IOException
     */
    @LogLogininfo("登出")
    @RequestMapping(value = "/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        
        
        subject.logout();
        ////移除在线人数 add by zsx
        onlineUserRedis.cleanLogoutUser(subject.getSession());
        
    
        String CasHost = sysConfig.getCasHost();
        String logoutUrl = CasHost + "logout?service=" + CasHost + "login";
        WebUtils.issueRedirect(request, response, logoutUrl);
    
        // sysUserTokenService.logout(getUserId());
        // return Result.ok();
    }
 
    /**
     * 从session中获取记录的验证码
     */
    private String getKaptcha(String key) {
        Object kaptcha = ShiroUtils.getSessionAttribute(key);
        if (kaptcha == null) {
            throw new LanbaseException("验证码已失效");
        }
        ShiroUtils.getSession().removeAttribute(key);
        return kaptcha.toString();
    }
    
    
//    /**
//     * 定时判断,查询用户最近一次操作时间 若最近一次时间超过5分钟,则判断用户下线
//     */
//    @Scheduled(fixedRate=2*60*1000)
//    public void cleanMayDownUser(){
//        onlineUserRedis.removeDownlineUser();
//    }
 
}