前言
经过商量,修改注册逻辑,用户首先填写用户名和邮箱字段,后端向用户邮箱发送验证码,用户再填写验证码和邮箱进行激活账号。
邮箱配置
在pom文件中,引入启动器。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
修改yaml文件。
spring:
mail:
host: smtp.163.com
username: 邮箱地址
password: 密码
properties.mail.smtp.port: 465
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
service
修改后的UserService.java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private MailService mailService;
@Autowired
private UUIDUtil uuidUtil;
@Autowired
private DigitUtil digitUtil;
@Autowired
private Md5Util md5Util;
@Transactional(rollbackFor = RuntimeException.class)
public User loadUserByUsername(String username) {
User user = userMapper.findUserByUsername(username);
if (user == null) {
return user;
}
Long uid = user.getId();
List<Role> authorities = new ArrayList<>();
List<UserRole> userRoles = userRoleMapper.findUserRolesByUid(uid);
for (UserRole userRole : userRoles) {
authorities.add(roleMapper.findRoleById(userRole.getRid()));
}
user.setAuthorities(authorities);
return user;
}
@Transactional(rollbackFor = RuntimeException.class)
public User loadUserByEmail(String email) {
User user = userMapper.findUserByEmail(email);
if (user == null) {
return user;
}
Long uid = user.getId();
List<Role> authorities = new ArrayList<>();
List<UserRole> userRoles = userRoleMapper.findUserRolesByUid(uid);
for (UserRole userRole : userRoles) {
authorities.add(roleMapper.findRoleById(userRole.getRid()));
}
user.setAuthorities(authorities);
return user;
}
@Transactional(rollbackFor = RuntimeException.class)
public void code(String username, String password, String email) {
if (username.contains("@")) {
throw new IllegalUsernameException("用户名不合法");
}
if ((userMapper.findUserByUsername(username)) != null) {
throw new UserExistException("用户名已经存在");
}
if ((userMapper.findUserByEmail(email)) != null) {
throw new UserExistException("邮箱已经存在");
}
String code = Integer.toString(digitUtil.code(6));
User user = new User();
user.setUsername(username);
user.setEmail(email);
user.setPassword(md5Util.encrypt(password));
user.setProfile("default.png");
user.setCode(code);
userMapper.insertUser(user);
userRoleMapper.insertNormalUser(user.getId());
String subject = "山大云会议";
String context = "<p>您的验证码为: "+code+"。</p>";
try {
mailService.sendHtmlMail(user.getEmail(), subject, context);
} catch (MessagingException e) {
throw new RuntimeException("发送邮件时出现异常");
}
}
@Transactional(rollbackFor = RuntimeException.class)
public Long register(String username, String password, String email, String code) {
User user = userMapper.findUserByCode(code);
if (user == null) {
throw new CodeNotFoundException("不存在的验证码");
}
if (!Objects.equals(username, user.getUsername())) {
throw new UsernameNotFoundException("不存在的用户名");
}
if (!Objects.equals(email, user.getEmail())) {
throw new EmailNotFoundException("不存在的邮箱");
}
user.setPassword(md5Util.encrypt(password));
user.setStatus(1);
user.setCode("");
userMapper.updateUser(user);
return user.getId();
}
}
添加的MailService.java
@Service
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
public void sendHtmlMail(String to, String subject, String context)
throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = null;
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setSubject(subject);
helper.setTo(to);
helper.setText(context, true);
javaMailSender.send(message);
}
}
controller
修改后的UserController.java
@Controller
@CrossOrigin(origins = {"*"})
public class UserController {
@Autowired
private UserService userService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private Md5Util md5Util;
private final static String EMAIL_PATTERN = "@mail.sdu.edu.cn";
@ResponseBody
@PostMapping("/login")
public ResponseData login(@RequestParam("text") String text,
@RequestParam("password") String password) {
ResponseData responseData;
User user;
if (checkValidEmail(text)) {
user = userService.loadUserByEmail(text);
} else {
user = userService.loadUserByUsername(text);
}
if (user != null) {
if (md5Util.verify(password, user.getPassword())) {
responseData = new ResponseData(200, "ok");
responseData.getData().put("token", jwtTokenUtil.generateToken(user));
} else {
responseData = new ResponseData(400, "密码错误");
}
} else {
responseData = new ResponseData(400, "用户名或者邮箱不存在");
}
return responseData;
}
@ResponseBody
@PostMapping("/code")
public ResponseData code(@RequestParam("username") String username,
@RequestParam("email") String email) {
ResponseData responseData;
if (isStringEmpty(username) || isStringEmpty(email)) {
responseData = new ResponseData(400, "不能为空");
return responseData;
}
String password = "111111";
if (!checkValidLength(username, password, email)) {
responseData = new ResponseData(400, "长度问题");
return responseData;
}
if (!checkValidEmail(email)) {
responseData = new ResponseData(400, "不支持的邮件格式");
return responseData;
}
try {
userService.code(username, password, email);
responseData = new ResponseData();
responseData.setCode(200);
responseData.setMessage("ok");
return responseData;
} catch (IllegalUsernameException exception) {
responseData = new ResponseData(400, exception.getMsg());
return responseData;
} catch (UserExistException exception) {
responseData = new ResponseData(400, exception.getMsg());
return responseData;
} catch (RuntimeException exception) {
responseData = new ResponseData(400, exception.getMessage());
return responseData;
}
}
@ResponseBody
@PostMapping("/register")
public ResponseData register(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("email") String email,
@RequestParam("code") String code) {
ResponseData responseData;
if (isStringEmpty(username) || isStringEmpty(email)) {
responseData = new ResponseData(400, "不能为空");
return responseData;
}
if (!checkValidLength(username, password, email)) {
responseData = new ResponseData(400, "长度问题");
return responseData;
}
if (!checkValidEmail(email)) {
responseData = new ResponseData(400, "不支持的邮件格式");
return responseData;
}
try {
Long uid = userService.register(username, password, email, code);
responseData = new ResponseData(200, "ok");
responseData.getData().put("uid", uid);
return responseData;
} catch (CodeNotFoundException | UsernameNotFoundException | EmailNotFoundException exception) {
responseData = new ResponseData(400, exception.getMessage());
return responseData;
}
}
private boolean isStringEmpty(String string) {
return string == null || "".equals(string);
}
private boolean checkValidLength(String username, String password, String email) {
return username.length() <= 32 && password.length() <= 32 && email.length() <= 64;
}
private boolean checkValidEmail(String email) {
return email.endsWith(EMAIL_PATTERN);
}
}
|