UserController.java 5.98 KB
package com.bsth.controller.sys;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bsth.common.Constants;
import com.bsth.common.ResponseCode;
import com.bsth.controller.BaseController;
import com.bsth.controller.sys.util.RSAUtils;
import com.bsth.entity.sys.SysUser;
import com.bsth.security.util.SecurityUtils;
import com.bsth.service.sys.SysUserService;

@RestController
@RequestMapping("user")
public class UserController extends BaseController<SysUser, Integer> {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	SysUserService sysUserService;
	
	@RequestMapping(value = "/login/jCryptionKey")
	public Map<String, Object> jCryptionKey(HttpServletRequest request){
		//公匙返回页面
		Map<String, Object> rs = new HashMap<>();
		rs.put("publickey", RSAUtils.generateBase64PublicKey());
		return rs;
	}
	
	//需要验证码的账号
	public static Map<String, Integer> captchaMap = new HashMap<>();

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Map<String, Object> login(HttpServletRequest request, @RequestParam String userName,
			@RequestParam String password, String captcha) {
		
		Map<String, Object> rs = new HashMap<>();
		rs.put("status", ResponseCode.ERROR);
		try {
			HttpSession session = request.getSession();
			rs.put("captcha", session.getAttribute("captcha"));
			
			if(captchaMap.get(userName) != null && captchaMap.get(userName) >= 3){
				//校验验证码
				String verCode = (String) session
						.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
				
				if(StringUtils.isBlank(captcha))
					return put(rs, "msg", "请输入验证码");
				
				if(!verCode.equals(captcha))
					return put(rs, "msg", "验证码有误,请刷新后重新输入");
			}
			
			//解密RSA
			userName = RSAUtils.decryptBase64(userName);
			password = RSAUtils.decryptBase64(password);
			
			SysUser user = sysUserService.findByUserName(userName);
			if (null == user) 
				return put(rs, "msg", "不存在的用户");
			
			if (!user.isEnabled()) 
				return put(rs, "msg", "该用户已被锁定,请联系管理员");
			
			// 校验密码
			boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
			if (!matchStatus) {
				rs.put("msg", "密码有误");
				
				Integer captchSize = captchaMap.get(userName);
				if(null == captchSize)
					captchSize = 0;
				
				captchSize ++;
				captchaMap.put(userName, captchSize);
				return rs;
			}

			// 登录
			SecurityUtils.login(user, request);
			//session里写入用户名,webSocket连接时标识身份用
			session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
			
			captchaMap.remove(userName);
			rs.put("status", ResponseCode.SUCCESS);
		} catch (Exception e) {
			logger.error("", e);
			rs.put("msg", "服务器出现异常,请联系管理员");
		}
		return rs;
	}
	
	@RequestMapping(value = "/login/captchaStatus")
	public int captchaStatus(String userName){
		Integer size = captchaMap.get(userName);
		return size == null?0:size;
	}
	
	public Map<String, Object> put(Map<String, Object> rs, String key, Object val){
		rs.put(key, val);
		return rs;
	}

	/**
	 * 
	 * @Title: loginFailure @Description: TODO(查询登录失败的详细信息) @param @param
	 * request @return String 返回类型 @throws
	 */
	@RequestMapping("/loginFailure")
	public String loginFailure(HttpServletRequest request) {
		String msg = "";
		HttpSession session = request.getSession();

		Object obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");

		if (obj instanceof BadCredentialsException)
			msg = "登录失败,用户名或密码错误.";
		else if (obj instanceof SessionAuthenticationException)
			msg = "登录失败,当前策略不允许重复登录.";
		session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
		return msg;
	}

	@RequestMapping("/currentUser")
	public SysUser currentUser() {
		return SecurityUtils.getCurrentUser();
	}

	/**
	 * @Title changeEnabled
	 * @Description: TODO(改变用户状态)
	 * @param id
	 *            用户ID
	 * @param enabled
	 *            状态
	 * @return
	 */
	@RequestMapping("/changeEnabled")
	public int changeEnabled(@RequestParam int id, @RequestParam int enabled) {
		return sysUserService.changeEnabled(id, enabled);
	}

	/**
	 * @Title changePWD
	 * @Description: TODO(修改密码)
	 * @param oldPWD
	 *            原始密码
	 * @param newwPWD
	 *            新密码
	 * @param cnewPWD
	 *            确认新密码
	 * @return
	 */
	@RequestMapping("/changePWD")
	public String changePWD(@RequestParam String oldPWD, @RequestParam String newPWD, @RequestParam String cnewPWD) {
		SysUser sysUser = SecurityUtils.getCurrentUser();
		String msg = "";
		if (new BCryptPasswordEncoder(4).matches(oldPWD, sysUser.getPassword())) {
			if (oldPWD.equals(newPWD)) {
				msg = "新密码不能跟原始密码一样!";
			} else {
				if (newPWD.equals(cnewPWD)) {
					sysUserService.changePWD(sysUser.getId(), newPWD);
					msg = "修改成功!";
				} else {
					msg = "新密码两次输入不一致!";
				}
			}
		} else {
			msg = "原始密码错误!";
		}
		return msg;
	}
}