找回密码功能开发

This commit is contained in:
x ronger 2019-11-24 15:50:02 +08:00
parent 3694099406
commit aa6bf24962
9 changed files with 230 additions and 21 deletions

View File

@ -0,0 +1,10 @@
package com.rymcu.vertical.dto;
import lombok.Data;
@Data
public class ForgetPasswordDTO {
private String code;
private String password;
}

View File

@ -15,4 +15,6 @@ public interface UserMapper extends Mapper<User> {
UserInfoDTO findUserInfoByAccount(@Param("account") String account);
UserDTO selectUserDTOByNickname(@Param("nickname") String nickname);
Integer updatePasswordByAccount(@Param("account") String account, @Param("password") String password);
}

View File

@ -1,5 +1,24 @@
package com.rymcu.vertical.service;
import javax.mail.MessagingException;
/**
* @author ronger
* @since 2019/11/23
* @version 1.0
* **/
public interface JavaMailService {
Integer sendEmailCode(String email);
/**
* 发送验证码邮件
* @param email 收件人邮箱
* @return 执行结果 0失败1成功
* */
Integer sendEmailCode(String email) throws MessagingException;
/**
* 发送找回密码邮件
* @param email 收件人邮箱
* @return 执行结果 0失败1成功
* */
Integer sendForgetPasswordEmail(String email) throws MessagingException;
}

View File

@ -21,4 +21,6 @@ public interface UserService extends Service<User> {
Map login(String account, String password);
UserDTO findUserDTOByNickname(String nickname);
Map forgetPassword(String code, String password);
}

View File

@ -3,21 +3,42 @@ package com.rymcu.vertical.service.impl;
import com.rymcu.vertical.core.service.redis.RedisService;
import com.rymcu.vertical.service.JavaMailService;
import com.rymcu.vertical.util.Utils;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author ronger
*/
@Service
public class JavaMailServiceImpl implements JavaMailService {
/**
* Java邮件发送器
*/
@Resource
private JavaMailSenderImpl mailSender;
@Resource
private RedisService redisService;
/**
* thymeleaf模板引擎
*/
@Resource
private TemplateEngine templateEngine;
@Value("${spring.mail.host}")
private String SERVER_HOST;
@ -27,13 +48,19 @@ public class JavaMailServiceImpl implements JavaMailService {
private String USERNAME;
@Value("${spring.mail.password}")
private String PASSWORD;
private final static String BASE_URL = "https://rymcu.com";
@Override
public Integer sendEmailCode(String email) {
public Integer sendEmailCode(String email) throws MessagingException {
return sendCode(email,0);
}
private Integer sendCode(String to, Integer type) {
@Override
public Integer sendForgetPasswordEmail(String email) throws MessagingException {
return sendCode(email,1);
}
private Integer sendCode(String to, Integer type) throws MessagingException {
Properties props = new Properties();
// 表示SMTP发送邮件需要进行身份验证
props.put("mail.smtp.auth", "true");
@ -47,18 +74,118 @@ public class JavaMailServiceImpl implements JavaMailService {
// 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置)
props.put("mail.password", PASSWORD);
mailSender.setJavaMailProperties(props);
Integer code = Utils.genCode();
redisService.set(to,code,5*60);
System.out.println(code);
if(type == 0) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(USERNAME);
simpleMailMessage.setTo(to);
if(type == 0) {
Integer code = Utils.genCode();
redisService.set(to,code,5*60);
simpleMailMessage.setSubject("新用户注册邮箱验证");
simpleMailMessage.setText("【RYMCU】您的校验码是 " + code + ",有效时间 5 分钟,请不要泄露验证码给其他人。如非本人操作,请忽略!");
mailSender.send(simpleMailMessage);
return 1;
} else if(type == 1){
String code = Utils.entryptPassword(to);
String url = BASE_URL + "/forget-password?code=" + code;
redisService.set(code,to,15*60);
String thymeleafTemplatePath = "mail/forgetPasswordTemplate";
Map<String, Object> thymeleafTemplateVariable = new HashMap<String, Object>();
thymeleafTemplateVariable.put("url", url);
sendTemplateEmail(USERNAME,
new String[] { to },
new String[] {},
"【RYMCU】 找回密码",
thymeleafTemplatePath,
thymeleafTemplateVariable);
return 1;
}
return 0;
}
/**
* 发送thymeleaf模板邮件
*
* @param deliver
* 发送人邮箱名 javalsj@163.com
* @param receivers
* 收件人可多个收件人 11111@qq.com,2222@163.com
* @param carbonCopys
* 抄送人可多个抄送人 33333@sohu.com
* @param subject
* 邮件主题 您收到一封高大上的邮件请查收
* @param thymeleafTemplatePath
* 邮件模板 mail\mailTemplate.html
* @param thymeleafTemplateVariable
* 邮件模板变量集
*/
public void sendTemplateEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String thymeleafTemplatePath,
Map<String, Object> thymeleafTemplateVariable) throws MessagingException {
String text = null;
if (thymeleafTemplateVariable != null && thymeleafTemplateVariable.size() > 0) {
Context context = new Context();
thymeleafTemplateVariable.forEach((key, value)->context.setVariable(key, value));
text = templateEngine.process(thymeleafTemplatePath, context);
}
sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
}
/**
* 发送的邮件(支持带附件/html类型的邮件)
*
* @param deliver
* 发送人邮箱名 javalsj@163.com
* @param receivers
* 收件人可多个收件人 11111@qq.com,2222@163.com
* @param carbonCopys
* 抄送人可多个抄送人 3333@sohu.com
* @param subject
* 邮件主题 您收到一封高大上的邮件请查收
* @param text
* 邮件内容 测试邮件逗你玩的 <html><body><img
* src=\"cid:attchmentFileName\"></body></html>
* @param attachmentFilePaths
* 附件文件路径
* 需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
* @throws Exception
* 邮件发送过程中的异常信息
*/
private void sendMimeMail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text,
boolean isHtml, String[] attachmentFilePaths) throws MessagingException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(deliver);
helper.setTo(receivers);
helper.setCc(carbonCopys);
helper.setSubject(subject);
helper.setText(text, isHtml);
// 添加邮件附件
if (attachmentFilePaths != null && attachmentFilePaths.length > 0) {
for (String attachmentFilePath : attachmentFilePaths) {
File file = new File(attachmentFilePath);
if (file.exists()) {
String attachmentFile = attachmentFilePath
.substring(attachmentFilePath.lastIndexOf(File.separator));
long size = file.length();
if (size > 1024 * 1024) {
String msg = String.format("邮件单个附件大小不允许超过1MB[%s]文件大小[%s]。", attachmentFilePath,
file.length());
throw new RuntimeException(msg);
} else {
FileSystemResource fileSystemResource = new FileSystemResource(file);
helper.addInline(attachmentFile, fileSystemResource);
}
}
}
}
mailSender.send(mimeMessage);
stopWatch.stop();
//logger.info("邮件发送成功, 花费时间{}秒", stopWatch.getStartTime());
}
}

View File

@ -46,7 +46,7 @@ public class UserServiceImpl extends AbstractService<User> implements UserServic
@Override
@Transactional
public Map register(String email, String password, String code) {
Map map = new HashMap();
Map map = new HashMap(2);
map.put("message","验证码无效!");
String vcode = redisService.get(email);
if(StringUtils.isNotBlank(vcode)){
@ -77,7 +77,7 @@ public class UserServiceImpl extends AbstractService<User> implements UserServic
@Override
public Map login(String account, String password) {
Map map = new HashMap();
Map map = new HashMap(1);
User user = new User();
user.setAccount(account);
user = userMapper.selectOne(user);
@ -103,4 +103,19 @@ public class UserServiceImpl extends AbstractService<User> implements UserServic
UserDTO user = userMapper.selectUserDTOByNickname(nickname);
return user;
}
@Override
public Map forgetPassword(String code, String password) {
Map map = new HashMap<>(2);
String account = redisService.get(code);
System.out.println("account:\n"+account);
if(StringUtils.isBlank(account)){
map.put("message","链接已失效");
} else {
userMapper.updatePasswordByAccount(account,Utils.entryptPassword(password));
map.put("message","修改成功,正在跳转登录登陆界面!");
map.put("flag",1);
}
return map;
}
}

View File

@ -7,14 +7,19 @@ import com.rymcu.vertical.core.result.GlobalResult;
import com.rymcu.vertical.core.result.GlobalResultGenerator;
import com.rymcu.vertical.core.result.GlobalResultMessage;
import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.dto.ForgetPasswordDTO;
import com.rymcu.vertical.dto.TUser;
import com.rymcu.vertical.entity.User;
import com.rymcu.vertical.service.ArticleService;
import com.rymcu.vertical.service.JavaMailService;
import com.rymcu.vertical.service.UserService;
import com.rymcu.vertical.util.UserUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -32,7 +37,7 @@ public class CommonApiController {
@ApiOperation(value = "获取邮件验证码")
@PostMapping("/get-email-code")
public GlobalResult getEmailCode(@RequestParam("email") String email) throws ServiceException {
public GlobalResult getEmailCode(@RequestParam("email") String email) throws MessagingException {
Map map = new HashMap();
map.put("message",GlobalResultMessage.SEND_SUCCESS.getMessage());
User user = userService.findByAccount(email);
@ -47,14 +52,14 @@ public class CommonApiController {
return GlobalResultGenerator.genSuccessResult(map);
}
@ApiOperation(value = "获取找回密码邮件验证码")
@PostMapping("/get-forget-email-code")
public GlobalResult getForgetEmailCode(@RequestParam("email") String email) {
Map map = new HashMap();
@ApiOperation(value = "获取找回密码邮件")
@PostMapping("/get-forget-password-email")
public GlobalResult getForgetPasswordEmail(@RequestParam("email") String email) throws MessagingException {
Map map = new HashMap<>(1);
map.put("message",GlobalResultMessage.SEND_SUCCESS.getMessage());
User user = userService.findByAccount(email);
if (user != null) {
Integer result = javaMailService.sendEmailCode(email);
Integer result = javaMailService.sendForgetPasswordEmail(email);
if(result == 0){
map.put("message",GlobalResultMessage.SEND_FAIL.getMessage());
}
@ -86,9 +91,9 @@ public class CommonApiController {
PageHelper.startPage(page, rows);
List<ArticleDTO> list = articleService.findArticles(searchText,tag);
PageInfo pageInfo = new PageInfo(list);
Map map = new HashMap();
Map map = new HashMap(2);
map.put("articles", pageInfo.getList());
Map pagination = new HashMap();
Map pagination = new HashMap(3);
pagination.put("paginationPageCount",pageInfo.getPages());
pagination.put("paginationPageNums",pageInfo.getNavigatepageNums());
pagination.put("currentPage",pageInfo.getPageNum());
@ -101,7 +106,7 @@ public class CommonApiController {
@GetMapping("/article/{id}")
public GlobalResult detail(@PathVariable Integer id){
ArticleDTO articleDTO = articleService.findArticleDTOById(id,1);
Map map = new HashMap<>();
Map map = new HashMap<>(1);
map.put("article", articleDTO);
return GlobalResultGenerator.genSuccessResult(map);
}
@ -109,8 +114,20 @@ public class CommonApiController {
@GetMapping("/update/{id}")
public GlobalResult update(@PathVariable Integer id){
ArticleDTO articleDTO = articleService.findArticleDTOById(id,2);
Map map = new HashMap<>();
Map map = new HashMap<>(1);
map.put("article", articleDTO);
return GlobalResultGenerator.genSuccessResult(map);
}
@GetMapping("/token/{token}")
public GlobalResult token(@PathVariable String token){
TUser tUser = UserUtils.getTUser(token);
return GlobalResultGenerator.genSuccessResult(tUser);
}
@PatchMapping("/forget-password")
public GlobalResult forgetPassword(@RequestBody ForgetPasswordDTO forgetPassword){
Map map = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword());
return GlobalResultGenerator.genSuccessResult(map);
}
}

View File

@ -41,6 +41,9 @@
<insert id="insertUserRole">
insert into vertical_user_role (id_user,id_role,created_time) values (#{idUser},#{idRole},sysdate())
</insert>
<update id="updatePasswordByAccount">
update vertical_user set password = #{password} where account = #{account}
</update>
<select id="findByAccount" resultMap="BaseResultMap">
select id, nickname, account, password, status from vertical_user where account = #{account} AND status = 0

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>找回密码</title>
</head>
<body>
<div>
你正在进行找回密码操作,点击 <a th:href="${url}">链接</a> 继续操作,有效时间 15 分钟,请及时处理。如非本人操作,请忽略!
如无法打开请访问以下地址:<span th:text="${url}"></span>
</div>
</body>
</html>