/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package cn.sn.dadao.modules.sys.web;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import cn.sn.dadao.common.config.Global;
import cn.sn.dadao.common.security.shiro.session.SessionDAO;
import cn.sn.dadao.common.servlet.ValidateCodeServlet;
import cn.sn.dadao.common.utils.CacheUtils;
import cn.sn.dadao.common.utils.CookieUtils;
import cn.sn.dadao.common.utils.IdGen;
import cn.sn.dadao.common.utils.StringUtils;
import cn.sn.dadao.common.web.BaseController;
import cn.sn.dadao.modules.sys.entity.User;
import cn.sn.dadao.modules.sys.security.FormAuthenticationFilter;
import cn.sn.dadao.modules.sys.security.SystemAuthorizingRealm;
import cn.sn.dadao.modules.sys.security.SystemAuthorizingRealm.Principal;
import cn.sn.dadao.modules.sys.service.SystemService;
import cn.sn.dadao.modules.sys.security.UsernamePasswordToken;
import cn.sn.dadao.modules.sys.utils.UserUtils;
/**
* 登录Controller
*
* @author ThinkGem
* @version 2013-5-31
*/
@Controller
public class LoginController extends BaseController {
@Autowired
private SessionDAO sessionDAO;
@Autowired
private SystemAuthorizingRealm systemAuthorizingRealm;
@Autowired
private FormAuthenticationFilter formAuthenticationFilter;
@Autowired
private SystemService systemService;
/**
* 管理登录
*/
@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
Principal principal = UserUtils.getPrincipal();
// // 默认页签模式
// String tabmode = CookieUtils.getCookie(request, "tabmode");
// if (tabmode == null){
// CookieUtils.setCookie(response, "tabmode", "1");
// }
if (logger.isDebugEnabled()) {
logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
}
// 如果已登录,再次访问主页,则退出原账号。
if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
CookieUtils.setCookie(response, "LOGINED", "false");
}
// 如果已经登录,则跳转到管理首页
if (principal != null && !principal.isMobileLogin()) {
return "redirect:" + adminPath;
}
// String view;
// view = "/WEB-INF/views/modules/sys/sysLogin.jsp";
// view = "classpath:";
// view +=
// "jar:file:/D:/GitHub/jeesite/src/main/webapp/WEB-INF/lib/jeesite.jar!";
// view += "/"+getClass().getName().replaceAll("\\.",
// "/").replace(getClass().getSimpleName(), "")+"view/sysLogin";
// view += ".jsp";
return "modules/sys/sysLogin";
}
@ResponseBody
@RequestMapping(value = "${frontPath}/login/ajaxTest", method = RequestMethod.POST)
public Map<String, Object> ajaxTest(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
String da = request.getParameter("da");
map.put("message", "权限测试成功+'"+da+"'");
return map;
}
@ResponseBody
@RequestMapping(value = "${frontPath}/login/appVersion_test", method = RequestMethod.POST)
public Map<String, Object> appVersion(HttpServletRequest request, HttpServletResponse response) {
getRoleJson();
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonarray", getRoleJson());
return map;
}
public JSONObject getRoleJson() {
String path = getClass().getClassLoader().getResource("appVersion.json").toString();
path = path.replace("\\", "/");
if (path.contains(":")) {
// path = path.substring(6);// 1
path = path.replace("file:", "");// 2
}
JSONObject jsonObject = null;
String input;
try {
input = FileUtils.readFileToString(new File(path), "UTF-8");
jsonObject = JSONObject.parseObject(input);
return jsonObject; }
catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
@ResponseBody
@RequestMapping(value = "${adminPath}/login/test", method = RequestMethod.POST)
public Map<String, Object> test(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
String username = request.getParameter("username");
/* Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username,password.toCharArray()));
}catch (Exception e) {
System.out.println(e.getMessage());
map.put("result", e.getMessage());
return map;
}*/
User user= UserUtils.getByLoginName(username);
String dataPass=user.getPassword().substring(16);
//System.out.println(dataPass);
AuthenticationInfo info = systemAuthorizingRealm.doGetAuthenticationInfo(formAuthenticationFilter.createToken(request,response));
//Subject subject = SecurityUtils.getSubject();
// UsernamePasswordToken token = new UsernamePasswordToken();
// subject.login(token);
//System.out.println( info.getPrincipals());
if(info.getCredentials().equals(dataPass)) {
// String sql = "select * from sys_user where LOGIN_NAME='" + username + "' and PASSWORD='" + password + "' ";
// DBHelper.selectList(sql, "select");
// System.out.println(DBHelper.selectList(sql, "select"));
map.put("success", true);
map.put("message", "登录成功");
map.put("username", user.getLoginName());
map.put("name", user.getName());
map.put("id", user.getId());
map.put("status", "0");
map.put("user", user);
map.put("office", user.getOffice().getName());
map.put("company", user.getCompany().getName());
}
else {
map.put("result", "登录失败,账号密码不匹配");
}
return map;
}
@RequestMapping(value = "${adminPath}/login/ajaxlogin", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> ajaxlogin(HttpServletRequest request) {
Map<String, Object> map = Maps.newHashMap();
@SuppressWarnings("unused")
String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() ;
// Principal principalOld = UserUtils.getPrincipal();
// 如果已经登录,则跳转到管理首页
/* if (principalOld != null) {
map.put("message", "请勿重复登录");
map.put("username", principalOld.getLoginName());
map.put("name", principalOld.getName());
map.put("status", "-1");
return map;
} else {*/
String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
User user= UserUtils.getByLoginName(username);
String password = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
// String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
// String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
String host = StringUtils.getRemoteAddr(request);
try {
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, null, mobile);
SecurityUtils.getSubject().login(usernamePasswordToken);
} catch (Exception e) {
map.put("message", "账号密码错误");
map.put("status", "1");
return map;
}
SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal) SecurityUtils.getSubject().getPrincipal();
map.put("success", true);
map.put("message", "登录成功");
map.put("username", principal.getLoginName());
map.put("name", principal.getName());
map.put("id", principal.getId());
map.put("status", "0");
map.put("syspass", user.getPassword());
map.put("user", user);
map.put("office", user.getOffice().getName());
map.put("company", user.getCompany().getName());
return map;
// }
}
/**
* 登录失败,真正登录的POST请求由Filter完成
*/
@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
Principal principal = UserUtils.getPrincipal();
// 如果已经登录,则跳转到管理首页
if (principal != null) {
return "redirect:" + adminPath;
}
String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
message = "用户或密码错误, 请重试.";
}
model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
if (logger.isDebugEnabled()) {
logger.debug("login fail, active session size: {}, message: {}, exception: {}",
sessionDAO.getActiveSessions(false).size(), message, exception);
}
// 非授权异常,登录失败,验证码加1。
if (!UnauthorizedException.class.getName().equals(exception)) {
model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
}
// 验证失败清空验证码
request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
// 如果是手机登录,则返回JSON字符串
if (mobile) {
return renderString(response, model);
}
return "modules/sys/sysLogin";
}
/**
* 登录成功,进入管理首页
*/
@RequiresPermissions("user")
@RequestMapping(value = "${adminPath}")
public String index(HttpServletRequest request, HttpServletResponse response) {
Principal principal = UserUtils.getPrincipal();
// 登录成功后,验证码计算器清零
isValidateCodeLogin(principal.getLoginName(), false, true);
if (logger.isDebugEnabled()) {
logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
}
// 如果已登录,再次访问主页,则退出原账号。
if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
String logined = CookieUtils.getCookie(request, "LOGINED");
if (StringUtils.isBlank(logined) || "false".equals(logined)) {
CookieUtils.setCookie(response, "LOGINED", "true");
} else if (StringUtils.equals(logined, "true")) {
UserUtils.getSubject().logout();
return "redirect:" + adminPath + "/login";
}
}
// 如果是手机登录,则返回JSON字符串
if (principal.isMobileLogin()) {
if (request.getParameter("login") != null) {
return renderString(response, principal);
}
if (request.getParameter("index") != null) {
return "modules/sys/sysIndex";
}
return "redirect:" + adminPath + "/login";
}
// // 登录成功后,获取上次登录的当前站点ID
// UserUtils.putCache("siteId",
// StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));
// System.out.println("==========================a");
// try {
// byte[] bytes = cn.sn.dadao.common.utils.FileUtils.readFileToByteArray(
// cn.sn.dadao.common.utils.FileUtils.getFile("c:\\sxt.dmp"));
// UserUtils.getSession().setAttribute("kkk", bytes);
// UserUtils.getSession().setAttribute("kkk2", bytes);
// } catch (Exception e) {
// e.printStackTrace();
// }
for (int i=0; i<1000000; i++){
//UserUtils.getSession().setAttribute("a", "a");
request.getSession().setAttribute("aaa", "aa");
}
// System.out.println("==========================b");
return "modules/sys/sysIndex";
}
/**
* 获取主题方案
*/
@RequestMapping(value = "/theme/{theme}")
public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request,
HttpServletResponse response) {
if (StringUtils.isNotBlank(theme)) {
CookieUtils.setCookie(response, "theme", theme);
} else {
theme = CookieUtils.getCookie(request, "theme");
}
return "redirect:" + request.getParameter("url");
}
@ResponseBody
@RequestMapping(value = "${frontPath}/user/updatePass", method = RequestMethod.POST)
public Map<String, Object> modifyPwdApp(HttpServletRequest request, HttpServletResponse response) {
User user = UserUtils.getUser();
Map<String, Object> map=new HashMap<String,Object>();
@SuppressWarnings("unused")
String userpass=user.getPassword();
String oldPassword=request.getParameter("oldpassword");
String newPassword=request.getParameter("newpassword");
if (SystemService.validatePassword(oldPassword, user.getPassword())){
systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
map.put("message","修改密码成功");
}else{
}
return map;
}
/**
* 是否是验证码登录
*
* @param useruame
* 用户名
* @param isFail
* 计数加1
* @param clean
* 计数清零
* @return
*/
@SuppressWarnings("unchecked")
public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean) {
Map<String, Integer> loginFailMap = (Map<String, Integer>) CacheUtils.get("loginFailMap");
if (loginFailMap == null) {
loginFailMap = Maps.newHashMap();
CacheUtils.put("loginFailMap", loginFailMap);
}
Integer loginFailNum = loginFailMap.get(useruame);
if (loginFailNum == null) {
loginFailNum = 0;
}
if (isFail) {
loginFailNum++;
loginFailMap.put(useruame, loginFailNum);
}
if (clean) {
loginFailMap.remove(useruame);
}
return loginFailNum >= 3;
}
}