This commit is contained in:
xiangwb
2017-11-07 09:18:24 +08:00
parent f85d2a825c
commit c7a1e35989
18 changed files with 446 additions and 203 deletions
@@ -27,14 +27,14 @@ public class CommonConstant {
/**
* 邮件服务器配置项
*/
public static final String SYSCONFIG_EMAILCONFIGKEY = "email_config";
public static final String EMAIL_KEY = "email_config";
/**
*
* 当前登录用户
*/
public static final String SESSION_CURRENT_USER = "current_user";
public static final String CURRENT_USER = "current_user";
/**
* 当前登录用户id
*/
public static final String SESSION_CURRENT_USER_ID = "current_id";
public static final String CURRENT_USER_ID = "current_id";
}
@@ -1,7 +1,10 @@
package com.xwbing.constant;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.List;
/**
* 说明: 公共枚举
@@ -10,12 +13,15 @@ import java.util.stream.Collectors;
* 作者: xiangwb
*/
public class CommonEnum {
public enum YesOrNo {
private CommonEnum() {
}
public enum YesOrNoEnum {
YES("是", "Y"), NO("否", "N");
private String name;
private String code;
YesOrNo(String name, String code) {
YesOrNoEnum(String name, String code) {
this.name = name;
this.code = code;
}
@@ -29,21 +35,18 @@ public class CommonEnum {
}
}
/**
* 登录登出标记
*/
public enum LoginInOut {
IN("登录", 1), OUT("登出", 2);
public enum SexEnum {
MAN("男", "1"), WOMAN("女", "0");
private String name;
private int value;
private String code;
LoginInOut(String name, int value) {
SexEnum(String name, String code) {
this.name = name;
this.value = value;
this.code = code;
}
public int getValue() {
return value;
public String getCode() {
return code;
}
public String getName() {
@@ -51,34 +54,25 @@ public class CommonEnum {
}
}
public enum ValidateResultEnum {
SUCCESS("校验通过", 1), FAILED("校验失败", 0);
private String msg;
private int errorCode;
ValidateResultEnum(String msg, int errorCode) {
this.msg = msg;
this.errorCode = errorCode;
}
public String getMsg() {
return this.msg;
}
public int getErrorCode() {
return this.errorCode;
}
}
public static void main(String[] args) {
String code = "Y";
for (YesOrNo yesOrNo : YesOrNo.values()) {
if (yesOrNo.getCode().equals(code)) {
System.out.println(yesOrNo.getName());
break;
}
// for (YesOrNoEnum yesOrNoEnum : YesOrNoEnum.values()) {
// if (yesOrNoEnum.getCode().equals(code)) {
// System.out.println(yesOrNoEnum.getName());
// break;
// }
// }
YesOrNoEnum yesOrNoEnum = Arrays.stream(YesOrNoEnum.values()).filter(obj -> obj.getCode().equals(code)).findFirst().get();
System.out.println(yesOrNoEnum.getName());
List<JSONObject> resultVos = new ArrayList<>();
JSONObject jsonObject;
for (YesOrNoEnum status : YesOrNoEnum.values()) {
jsonObject = new JSONObject();
jsonObject.put("code", status.getCode());
jsonObject.put("name", status.getName());
resultVos.add(jsonObject);
}
YesOrNo yesOrNo = Arrays.stream(YesOrNo.values()).filter(obj -> obj.getCode().equals(code)).collect(Collectors.toList()).get(0);
System.out.println(yesOrNo.getName());
// return resultVos;
}
}
@@ -5,7 +5,6 @@ import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.Pattern;
@@ -22,11 +21,11 @@ public class SysConfig extends BaseEntity {
private static final long serialVersionUID = -7587016038432881980L;
public static String table = "system_config";
/**
* 配置项的key
* 配置项的code
*/
@NotBlank(message = "配置项的key不能为空")
@Length(min = 1, max = 50, message = "key长度为1-50")
private String key;
@NotBlank(message = "配置项的code不能为空")
@Length(min = 1, max = 50, message = "code长度为1-50")
private String code;
/**
* 配置项的值
*/
@@ -43,7 +42,5 @@ public class SysConfig extends BaseEntity {
*/
@NotBlank(message = "是否启用不能为空")
@Pattern(regexp = "[Y|N]",message = "是否启用格式为Y|N")
@Column(name = "is_enable")
private String isEnable;
private String enable;
}
@@ -26,15 +26,27 @@ public class SysUser extends BaseEntity {
* 用户名
*/
@NotBlank(message = "用户名不能为空")
@Length(min = 1, max = 20, message = "长度为1-20")
@Length(min = 1, max = 20, message = "用户名长度为1-20")
@Column(name = "user_name")
private String userName;
/**
* 姓名
*/
@NotBlank(message = "姓名不能为空")
@Length(min = 1, max = 20, message = "长度为1-5")
@Length(min = 1, max = 20, message = "姓名长度为1-5")
private String name;
/**
* 邮箱
*/
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式有误")
private String mail;
/**
* 性别
*/
@NotBlank(message = "性别不能为空")
@Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男")
private String sex;
/**
* 盐值
*/
@@ -44,14 +56,11 @@ public class SysUser extends BaseEntity {
*/
private String password;
/**
* 邮箱
* 是否为管理员
*/
@Email
private String mail;
/**
* 性别
*/
@NotBlank
@Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男")
private String sex;
private String admin;
//临时字段
private transient String create;
private transient String modified;
private transient String sexName;
}
@@ -3,12 +3,16 @@ package com.xwbing.repository;
import com.xwbing.entity.SysConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* 说明:
* 项目名称: boot-module-demo
* 创建时间: 2017/5/5 16:44
* 作者: xiangwb
*/
public interface SysConfigRepository extends JpaRepository<SysConfig,String> {
SysConfig findByKey(String code);
public interface SysConfigRepository extends JpaRepository<SysConfig, String> {
SysConfig findByCode(String code);
List<SysConfig> findByEnable(String enable);
}
@@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* 说明:
@@ -22,21 +23,22 @@ import java.util.Date;
public class SysConfigService {
@Autowired
private SysConfigRepository sysConfigRepository;
private static Logger logger= LoggerFactory.getLogger(SysConfigService.class);
private static Logger logger = LoggerFactory.getLogger(SysConfigService.class);
public RestMessage save(SysConfig sysConfig) {
logger.info("保存配置信息");
RestMessage result = new RestMessage();
sysConfig.setId(PassWordUtil.createId());
sysConfig.setCreateTime(new Date());
if (sysConfig==null) {
if (sysConfig == null) {
throw new BusinessException("配置数据不能为空");
}
SysConfig old = findByKey(sysConfig.getKey());
if (old!=null) {
throw new BusinessException(sysConfig.getKey() + "已存在");
SysConfig old = findByCode(sysConfig.getCode());
if (old != null) {
throw new BusinessException(sysConfig.getCode() + "已存在");
}
sysConfig.setId(PassWordUtil.createId());
sysConfig.setCreateTime(new Date());
SysConfig one = sysConfigRepository.save(sysConfig);
if (one!=null) {
if (one != null) {
result.setSuccess(true);
result.setMessage("保存配置成功");
} else {
@@ -48,8 +50,8 @@ public class SysConfigService {
public RestMessage removeByCode(String code) {
logger.info("删除配置信息");
RestMessage result = new RestMessage();
SysConfig old = findByKey(code);
if (old==null) {
SysConfig old = findByCode(code);
if (old == null) {
throw new BusinessException("该配置项不存在");
}
sysConfigRepository.delete(old.getId());
@@ -58,7 +60,30 @@ public class SysConfigService {
return result;
}
public SysConfig findByKey(String key) {
return sysConfigRepository.findByKey(key);
public RestMessage update(SysConfig sysConfig) {
RestMessage result = new RestMessage();
SysConfig old = findByCode(sysConfig.getCode());
if (old == null) {
throw new BusinessException("该配置项不存在");
}
old.setValue(sysConfig.getValue());
old.setEnable(sysConfig.getEnable());
old.setModifiedTime(new Date());
SysConfig save = sysConfigRepository.save(old);
if (save != null) {
result.setMessage("更新成功");
result.setSuccess(true);
} else {
result.setMessage("更新失败");
}
return result;
}
public SysConfig findByCode(String code) {
return sysConfigRepository.findByCode(code);
}
public List<SysConfig> findByEnable(String enable) {
return sysConfigRepository.findByEnable(enable);
}
}
@@ -2,18 +2,19 @@ package com.xwbing.service;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.constant.CommonConstant;
import com.xwbing.constant.CommonEnum;
import com.xwbing.entity.SysConfig;
import com.xwbing.entity.SysUser;
import com.xwbing.util.CommonDataUtil;
import com.xwbing.entity.model.EmailModel;
import com.xwbing.exception.BusinessException;
import com.xwbing.repository.UserRepository;
import com.xwbing.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@@ -25,9 +26,9 @@ import java.util.List;
*/
@Service
public class UserService {
@Autowired
@Resource
private UserRepository userRepository;
@Autowired
@Resource
private SysConfigService sysConfigService;
/**
@@ -48,25 +49,16 @@ public class UserService {
String[] res = PassWordUtil.getUserSecret(null, null);
sysUser.setSalt(res[1]);
sysUser.setPassword(res[2]);
// 设置否管理员
sysUser.setAdmin(CommonEnum.YesOrNoEnum.NO.getCode());
SysUser one = userRepository.save(sysUser);
if (one == null) {
throw new BusinessException("新增用户失败");
}
SysConfig sysConfig = sysConfigService.findByKey(CommonConstant.SYSCONFIG_EMAILCONFIGKEY);
if (sysConfig==null) {
throw new BusinessException("没有查找到邮件配置项");
}
EmailModel emailModel = null;
if (StringUtils.isNotEmpty(sysConfig.getKey())) {
JSONObject jsonObject = JSONObject.parseObject(sysConfig.getValue());
emailModel = JSONObject.toJavaObject(jsonObject, EmailModel.class);
}
emailModel.setToEmail(sysUser.getMail());
emailModel.setSubject(emailModel.getSubject());
emailModel.setCentent(emailModel.getCentent() + " 你的用户名是:" + sysUser.getUserName() + "密码是:" + res[0]);
//发送邮件
boolean send = sendEmail(sysUser, res[0]);
// 发送邮件结束
boolean sucess = EmailUtil.sendTextEmail(emailModel);
if (!sucess) {
if (!send) {
throw new BusinessException("发送密码邮件错误");
}
result.setSuccess(true);
@@ -85,7 +77,14 @@ public class UserService {
if (old == null) {
throw new BusinessException("该对象不存在");
}
if (id.equals(CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID))) {
throw new BusinessException("不能删除当前登录用户");
}
if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) {
throw new BusinessException("不能对管理员进行删除操作");
}
userRepository.delete(id);
result.setMessage("删除成功");
result.setSuccess(true);
return result;
@@ -103,17 +102,24 @@ public class UserService {
if (old == null) {
throw new BusinessException("该对象不存在");
}
if (old.getId().equals(CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID))) {
throw new BusinessException("不能修改当前登录用户");
}
if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) {
throw new BusinessException("不能对管理员进行修改操作");
}
// 根据实际情况补充
old.setName(sysUser.getName());
old.setMail(sysUser.getMail());
old.setSex(sysUser.getSex());
old.setUserName(sysUser.getUserName());
old.setModifiedTime(new Date());
// old.setUserName(sysUser.getUserName());//用户名不能修改
SysUser one = userRepository.save(old);
if (one == null) {
result.setMessage("更新用户成功");
if (one != null) {
result.setMessage("更新成功");
result.setSuccess(true);
} else {
result.setMessage("更新用户失败");
result.setMessage("更新失败");
}
return result;
}
@@ -134,7 +140,49 @@ public class UserService {
* @return
*/
public List<SysUser> listAll() {
return userRepository.findAll();
List<SysUser> all = userRepository.findAll();
if (CollectionUtils.isNotEmpty(all)) {
all.forEach(sysUser -> {
CommonEnum.SexEnum sexEnum = Arrays.stream(CommonEnum.SexEnum.values()).filter(obj -> obj.getCode().equals(sysUser.getSex())).findFirst().get();
sysUser.setSexName(sexEnum.getName());
sysUser.setCreate(DateUtil2.dateToStr(sysUser.getCreateTime(), DateUtil2.YYYY_MM_DD_HH_MM_SS));
Date modifiedTime = sysUser.getModifiedTime();
if (modifiedTime != null)
sysUser.setModified(DateUtil2.dateToStr(sysUser.getModifiedTime(), DateUtil2.YYYY_MM_DD_HH_MM_SS));
});
}
return all;
}
/**
* 重置密码
*
* @param id
* @return
*/
public RestMessage resetPassWord(String id) {
RestMessage result = new RestMessage();
SysUser old = findOne(id);
if (old == null)
throw new BusinessException("未查询到用户信息");
if (CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID).equals(id))
throw new BusinessException("不能重置当前登录用户");
if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) {
throw new BusinessException("管理员密码不能重置");
}
String[] str = PassWordUtil.getUserSecret(null, null);
old.setSalt(str[1]);
old.setPassword(str[2]);
old.setModifiedTime(new Date());
SysUser save = userRepository.save(old);
if (save == null)
throw new BusinessException("重置密码失败");
boolean send = sendEmail(old, str[0]);
if (!send)
throw new BusinessException("发送密码邮件错误");
result.setSuccess(true);
result.setMessage("重置密码成功");
return result;
}
/**
@@ -144,25 +192,24 @@ public class UserService {
* @param oldPassWord
* @return
*/
public RestMessage updatePassWord(HttpServletRequest request,String newPassWord, String oldPassWord) {
public RestMessage updatePassWord(String newPassWord, String oldPassWord, String id) {
RestMessage result = new RestMessage();
HttpSession session = request.getSession();
String id = (String) session.getAttribute(CommonConstant.SESSION_CURRENT_USER_ID);
SysUser sysUser = findOne(id);
if (sysUser == null)
throw new BusinessException("该用户不存在");
boolean flag = checkPassWord(oldPassWord, sysUser.getPassword(), sysUser.getSalt());
if (!flag)
throw new BusinessException("原密码错误,请重新输入");
throw new BusinessException("原密码错误,请重新输入");
String[] str = PassWordUtil.getUserSecret(newPassWord, null);
sysUser.setSalt(str[1]);
sysUser.setPassword(str[2]);
SysUser one = userRepository.save(sysUser);
if (one!=null) {
result.setMessage("更新密码成功");
sysUser.setModifiedTime(new Date());
SysUser save = userRepository.save(sysUser);
if (save != null) {
result.setMessage("修改密码成功");
result.setSuccess(true);
} else {
result.setMessage("更新密码失败");
result.setMessage("修改密码失败");
}
return result;
}
@@ -170,18 +217,16 @@ public class UserService {
/**
* 登录
*
* @param request
* @param userName
* @param passWord
* @param checkCode
* @return
*/
public RestMessage login(HttpServletRequest request, String userName, String passWord, String checkCode) {
public RestMessage login(String userName, String passWord, String checkCode) {
RestMessage restMessage = new RestMessage();
HttpSession session = request.getSession();
String imgCode = (String) session.getAttribute(CommonConstant.KEY_CAPTCHA);
String imgCode = (String) CommonDataUtil.getToken(CommonConstant.KEY_CAPTCHA);
//验证验证码
if (!checkCode.equalsIgnoreCase(imgCode) ) {
if (!checkCode.equalsIgnoreCase(imgCode)) {
throw new BusinessException("验证码错误");
}
//验证账号,密码
@@ -191,8 +236,8 @@ public class UserService {
boolean flag = checkPassWord(passWord, user.getPassword(), user.getSalt());
if (!flag)
throw new BusinessException("密码错误");
session.setAttribute(CommonConstant.SESSION_CURRENT_USER, userName);
session.setAttribute(CommonConstant.SESSION_CURRENT_USER_ID, user.getId());
CommonDataUtil.setToken(CommonConstant.CURRENT_USER, userName);
CommonDataUtil.setToken(CommonConstant.CURRENT_USER_ID, user.getId());
restMessage.setSuccess(true);
restMessage.setMessage("登录成功");
return restMessage;
@@ -226,4 +271,24 @@ public class UserService {
//判断密码是否相同
return realPassWord.equals(validatePassWord);
}
/**
* 发送邮件
*
* @param sysUser
* @param passWord
* @return
*/
private boolean sendEmail(SysUser sysUser, String passWord) {
SysConfig sysConfig = sysConfigService.findByCode(CommonConstant.EMAIL_KEY);
if (sysConfig == null) {
throw new BusinessException("没有查找到邮件配置项");
}
JSONObject jsonObject = JSONObject.parseObject(sysConfig.getValue());
EmailModel emailModel = JSONObject.toJavaObject(jsonObject, EmailModel.class);
emailModel.setToEmail(sysUser.getMail());
emailModel.setSubject(emailModel.getSubject());
emailModel.setCentent(emailModel.getCentent() + " 你的用户名是:" + sysUser.getUserName() + ",密码是:" + passWord);
return EmailUtil.sendTextEmail(emailModel);
}
}
@@ -0,0 +1,29 @@
package com.xwbing.util;
import java.util.HashMap;
import java.util.Map;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/6 10:00
* 作者: xiangwb
* 说明: 公共数据类
*/
public class CommonDataUtil {
private static Map<String, Object> token = new HashMap();
public CommonDataUtil() {
}
public static Object getToken(String key) {
return token.get(key);
}
public static void setToken(String key, Object value) {
token.put(key, value);
}
public static void clearMap() {
token.clear();
}
}
@@ -127,6 +127,7 @@ public class EmailUtil {
}
public static void main(String[] args) {
String email = "{'serverHost':'smtp.163.com','serverPort':25,'serverHost':'smtp.163.com','protocol':'smtp','auth':true,'fromEmail':'xwbing2009@163.com','password':'xwbing900417','subject':'注册成功','centent':'注册成功'}";
EmailModel emailModel = new EmailModel();
emailModel.setServerHost("smtp.163.com");
emailModel.setServerPort(25);
@@ -1,12 +1,12 @@
package com.xwbing.util.captcah;
import com.xwbing.constant.CommonConstant;
import com.xwbing.util.CommonDataUtil;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@@ -18,6 +18,7 @@ import java.io.OutputStream;
*/
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = -124247581620199710L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) {
// 设置相应类型,告诉浏览器输出的内容为图片
@@ -27,12 +28,13 @@ public class CaptchaServlet extends HttpServlet {
res.setHeader("Cache-Control", "no-cache");
res.setDateHeader("Expire", 0);
try {
HttpSession session = req.getSession();
CaptchaUtil tool = new CaptchaUtil();
StringBuffer code = new StringBuffer();
BufferedImage image = tool.genRandomCodeImage(code);
session.removeAttribute(CommonConstant.KEY_CAPTCHA);
session.setAttribute(CommonConstant.KEY_CAPTCHA, code.toString());
// HttpSession session = req.getSession();
// session.removeAttribute(CommonConstant.KEY_CAPTCHA);
// session.setAttribute(CommonConstant.KEY_CAPTCHA, code.toString());
CommonDataUtil.setToken(CommonConstant.KEY_CAPTCHA, code.toString());
// 将内存中的图片通过流形式输出到客户端
OutputStream out = res.getOutputStream();
ImageIO.write(image, "JPEG", out);
@@ -102,11 +102,11 @@ public class CaptchaUtil {
CaptchaUtil tool = new CaptchaUtil();
StringBuffer code = new StringBuffer();
BufferedImage image = tool.genRandomCodeImage(code);
System.out.println("&gt;&gt;&gt; random key =: " + code);
System.out.println("&gt;&gt;&gt; random code =: " + code);
try {
// 将内存中的图片通过流动形式输出到客户端
ImageIO.write(image, "JPEG", new FileOutputStream(new File(
"random-key.jpg")));
"random-code.jpg")));
} catch (Exception e) {
e.printStackTrace();
}