当前位置:网站首页>Data and information resource sharing platform (VIII)
Data and information resource sharing platform (VIII)
2022-06-10 23:29:00 【yyDrifter】
Email registration / Password back / authentication
principle
Set two fields in the database ,status:(0: not active ,1: Activation successful ),activition_code:( Release activation code ):
The user fills in the information , Click registration , Insert data succeeded ,state The default field is 0, Generate a activition_code( Use the e-mail you sent me 、 password 、 And the current time ) Also stored in the database .
Send E-mail , Prompt the user to log in to the mailbox to activate , There is an activation success page in the email URL,URL There are two parameters ( user ID And activation code ).
The user logs in to the mailbox and clicks the link , Go to the process activated business logic page or Servlet, obtain URL Two parameters in , Query the data in the database based on these two parameters , If there is , Check whether the activation code transmitted from the link is consistent with the database field activation code , atypism , Delete this record in the database , And jump to the activation failure interface , Agreement , The field state by 1, Activation successful , Go to the activation success page .
Back end
UserController.java
Email registration
@RequestMapping("/register.do")
public OutResponse<Object> registerdo( User user) {
OutResponse<Object> outResponse = new OutResponse<>();
try {
userService.register(user);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error(" User registration failed , user name :{} mailbox :{}", user.getUserName(), user.getEmail());
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error(" User registration failed , user name :{} mailbox :{}", user.getUserName(), user.getEmail());
}
return outResponse;
}
Email account activation
@RequestMapping("/activate")
public ModelAndView activate(String userName, String activationCode) {
OutResponse<Object> outResponse = new OutResponse<>();
ModelAndView view = new ModelAndView("/page/active");
try {
userService.updateUserActivate(userName, activationCode);
outResponse.setCode(CodeEnum.SUCCESS);
outResponse.setMsg(" honorific 【"+userName+"】 user , Congratulations on your successful account activation ");
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error(" User activation failed , user name :{}", userName);
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error(" User activation failed , user name :{}", userName);
}
view.addObject("outResponse", outResponse);
return view;
}
Retrieve password
@RequestMapping("/sendCheckCode")
public OutResponse<Object> sendCheckCode(String email) {
OutResponse<Object> outResponse = new OutResponse<>();
try {
System.out.println("--------------------kajsfdlkjaslkfd");
userService.sendCheckCode(email);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error(" Verification code sending failed , mailbox :{}");
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error(" Verification code sending failed , mailbox :{}", email);
}
return outResponse;
}
Password change
@RequestMapping("/findPassword.do")
public OutResponse<Object> findPassworddo(String email, String password, String checkcode) {
OutResponse<Object> outResponse = new OutResponse<Object>();
try {
userService.modifyPassword(email, password, checkcode);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error(" Password change failed , mailbox {}", email);
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error(" Password change failed , mailbox :{}", email);
}
return outResponse;
}
User.java
public class User {
private String userid;
private String email;
private String userName;
private String password;
private String userIcon;
private String userBg;
private String age;
private String sex;
private String characters;
private Integer mark=0;
private String address;
private String work;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
private String birthdayString;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
private Date registerTime;
private String registerTimeString;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
private Date lastLoginTime;
private String lastLoginTimeString ;
private String activationCode;
private Integer status;
private Integer userPage;
}
UserMapper.xml
Insert email address information
<insert id="insert" parameterType="com.known.common.model.User" >
insert into known_user (userid, email, user_name,
password, user_icon, user_bg, birthday,
register_time, last_login_time, activation_code)
values (#{
userid,jdbcType=VARCHAR}, #{
email,jdbcType=VARCHAR}, #{
userName,jdbcType=VARCHAR},
#{
password,jdbcType=VARCHAR}, #{
userIcon,jdbcType=VARCHAR}, #{
userBg,jdbcType=VARCHAR},
#{
birthday,jdbcType=TIMESTAMP}, #{
registerTime,jdbcType=TIMESTAMP},
#{
lastLoginTime,jdbcType=TIMESTAMP},#{
activationCode,jdbcType=VARCHAR})
</insert>
Update the account information after the email account is activated
<update id="updateStatus">
update known_user set status = 1
where user_name = #{
userName,jdbcType=VARCHAR}
and activation_code=#{
activationCode,jdbcType=VARCHAR}
</update>
StringUtil.java
Preliminary verification of mailbox format
// Judge whether it is a mailbox
public static boolean isEmail(String str) {
String checkEmail = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
if (!isEmpty(str)) {
return str.matches(checkEmail);
} else {
return false;
}
}
UserService.java- Interface
User findUserByEmail(String email);// Get the mailbox back
void sendCheckCode(String email) throws BussinessException;// Send verification code
void modifyPassword(String email, String password, String checkcode) throws BussinessException;// Change Password
UserServiceImpl.java- Interface implementation logic
Send activation email
// Send activation email
String subject = " Student information resource sharing system system notification email ";
StringBuffer content = new StringBuffer(" dear 【" + user.getUserName() + "】 user <br><br>");
content.append(" Welcome to the student information resource sharing system !<br><br>");
content.append(" Click on <a href='" + mailConfig.getGlob_Real_Path() + "/user/activate?userName=" + user.getUserName() +
"&activationCode=" + activationCode + "'> Student information resource sharing system account activation </a> Activate your account !");
try {
MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
subject, new String(content));
} catch (Exception e) {
throw new BussinessException(" Failed to send email , Please try again later ");
}
design sketch 
Search for users by user name , Verify whether activation and registration are successful
public void updateUserActivate(String userName, String activationCode) throws BussinessException {
// Search for users by user name
User user = findUserByUserName(userName);
if (user == null) {
throw new BussinessException(" user 【"+userName+"】 non-existent , Please register the user ");
}
if (user.getUserPage() != 0) {
throw new BussinessException(" user 【"+userName+"】 Activated , Please log in ");
}
if (!activationCode.equals(user.getActivationCode())) {
throw new BussinessException(" user 【"+userName+"】 The activation code is invalid , Please use the latest activation link ");
}
userMapper.updateStatus(userName, activationCode);
}
status by 0 Represents that the account is not activated
if (user.getStatus() == 0) {
throw new BussinessException(" Please check your email , Log in after activating the account ");
}
Email verification code sent
public void sendCheckCode(String email) throws BussinessException {
if (StringUtil.isEmpty(email) || !StringUtil.isEmail(email)) {
throw new BussinessException(" Illegal input parameter ");
}
User user = findUserByEmail(email);
if (user == null) {
throw new BussinessException(" The mailbox doesn't exist ");
}
String checkCode = StringUtil.getActivationCode(6);
String subject = " Student information resource sharing system system notification email ";
StringBuffer content = new StringBuffer(" dear 【" + user.getUserName() + "】 user <br><br>");
content.append(" Welcome to <a href='"+mailConfig.getGlob_Real_Path()+"'> Student information resource sharing system </a> Password retrieval function of <br><br>");
content.append(" Your verification code is <h3 style='color:red;'>" + checkCode + "</h3>");
try {
System.out.println("======================"+checkCode);
MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
subject, new String(content));
} catch (Exception e) {
throw new BussinessException(" Failed to send email , Please try again later ");
}
user.setActivationCode(checkCode);
userMapper.update(user);
}
User validation
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Integer changeMark(String userid, int mark) {
return userMapper.changeUserMark(mark, userid);
}
public User findUserInfo4UserHome(String userId) throws BussinessException {
User user = findUserByUserid(userId);
if (user == null) {
throw new BussinessException(" The user doesn't exist ");
}
// Set password to blank
user.setPassword(null);
// Set the activation code to null
user.setActivationCode(null);
return user;
}
application-config Set the sender's mailbox
mail.sendUserName= Your email address ( recommend 163)
mail.sendPassword= mailbox pop Server address
front end
register
<div class="form-group">
<label class="col-lg-2 control-label"> mailbox :</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="email" id="email" placeholder=" Used to retrieve the password , Please fill in the correct email address ">
</div>
</div>

Retrieve password
<div class="container-findpassword">
<div class="findpassword">
<div>
<legend class="form_legend">
Retrieve password
</legend>
<form id="findPassword">
<div class="form-group">
<input class="form-control" placeholder=" Please enter email address " name="email" id="email"></input>
</div>
<div class="form-group" >
<div id="embed-captcha"></div>
<p id="wait" class="show"> Loading captcha ......</p>
<p id="notice" class="hide"> Please drag the verification code to the corresponding position </p>
</div>
</form>
<div class="form-group">
<button type="button" class="btn btn-info block full-width" id="findpassword"> Send verification code </button>
</div>
<p class="foot">
<a href="${realpath}/user/login"> Return to log in </a>
|
<a href="${realpath}/user/register"> Sign up for a new account </a>
</p>
</div>
</div>
var handlerEmbed = function (captchaObj) {
$("#findpassword").click(function (e) {
var validate = captchaObj.getValidate();
if (!validate) {
$("#notice")[0].className = "show";
setTimeout(function () {
$("#notice")[0].className = "hide";
}, 2000);
e.preventDefault();
} else{
var email = $('#email').val();
var emailreg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (email == null || $.trim(email) == '') {
checkForm(' The mailbox cannot be empty ', 'email');
$("#email").parent().addClass('has-error');
} else if (!emailreg.test(email)) {
checkForm(' Please enter the correct email ', "email");
$("#email").parent().addClass('has-error');
} else {
$("#email").parent().removeClass('has-error');
var loadingindex = layer.load(0, {
shade: [0.1,'#fff'] //0.1 Transparent white background
});
$.ajax({
url: known.realpath + '/user/sendCheckCode',
type: 'POST',
dataType: 'json',
data: $('#findPassword').serialize(),
success: function(data) {
layer.close(loadingindex);
if (data.msg == null) {
var content = '<form id="modifyPassword"><div class="form-group"><input class="form-control" type="password" placeholder=" Please enter the new password " name="password" id="password"></input></div><div class="form-group"><input class="form-control" type="password" placeholder=" Please confirm the new password " name="confirmPassword" id="confirmPassword"></input></div><div class="form-group"><input class="form-control" placeholder=" Verification Code " name="checkcode" id="checkcode"></input></div></form>';
var d = dialog({
title: ' Change Password ',
width: 300,
content: content,
okValue: ' determine ',
ok: function() {
...
} else if (checkcode == null || $.trim(checkcode) == '') {
$("#confirmPassword").parent().removeClass('has-error');
checkForm(" The verification code cannot be an empty string ", "checkcode");
$("#checkcode").parent().addClass('has-error');
return false;
} else {
$.ajax({
url: known.realpath+ '/user/findPassword.do',
type: 'POST',
dataType: 'json',
data: {
"email": email,
"password": password,
"checkcode": checkcode
},
success: function(data) {
if (data.msg == null) {
var d = dialog({
content: "<div><img src='" + known.realpath +"/resources/images/loading.gif' /> Modification successful , Jumping ...</div>",
});
d.showModal();
setTimeout(function() {
d.close().remove();
document.location.href = known.realpath + "/user/login";
}, 1000);
} else {
checkForm(data.msg, "checkcode");
}
}
});
return false;

边栏推荐
- 数据与信息资源共享平台(五)
- 【sql语句基础】——增(insert)
- Why is the kotlin language not popular now?
- Which securities company does qiniu's securities belong to? Is it safe?
- 线程池的创建
- Project training 10 - backup of specific databases
- 上海证券开户是安全的吗?
- Clustered and non clustered indexes
- About string format(String format, Object... args)
- 【GMM+KDE】基于MATLAB的GMM和KDE核估计得目标跟踪仿真
猜你喜欢

UE4 getting started with bone animation

About not being able to create a new package under Src in idea

改变世界的开发者丨玩转“俄罗斯方块”的瑶光少年

Chapter 6 - branch and bound method

执行Oracle的SQL语句报错【ORA-00904: “CREATETIME“: 标识符无效】、【ORA-00913: 值过多】解决办法

Dell R730 raid5 安装Server 2016(解决磁盘大于2T)

leetcode 130. Surrounded regions (medium)

PwnTheBox,Pwn:tutorial1

Solutions to the error reported by executing Oracle SQL statement [ora-00904: "createtime": invalid identifier] and [ora-00913: too many values]

mysql 表机制
随机推荐
MySQL related -0416
功能测试之设计语言测试:功能测试包含哪些测试?分别有什么作用
iframe框架自适应大小/全屏显示网页框架的方法
关于嵌入式音频开发需要注意的两个方面
300题 线代第一讲行列式
LeetCode+ 16 - 20
unity 代码为动画注册事件
This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
OpenVP*整合ldap認證
样板小作坊
Expandable to Max – MCU and MPU development, using the same license
laravel8 实现阿里云文件上传
OpenVP*整合ldap认证
关于高考的那些事儿
字蛛(font-spider)教学——ttf/otf字体文件压缩
项目实训13——界面补充
Introduction to software testing: the concept and process of software testing (brilliant content)
Exécuteur - shutdown, shutdown Now, awaittermination details and actual Fighting
The data file insurance CSV contains 1338 observations, that is, the registered beneficiaries of the insurance plan and the characteristics that represent the characteristics of patients and the total
我们对产业互联网的认识,还是困囿于互联网式的平台和中心的逻辑之中