rendering

The registration process

1.[Front end] Users submit registration information on the registration page; 2.[Back-end] Verifies the parameters submitted by the user. If any error occurs, an error message is returned and the user proceeds to the next step. 3.[back-end] Randomly generate an ID, take ID as key, user information as value, store it in Redis, and set the duration; 4.[back-end] Generates activation links and sends emails to users’ mailboxes through the mail system. 6.[Back-end] Verify whether the value is expired and whether the verification mailbox is registered. If no, the user information is saved to the database, indicating that the user is registered successfully.

Functional implementation (reverse analysis)

1, the implementation of check email cn. Ictgu. View mail. MailService

package cn.ictgu.tools.mail; import cn.ictgu.dao.model.User; import com.alibaba.fastjson.JSONObject; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; /** * Created by Silence on 2017/3/11. */ @service @log4j public class MailService {@autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String from; Private static final String TITLE_SIGN_UP = "[email title]"; Private static final String CONTENT = "[static final String]"; public void userValidate(User user, String token){ MimeMessage mailMessage = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, "GBK"); helper.setFrom(from); helper.setTo(user.getEmail()); helper.setSubject(TITLE_SIGN_UP); String link = "http://www.ictgu.cn/validate/" + token; String message = String.format(CONTENT, user.getNickname(), link, link, user.getEmail()); helper.setText(message, true); mailSender.send(mailMessage); } catch (MessagingException e) {log.error(" failed to send email: User:" + jsonObject.tojsonString (User) + ", Token: "+ Token); }}Copy the code

Note: Two parameters are passed in to send an email: user and token. User is the user registration information, token is a random UUID, redis has the corresponding key, and its value is the JSON string of user. (The rule for key is the configuration file redis.prefix-signup + UUID)

Mail template problems: The essence of the email content is a String, the style is controlled by HTML + CSS. During development, the template is designed in the mailbox, the variable is replaced by % S, and then the whole String is stored in a suitable place. When sending the email, the string.format () method is used to replace %s with the actual value, and the end user can see the email. Therefore, there is no need to use third-party templates, adding JAR packages will increase the complexity of the system, the same function can be simplified as much as possible.

2. How to generate tokens? Please see the cn. Ictgu. Redis. RedisTokenManager

  public String getTokenOfSignUp(User user){
    String token = UUID.randomUUID().toString();
    String value = JSONObject.toJSONString(user);
    stringRedisTemplate.opsForValue().set(signUpPrefix + token, value);
    stringRedisTemplate.expire(signUpPrefix + token, 12, TimeUnit.HOURS);
    return token;
  }Copy the code

Uuid.randomuuid ().toString() is an automatic primary key generation method provided by javaJDK. Universally Unique Identifier (UUID) a global Unique Identifier is a number generated on a machine. It is guaranteed to be Unique to all machines in the same space and time. It is a form of a 16-digit number. A combination of the following parts: The current date and time (the first part of a UUID is time dependent, and if you generate a UUID a few seconds later, the first part is different and the rest are the same), the clock sequence, the globally unique IEEE machine id (obtained from a network card if there is one, and otherwise if there is no network card), The only drawback to UUID is that the resulting string can be long.

3, token, you need to be in the service layer associated with the user and token email, see cn. Ictgu. Dao. Service. UserService

public boolean signUp(User user){ String email = user.getEmail(); If (existEmail(email)){log.error(" user registered, email registered :" + email); return false; } sendValidateEmail(user); return true; } @Async private void sendValidateEmail(User user){ String token = tokenManager.getTokenOfSignUp(user); Log.error (" User registered, ready to send email: User:" + jsonObject.tojsonString (User) + ", Token: "+ Token); mailService.userValidate(user, token); } private boolean existEmail(String email){ return mapper.selectByEmail(email) ! = null; }Copy the code

Note: It takes a long time to send emails. Therefore, use asynchronous mail to improve user experience

4. User is simple

@RestController public class UserApi { @Autowired private UserService userService; @RequestMapping(value = "/sign-up", method = RequestMethod.POST) public SimpleResponse signUp(HttpServletRequest request){ User user = createUser(request); SimpleResponse response = checkSignUpRequest(user); if (response.getCode() == 100){ if (! userService.signUp(user)){ response.setCode(200); Response. setMessage(" This mailbox has been registered, please do not register again!" ); return response; }else {response.setMessage(" Registration activation email has been sent to your mailbox, please activate and complete registration within 12 hours!" ); return response; } } return response; } private SimpleResponse checkSignUpRequest(User user){ SimpleResponse response = new SimpleResponse(); String email = user.getEmail(); if (! CheckUtils.checkEmail(email)){ response.setCode(200); Response.setmessage (" invalid mailbox format "); return response; } String password = user.getPassword(); if (! CheckUtils.checkPassword(password)){ response.setCode(200); Response.setmessage (" Password must be 8-16 characters in length and must contain numbers and letters "); return response; } String nickname = user.getNickname(); if (! CheckUtils.checkNickname(nickname)){ response.setCode(200); Response.setmessage (" nickname length is invalid "); return response; } response.setCode(100); return response; }}Copy the code

Note: This layer mainly does the verification of user registration parameters

review

From the bottom up, from the user registration to the email sent to achieve, most of the code is to do the parameter verification, because the user behavior is not trusted, to build a secure background system, it is necessary to have no dead corner of the verification…

Making the address

Address: github.com/ChinaSilenc…

Demo Address:

Address: www.ictgu.cn

Related articles

Spring Boot Full stack development: Spring Boot full stack development: Application deployment using Spring Boot full stack development: beautiful mail registration Spring Boot full stack development: Spring Boot full stack development: video parsing of youku Spring Boot full stack development: video parsing of Lev Spring Boot full stack development: user security Spring Boot full stack development: concurrent crawler optimization to be continued

At the end of the article’s welfare

Java data collection of links: pan.baidu.com/s/1pUCCPstP… Password: b2XC More information: 2020 Selected Ali Java, architecture, micro services selected information, plus V ❤ : QWERDD111

This article is published by OpenWrite!