| /** | 
|  * Copyright (c) 2018 人人开源 All rights reserved. | 
|  * <p> | 
|  * https://www.renren.io | 
|  * <p> | 
|  * 版权所有,侵权必究! | 
|  */ | 
|   | 
| package com.zt.security.controller; | 
|   | 
| import com.alibaba.fastjson.JSONObject; | 
| import com.zt.common.constant.Constant; | 
| import com.zt.common.exception.ErrorCode; | 
| import com.zt.common.exception.RenException; | 
| import com.zt.common.servlet.Result; | 
| import com.zt.common.utils.IpUtils; | 
| import com.zt.common.validator.AssertUtils; | 
| import com.zt.common.validator.ValidatorUtils; | 
| import com.zt.core.context.User; | 
| import com.zt.core.context.UserContext; | 
| import com.zt.core.security.BCryptPasswordEncoder; | 
| import com.zt.core.security.Md5Utils; | 
| import com.zt.core.sys.model.SysUser; | 
| import com.zt.modules.log.enums.LoginOperationEnum; | 
| import com.zt.modules.log.enums.LoginStatusEnum; | 
| import com.zt.modules.log.model.SysLogLogin; | 
| import com.zt.modules.log.service.SysLogLoginService; | 
| import com.zt.modules.sys.service.SysParamsService; | 
| import com.zt.modules.sys.service.SysUserService; | 
| import com.zt.security.dto.LoginDto; | 
| import com.zt.security.model.LoginInfo; | 
| import com.zt.security.model.LoginUser; | 
| import com.zt.security.service.CaptchaService; | 
| import com.zt.security.service.SysUserTokenService; | 
| import io.swagger.annotations.Api; | 
| import io.swagger.annotations.ApiImplicitParam; | 
| import io.swagger.annotations.ApiOperation; | 
| import org.apache.commons.httpclient.HttpClient; | 
| import org.apache.commons.httpclient.HttpStatus; | 
| import org.apache.commons.httpclient.methods.GetMethod; | 
| import org.apache.commons.httpclient.methods.PostMethod; | 
| import org.springframework.beans.factory.annotation.Autowired; | 
| import org.springframework.beans.factory.annotation.Value; | 
| import org.springframework.http.HttpHeaders; | 
| import org.springframework.web.bind.annotation.GetMapping; | 
| import org.springframework.web.bind.annotation.PostMapping; | 
| import org.springframework.web.bind.annotation.RequestBody; | 
| import org.springframework.web.bind.annotation.RestController; | 
|   | 
| import javax.servlet.http.HttpServletRequest; | 
| import javax.servlet.http.HttpServletResponse; | 
| import javax.servlet.http.HttpSession; | 
| import java.io.BufferedReader; | 
| import java.io.IOException; | 
| import java.io.InputStream; | 
| import java.io.InputStreamReader; | 
| import java.text.ParseException; | 
| import java.text.SimpleDateFormat; | 
| import java.util.Date; | 
| import java.util.HashMap; | 
| import java.util.List; | 
| import java.util.Map; | 
|   | 
| /** | 
|  * 登录 | 
|  * | 
|  * @author hehz | 
|  */ | 
| @RestController | 
| @Api(tags = "登录管理") | 
| public class LoginController { | 
|   | 
|     @Value("${data.menuPos}") | 
|     private String menuPos; | 
|     @Value("${data.debug}") | 
|     private Boolean debug; | 
|     @Value("${data.test}") | 
|     private Boolean test; | 
|   | 
|     @Value("${data.testNewFun}") | 
|     private Boolean testNewFun; | 
|   | 
|     @Autowired | 
|     private SysUserService sysUserService; | 
|     @Autowired | 
|     private SysUserTokenService sysUserTokenService; | 
|     @Autowired | 
|     private CaptchaService captchaService; | 
|     @Autowired | 
|     private SysLogLoginService sysLogLoginService; | 
|     @Autowired | 
|     private SysParamsService paramsService; | 
|   | 
|     @GetMapping("captcha") | 
|     @ApiOperation(value = "验证码", produces = "application/octet-stream") | 
|     @ApiImplicitParam(dataType = Constant.QT.STRING, name = "uuid", required = true) | 
|     public void captcha(HttpServletResponse response, String uuid) throws IOException { | 
|         // uuid不能为空 | 
|         AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL.getCode()); | 
|   | 
|         // 生成验证码 | 
|         captchaService.create(response, uuid); | 
|     } | 
|   | 
|     @PostMapping("loginProcess") | 
|     @ApiOperation(value = "登录") | 
|     public Result loginProcess(HttpServletRequest request, @RequestBody LoginDto login) { | 
|         sysUserTokenService.loginProcess(); | 
|         return Result.ok(); | 
|     } | 
|   | 
|     @PostMapping("login") | 
|     @ApiOperation(value = "登录") | 
|     public Result<Map<String, Object>> login(HttpServletRequest request, @RequestBody LoginDto login) { | 
|         // 效验数据 | 
|         //ValidatorUtils.validateEntity(login); | 
|   | 
|         // 验证码是否正确 | 
| //        if (paramsService.getBooleanValue(Constant.ParamKey.IS_LOGIN_NEED_CAPTURE, true) | 
| //                && !captchaService.validate(login.getUuid(), login.getCaptcha())) { | 
| //            return Result.ok().error(ErrorCode.CAPTCHA_ERROR.getCode()); | 
| //        } | 
|   | 
|         SysLogLogin log = new SysLogLogin(); | 
|         log.setOperation(LoginOperationEnum.LOGIN.value()); | 
|         log.setCreateDate(new Date()); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|         log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|   | 
|         if (testNewFun) { | 
|             singleTest(request, login.getToken(), login.getToken()); | 
|         } | 
|   | 
|         //SysUser user = null; | 
|         // md5加密密码 | 
|         String password = Md5Utils.hash(login.getPassword()); | 
| /*        if (login.getUsername().contains(".")) { | 
|             // 用户名存在域名 | 
|             String code = login.getUsername().split("\\.")[0];  // 获取域名 | 
|             String name = login.getUsername().split("\\.")[1];  // 获取用户名称 | 
|             List<SysUser> userCodeList = sysUserService.isGetByUsernameList(name, null, code, password); | 
|             if (userCodeList.size() <= 0) { | 
|                 throw new RenException(ErrorCode.ACCOUNT_ERROR); | 
|             } else if (userCodeList.size() > 1) { | 
|                 throw new RenException(ErrorCode.ACCOUNT_THERE_ARE_MULTIPLE_ERROR); | 
|             } | 
|             user = userCodeList.get(0); | 
|   | 
|         } else { | 
|             // 用户名不存在域名 | 
|             List<SysUser> userList = sysUserService.isGetByUsernameList(login.getUsername(), null, null, null); | 
|             if (userList.size() > 1) { | 
|                 for (SysUser sysUser : userList) { | 
|                     if (sysUser.getCompanyId() == unitid) { | 
|                         user = userList.get(0); | 
|                         break; | 
|                     } | 
|                 } | 
|             } else if (userList.size() <= 0) { | 
|                 log.setStatus(LoginStatusEnum.FAIL.value()); | 
|                 log.setCreatorName(login.getUsername()); | 
|                 sysLogLoginService.insert(log); | 
|                 throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR); | 
|             } else { | 
|                 user = userList.get(0); | 
|             } | 
|         }*/ | 
|   | 
|         // 用户信息 | 
|         SysUser user = sysUserService.getByUsername(login.getUsername()); | 
|         // 用户不存在 | 
|         if (user == null) { | 
|             log.setStatus(LoginStatusEnum.FAIL.value()); | 
|             log.setCreatorName(login.getUsername()); | 
|             sysLogLoginService.insert(log); | 
|             Map<String, Object> map = new HashMap<>(); | 
|             map.put("info", "用户不存在"); | 
|             return Result.ok().ok(map); | 
|             //throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR); | 
|         } else { | 
|             if (!"single".equals(login.getLoginMethod())) { | 
|                 BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); | 
|                 if (!encoder.matches(login.getPassword(),user.getPassword())){ | 
|                     log.setStatus(LoginStatusEnum.FAIL.value()); | 
|                     log.setCreatorName(login.getUsername()); | 
|                     sysLogLoginService.insert(log); | 
|                     Map<String, Object> map = new HashMap<>(); | 
|                     map.put("info", "密码不正确"); | 
|                     return Result.ok().ok(map); | 
|                 } | 
|             } | 
| /* | 
|             List<SysUser> userList = sysUserService.checkUserArea(user.getId(),localServer); | 
|             if (userList.size()>0){ | 
|                 Map<String, Object> map = new HashMap<>(); | 
|                 //map.put(Constant.Sys.TOKEN_HEADER, token); | 
|                 //map.put("expire", EXPIRE); | 
|                 //map.put("test", test); | 
|                 map.put("info", "该用户不能在该服务器登录"); | 
|                 return Result.ok().ok(map); | 
|             } | 
| */ | 
| /*            String systemId = null; | 
|             if ("smj".equals(login.getSystemMarker())) | 
|                 systemId = "1471651415041593346"; | 
|             else if ("djxl".equals(login.getSystemMarker())) | 
|                 systemId = "1283299421357899778"; | 
|             User user2 = sysUserService.userRoleInfo(login.getUsername(),systemId); | 
|             if (user2==null){ | 
|                 Map<String, Object> map = new HashMap<>(); | 
|                 map.put("info", "用户没有系统权限"); | 
|                 return Result.ok().ok(map); | 
|             }*/ | 
|         } | 
|   | 
|         Date thisErrorLoginTime = null;        // 修改的本次登陆错误时间 | 
|         Integer isLocked = 0; //账号是否被锁定 | 
|         // 密码错误 | 
|         // if (!Md5Utils.hash(login.getPassword()).equals(user.getPassword())) { | 
| //        if (1==0) { | 
| //            log.setStatus(LoginStatusEnum.FAIL.value()); | 
| //            log.setCreator(user.getId()); | 
| //            log.setCreatorName(user.getUsername()); | 
| //            sysLogLoginService.insert(log); | 
| // | 
| ////            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR); | 
| //            if (user.getIsLocked() == null) { | 
| //                user.setIsLocked(0); | 
| //            } else { | 
| //                isLocked = user.getIsLocked(); | 
| //            } | 
| //            if (user.getLoginErrorCount() == null) { | 
| //                user.setLoginErrorCount(0); | 
| //            } | 
| //            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | 
| //            String dateStr = format.format(new Date()); | 
| // | 
| //            try { | 
| //                thisErrorLoginTime = format.parse(dateStr); | 
| //            } catch (ParseException e) { | 
| //                e.printStackTrace(); | 
| //            } | 
| //            if (isLocked == 1) {// 账户被锁定 // 被锁定是登陆错误次数一定是5,所以只判断一次 | 
| //                Date lastLoginErrorTime = null; // 最后一次登陆错误时间 | 
| //                Long timeSlot = 0L; | 
| //                if (user.getLastLoginErrorTime() == null) { | 
| //                    lastLoginErrorTime = thisErrorLoginTime; | 
| //                } else { | 
| //                    lastLoginErrorTime = user.getLastLoginErrorTime(); | 
| //                    timeSlot = thisErrorLoginTime.getTime() - lastLoginErrorTime.getTime(); | 
| //                } | 
| //                if (timeSlot < 1800000) {    // 判断最后锁定时间,30分钟之内继续锁定 | 
| //                    throw new RenException("您的账户已被锁定,请" + (30 - Math.ceil((double) timeSlot / 60000)) + "分钟之后再次尝试"); | 
| //                } else {                                    // 判断最后锁定时间,30分钟之后仍是错误,继续锁定30分钟 | 
| //                    user.setLastLoginErrorTime(thisErrorLoginTime); | 
| //                    sysUserService.updateLogin(user.getId(), null, null, thisErrorLoginTime);//修改用户 | 
| //                    throw new RenException("账户或密码错误,您的账户已被锁定,请30分钟之后再次尝试登陆"); | 
| //                } | 
| //            } else if (user.getLoginErrorCount() == 4) {    // 账户第五次登陆失败  ,此时登陆错误次数增加至5,以后错误仍是5,不再递增 | 
| //                user.setLoginErrorCount(5); | 
| //                user.setIsLocked(1); | 
| //                user.setLastLoginErrorTime(thisErrorLoginTime); | 
| //                sysUserService.updateLogin(user.getId(), 5, 1, thisErrorLoginTime);//修改用户 | 
| //                throw new RenException("您的账户已被锁定,请30分钟之后再次尝试登陆"); | 
| //            } else {                                        // 账户前四次登陆失败 | 
| //                user.setLoginErrorCount(user.getLoginErrorCount() + 1); | 
| //                user.setLastLoginErrorTime(thisErrorLoginTime); | 
| //                sysUserService.updateLogin(user.getId(), user.getLoginErrorCount(), isLocked, thisErrorLoginTime);//修改用户 | 
| //                throw new RenException("账户或密码错误,您还有" + (5 - user.getLoginErrorCount()) + "次登陆机会"); | 
| //            } | 
| //        } else { | 
| //            isLocked = user.getIsLocked(); | 
| //            if (isLocked != null && isLocked == 1) { | 
| //                Date lastLoginErrorTime = null; // 最后一次登陆错误时间 | 
| //                Long timeSlot = 0L; | 
| //                if (user.getLastLoginErrorTime() == null) { | 
| //                    lastLoginErrorTime = new Date(); | 
| //                } else { | 
| //                    lastLoginErrorTime = user.getLastLoginErrorTime(); | 
| //                    timeSlot = new Date().getTime() - lastLoginErrorTime.getTime(); | 
| //                } | 
| //                if (timeSlot < 1800000) {    // 判断最后锁定时间,30分钟之内继续锁定 | 
| //                    throw new RenException("您的账户已被锁定,请" + (30 - Math.ceil((double) timeSlot / 60000)) + "分钟之后再次尝试"); | 
| //                } | 
| //            } | 
| //        } | 
|         // 账号停用 | 
| //        if (user.getStatus() == UserStatus.DISABLE.getValue()) { | 
| //            log.setStatus(LoginStatusEnum.LOCK.value()); | 
| //            log.setCreator(user.getId()); | 
| //            log.setCreatorName(user.getUsername()); | 
| //            sysLogLoginService.insert(log); | 
| // | 
| //            throw new RenException(ErrorCode.ACCOUNT_DISABLE); | 
| //        } | 
| //        sysUserService.updateLogin(user.getId(), 0, 0, null);//修改用户 | 
|         // 登录成功 | 
|         log.setStatus(LoginStatusEnum.SUCCESS.value()); | 
|         log.setCreator(user.getId()); | 
|         log.setCreatorName(user.getUsername()); | 
|         sysLogLoginService.insert(log); | 
|   | 
|         sysUserTokenService.logout(user.getId()); | 
|         Result a = sysUserTokenService.createToken(user.getId(),login.getSystemMarker(),login.getToken()); | 
|         return a; | 
|     } | 
|   | 
|     @GetMapping("singlelogin") | 
|     @ApiOperation(value = "登录") | 
|     public Result<Map<String, Object>> singlelogin(HttpServletRequest request, String token, String systemMarker) { | 
|         // 效验数据 | 
|         SysLogLogin log = new SysLogLogin(); | 
|         log.setOperation(LoginOperationEnum.LOGIN.value()); | 
|         log.setCreateDate(new Date()); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|         log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|   | 
|         HttpClient client = new HttpClient();     //创建Client | 
|         String result = ""; | 
|         try { | 
|             String url="http://127.0.0.1:8066?token="+token; | 
|             GetMethod method = new GetMethod(url); | 
|             System.out.println("token:"+token); | 
|             System.out.println("singleSignUrl:"+url); | 
|             client.executeMethod(method); | 
|             System.out.println("StatusCode:"+method.getStatusCode()); | 
|             if (method.getStatusCode() == HttpStatus.SC_OK) {// 响应成功 | 
|                 System.out.println("HttpStatus.SC_OK:"); | 
|                 //result = method.getResponseBodyAsString();// 调用返回结果 | 
|                 InputStream inputStream = method.getResponseBodyAsStream(); | 
|                 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); | 
|                 StringBuffer stringBuffer = new StringBuffer(); | 
|                 String str= ""; | 
|                 while((str = br.readLine()) != null){ | 
|                     stringBuffer .append(str ); | 
|                 } | 
|                 System.out.println("result stringBuffer.toString():"+stringBuffer.toString()); | 
|                 result = stringBuffer.toString(); | 
|   | 
|                 LoginInfo loginInfo  = JSONObject.parseObject(result, LoginInfo.class); | 
|                 System.out.println("loginInfo:"+loginInfo); | 
|                 System.out.println("loginUser:"+loginInfo.getUser()); | 
|                 System.out.println("loginDept:"+loginInfo.getUser().getDept()); | 
|   | 
|                 // 登录成功 | 
|                 log.setStatus(LoginStatusEnum.SUCCESS.value()); | 
|                 log.setCreator(loginInfo.getUser().getUserId()); | 
|                 log.setCreatorName(loginInfo.getUser().getUserName()); | 
|                 sysLogLoginService.insert(log); | 
|   | 
|                 Result a = sysUserTokenService.createToken(loginInfo.getUser().getUserId(),systemMarker,token); | 
|                 return a; | 
|   | 
|             } else {// 不成功组装结果 | 
|                 System.out.println("远程调用没有返回值"); | 
|             } | 
|         } catch (IOException e) { | 
|             e.printStackTrace(); | 
|         } | 
|         Map<String, Object> map = new HashMap<>(); | 
|         map.put(Constant.Sys.TOKEN_HEADER, token); | 
|         map.put("test", test); | 
|         map.put("info", "单点登录失败"); | 
|   | 
|         return Result.ok().ok(map); | 
|     } | 
|   | 
|     void singleTest(HttpServletRequest request, String token, String systemMarker) { | 
|         if (token != null) { | 
|             HttpClient client = new HttpClient();     //创建Client | 
|             String result = ""; | 
|             try { | 
|                 String url = "http://127.0.0.1:8066/system/user/getLoginUserOfToken?token=" + token; | 
|                 GetMethod method = new GetMethod(url); | 
|                 System.out.println("token:" + token); | 
|                 System.out.println("singleSignUrl:" + url); | 
|                 client.executeMethod(method); | 
|                 System.out.println("StatusCode:" + method.getStatusCode()); | 
|                 if (method.getStatusCode() == HttpStatus.SC_OK) {// 响应成功 | 
|                     System.out.println("HttpStatus.SC_OK:"); | 
|                     //result = method.getResponseBodyAsString();// 调用返回结果 | 
|                     InputStream inputStream = method.getResponseBodyAsStream(); | 
|                     BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); | 
|                     StringBuffer stringBuffer = new StringBuffer(); | 
|                     String str = ""; | 
|                     while ((str = br.readLine()) != null) { | 
|                         stringBuffer.append(str); | 
|                     } | 
|                     System.out.println("result stringBuffer.toString():" + stringBuffer.toString()); | 
|                     result = stringBuffer.toString(); | 
|   | 
|                     LoginInfo loginInfo = JSONObject.parseObject(result, LoginInfo.class); | 
|                     System.out.println("loginInfo:" + loginInfo); | 
|                     System.out.println("loginUser:" + loginInfo.getUser()); | 
|                     System.out.println("loginDept:" + loginInfo.getUser().getDept()); | 
|                 } else {// 不成功组装结果 | 
|                     System.out.println("远程调用没有返回值"); | 
|                 } | 
|             } catch (IOException e) { | 
|                 e.printStackTrace(); | 
|             } | 
|         } | 
|     } | 
|   | 
|     @GetMapping("/system/user/getLoginUserOfToken") | 
|     @ApiOperation(value = "登录") | 
|     public String getLoginUserOfToken(HttpServletRequest request, String username, String token, String systemMarker) { | 
|          LoginInfo loginInfo  = new LoginInfo(); | 
|         LoginUser loginUser  = new LoginUser(); | 
|         loginUser.setUserName(username); | 
|         loginInfo.setUser(loginUser); | 
|         String json = JSONObject.toJSONString(loginInfo); | 
|         return json; | 
|     } | 
|   | 
|     @GetMapping("/system/user/verifyOfToken") | 
|     @ApiOperation(value = "登录") | 
|     public Result<String> verifyOfToken(HttpServletRequest request, String token) { | 
|         return Result.ok(token); | 
|     } | 
|   | 
|     @GetMapping("user/info") | 
|     @ApiOperation("登录用户信息") | 
|     public Result<User> info() { | 
|         return Result.ok(UserContext.getUser()); | 
|     } | 
|   | 
|     @GetMapping("user/userRoleInfo") | 
|     @ApiOperation("菜单登录用户信息") | 
|     public Result<User> userRoleInfo(String systemId) { | 
|         return Result.ok(sysUserService.userRoleInfo(null,systemId)); | 
|     } | 
|   | 
|     @GetMapping("user/userRoles") | 
|     @ApiOperation("菜单登录用户信息") | 
|     public Result<String> userRoles() { | 
|         User user = UserContext.getUser(); | 
|         String roleNames = sysUserService.getRoleNames(user.getId()); | 
|         return Result.ok(roleNames); | 
|     } | 
|   | 
|   | 
|     @GetMapping("user/checkTestHome") | 
|     @ApiOperation("菜单登录用户信息") | 
|     public Result<Integer> checkTestHome(String systemId) { | 
|         return Result.ok(sysUserService.checkTestHome(systemId)); | 
|     } | 
|   | 
|     @GetMapping("user/adminRole") | 
|     @ApiOperation("登录用户信息") | 
|     public Result<JSONObject> adminRole() { | 
|         Map<String,Object> map= sysUserService.adminRole(); | 
|         String roles= sysUserService.getRoles(); | 
|         map.put("roles",roles==null?"":roles); | 
|         map.put("menuPos",menuPos); | 
|         map.put("debug",debug); | 
|         map.put("test",test); | 
|         JSONObject jsonObj=new JSONObject(map); | 
|         return Result.ok(jsonObj); | 
|     } | 
|   | 
|     @GetMapping("loginOut") | 
|     @ApiOperation(value = "退出") | 
|     public Result loginOut(String username) { | 
|         SysUser user = sysUserService.getByUsername(username); | 
|          if (user != null) { | 
|             sysUserTokenService.logout(user.getId()); | 
|         } | 
|         return Result.ok(); | 
|     } | 
|   | 
|     @PostMapping("logout") | 
|     @ApiOperation(value = "退出") | 
|     public Result logout(HttpServletRequest request) { | 
|         User user = UserContext.getUser(); | 
|         // 退出 | 
|         sysUserTokenService.logout(user.getId()); | 
|         // 用户信息 | 
|         SysLogLogin log = new SysLogLogin(); | 
|         log.setOperation(LoginOperationEnum.LOGOUT.value()); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|         log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); | 
|         log.setIp(IpUtils.getIpAddr(request)); | 
|         log.setStatus(LoginStatusEnum.SUCCESS.value()); | 
|         log.setCreator(user.getId()); | 
|         log.setCreatorName(user.getUsername()); | 
|         log.setCreateDate(new Date()); | 
|         sysLogLoginService.insert(log); | 
|   | 
|         return Result.ok(); | 
|     } | 
|   | 
| } |