用户模块技术要点:
1、横向越权和纵向越权
2、Token
3、缓存(Guava Cache)
4、高复用服务器响应对象的设计思想和抽象封装
5、String和byte[]之间的转化(MD5加密)
6、session的详细解释
7、门户_用户接口
8、后台_用户接口
用户模块功能:
1.登录
2.用户名校验
3.注册
4.忘记密码
5.提交问题答案
6.重置密码
7.获取用户信息
8.更新用户信息
9.退出登录
一、登录:
1、用户名是否存在
2、如果存在则将密码转换为MD5加密形式
3、校验用户名和密码是否正确
4、正确则将用户放入到Session中
具体实现代码如下:
Controller层:
@Controller //WEB层(用于标注类本身的用途)
@RequestMapping("/user/") //将请求地址的前面加上/user
public class UserController {
//按类型进行注入
//将iUserService注入进来
@Autowired
private IUserService iUserService;
//登陆功能
//访问地址为login.do 访问方式为POST
@RequestMapping(value = "login.do",method = RequestMethod.POST)
@ResponseBody //自动通过SpingMvc的json插件将返回值转换成json
public ServerResponse<User> login(String username, String password, HttpSession session) {
ServerResponse<User> response = iUserService.login(username, password);
if (response.isSuccess()) //如果登陆成功,将用户放入到Session中
session.setAttribute(Const.CURRENT_USER, response.getData());
return response; //将响应信息返回到前端
}
}
interface IUserService :
public interface IUserService {
ServerResponse<User> login(String username, String password);
}
Service层:
//Service表示业务层
//创建iUserService对象,放入到容器中
@Service("iUserService")
public class UserServiceImpl implements IUserService {
@Autowired //注入userMapper
private UserMapper userMapper;
@Override
public ServerResponse<User> login(String username, String password) {
int resultCount = userMapper.checkUsername(username); //先查询用户名,看用户名是否存在
if (resultCount == 0) //如果查不到的话,用户不存在
return ServerResponse.createByErrorMessage("用户名不存在");
String md5Password = MD5Util.MD5EncodeUtf8(password); //将密码转化为MD5
User user = userMapper.selectLogin(username, md5Password); //通过用户名和密码进行查询
if (user == null)
return ServerResponse.createByErrorMessage("密码错误");
//将密码设置为空
user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
return ServerResponse.createBySuccess("登录成功", user);
}
}
Dao层:
UserMapper:
public interface UserMapper {
int checkUsername(String username); //查询用户名,看此用户名是否存在
//@Param为传入的参数起名字,这样在Dao层可以获得数据
User selectLogin(@Param("username") String username, @Param("password")String password);
}
<select id="checkUsername" resultType="int" parameterType="string" >
select count(1) from mmall_user where username = #{username}
</select>
<select id="selectLogin" resultMap="BaseResultMap" parameterType="map">
SELECT
<include refid="Base_Column_List" /> <!--只需要查询我们需要的字段-->
from mmall_user
where username = #{username}
and password = #{password}
</select>
二、退出登录:
将用户从Session中 移除
具体实现代码如下:
Controller层:
@RequestMapping(value = "logout.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> logout(HttpSession session){
session.removeAttribute(Const.CURRENT_USER);
return ServerResponse.createBySuccess();
}
三、注册:
1、用户名是否存在
2、校验邮箱是否存在
3、将密码转化为MD5形式
4、将用户放入数据库中
具体实现代码如下:
Controller层:
//注册功能
@RequestMapping(value = "register.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> register(User user){
return iUserService.register(user);
}
//校验功能
@RequestMapping(value = "check_valid.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> checkValid(String str,String type){
return iUserService.checkValid(str,type);
}
interface IUserService :
public interface IUserService {
ServerResponse<String> register(User user);
ServerResponse<String> checkValid(String str,String type);
}
Service层:
//注册
@Service("iUserService")
public class UserServiceImpl implements IUserService {
public ServerResponse<String> register(User user) {
@Autowired //注入userMapper
private UserMapper userMapper;
ServerResponse<String> vaildResponse =
this.checkValid(user.getUsername(),Const.USERNAME);
if(!vaildResponse.isSuccess()) //校验用户名
return vaildResponse;
vaildResponse = this.checkValid(user.getEmail(),Const.EMAIL);
if(!vaildResponse.isSuccess()) //校验邮箱
return vaildResponse;
user.setRole(Const.Role.ROLE_CUSTOMER); //设置用户角色
user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword())); //MD5加密
int resultCount = userMapper.insert(user); //插入用户
if (resultCount == 0)
return ServerResponse.createByErrorMessage("注册失败");
return ServerResponse.createBySuccessMessage("注册成功");
}
}
//校验
public ServerResponse<String> checkValid(String str,String type){
if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){ //type不是空,才开始校验
if(Const.USERNAME.equals(type)){ //判断用户名
int resultCount = userMapper.checkUsername(str);
if(resultCount > 0 )
return ServerResponse.createByErrorMessage("用户名已存在");
}
if(Const.EMAIL.equals(type)){ //判断email
int resultCount = userMapper.checkEmail(str);
if(resultCount > 0 )
return ServerResponse.createByErrorMessage("email已存在");
}
}else{
return ServerResponse.createByErrorMessage("参数错误");
}
return ServerResponse.createBySuccessMessage("校验成功");
}
Dao层:
UserMapper:
public interface UserMapper {
int checkEmail(String email); //查询邮箱,看此邮箱是否存在
int insert(User record);
}
<select id="checkEmail" resultType="int" parameterType="string" >
select count(1) from mmall_user
where email = #{email}
</select>
<insert id="insert" parameterType="com.mmall.pojo.User" >
insert into mmall_user (id, username, password,
email, phone, question,
answer, role, create_time,
update_time)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{question,jdbcType=VARCHAR},
#{answer,jdbcType=VARCHAR}, #{role,jdbcType=INTEGER}, now(),
now())
</insert>
四、获取用户信息:
1、判断用户是否登录
2、登录则将用户信息取出
具体实现代码如下:
Controller层:
@RequestMapping(value = "get_user_info.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> getUserInfo(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if(user != null){
return ServerResponse.createBySuccess(user);
}
return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
}
五、忘记密码、重置密码:
1、用户名是否存在
2、根据用户名查询问题
3、答案正确则生成token
4、将token存入到guava cache本地缓存中,有效期为12小时(防止横向越权)
5、校验用户名是否存在
6、校验token是否正确
7、正确则重新设置密码
具体实现代码如下:
Controller层:
//忘记密码的时候根据用户名查询问题
@RequestMapping(value = "forget_get_question.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> forgetGetQuestion(String username){
return iUserService.selectQuestion(username); //返回提示问题
}
//检查用户回答的答案是否正确
@RequestMapping(value = "forget_check_answer.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> forgetCheckAnswer(String username,String question,String answer){
return iUserService.checkAnswer(username,question,answer);
}
//忘记密码中的重置密码
@RequestMapping(value = "forget_reset_password.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> forgetRestPassword(String username,String passwordNew,String forgetToken){
return iUserService.forgetResetPassword(username,passwordNew,forgetToken);
}
interface IUserService :
public interface IUserService {
ServerResponse selectQuestion(String username);
ServerResponse<String> checkAnswer(String username,String question,String answer);
ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken);
}
Service层:
//忘记密码,查询问题
public ServerResponse selectQuestion(String username){
ServerResponse validResponse = this.checkValid(username,Const.USERNAME); //先看下用户是否存在
if(validResponse.isSuccess())
return ServerResponse.createByErrorMessage("用户不存在");
String question = userMapper.selectQuestionByUsername(username); //存在的话根据用户名查询问题
if(org.apache.commons.lang3.StringUtils.isNotBlank(question)) //当问题不为空的时候返回
return ServerResponse.createBySuccess(question);
return ServerResponse.createByErrorMessage("找回密码的问题是空的");
}
//检查用户回答的答案是否正确
public ServerResponse<String> checkAnswer(String username,String question,String answer){
int resultCount = userMapper.checkAnswer(username,question,answer);
if(resultCount > 0){ //说明问题及问题答案是这个用户的,并且是正确的
String forgetToken = UUID.randomUUID().toString(); //声明一个token
TokenCache.setKey(TokenCache.TOKEN_PREFIX + username,forgetToken);
return ServerResponse.createBySuccess(forgetToken);
}
return ServerResponse.createByErrorMessage("问题的答案错误");
}
//忘记密码中的重置密码
public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken) {
if (org.apache.commons.lang3.StringUtils.isBlank(forgetToken)) //先判断是否携带了token
return ServerResponse.createByErrorMessage("参数错误,token需要传递");
ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
if (validResponse.isSuccess()) //校验一下用户名
return ServerResponse.createByErrorMessage("用户不存在");
String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username); //从缓存中获取用户的token
if (org.apache.commons.lang3.StringUtils.isBlank(token)) //获取到看token是否为空
return ServerResponse.createByErrorMessage("token无效或者过期");
if (org.apache.commons.lang3.StringUtils.equals(forgetToken, token)) { //比较token是否相等
String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
int rowCount = userMapper.updatePasswordByUsername(username, md5Password); //更新密码
if (rowCount > 0) //如果个数大于1,则更新密码成功
return ServerResponse.createBySuccessMessage("修改密码成功");
}else {
return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
}
return ServerResponse.createByErrorMessage("修改密码失败");
}
Dao层:
UserMapper:
public interface UserMapper {
String selectQuestionByUsername(String username);
int checkAnswer(@Param("username")String username,@Param("question")String question,@Param("answer")String answer);
int updatePasswordByUsername(@Param("username")String username,@Param("passwordNew")String passwordNew);
}
<select id="selectQuestionByUsername" resultType="string" parameterType="string">
select
question
from mmall_user
where username = #{username}
</select>
<select id="checkAnswer" resultType="int" parameterType="map">
SELECT
count(1)
from mmall_user
where username=#{username}
and question = #{question}
and answer = #{answer}
</select>
<update id="updatePasswordByUsername" parameterType="map">
update mmall_user
SET password = #{passwordNew},update_time = now()
where username = #{username}
</update>
六、登录状态下重置密码:
1、从session中取出用户
2、校验旧密码是否正确(防止横向越权)
3、正确则修改密码
具体实现代码如下:
Controller层:
//登陆状态下的重置密码
@RequestMapping(value = "reset_password.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> resetPassword(HttpSession session,String passwordOld,String passwordNew){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null)
return ServerResponse.createByErrorMessage("用户未登录");
return iUserService.resetPassword(passwordOld,passwordNew,user); //重置密码
}
interface IUserService :
public interface IUserService {
ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user);
}
Service层:
//登陆状态下的重置密码
public ServerResponse<String> resetPassword(String passwordOld, String passwordNew,User user) {
//防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
if(resultCount == 0)
return ServerResponse.createByErrorMessage("旧密码错误");
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user); //选择性的更新,没变化的就不动,变化了的就更新
if(updateCount > 0) //更新成功
return ServerResponse.createBySuccessMessage("密码更新成功");
return ServerResponse.createByErrorMessage("密码更新失败");
}
Dao层:
UserMapper:
public interface UserMapper {
int checkPassword(@Param(value="password")String password,@Param("userId")Integer userId);
}
<select id="checkPassword" resultType="int" parameterType="map">
SELECT
count(1)
from mmall_user
where password = #{password}
and id = #{userId}
</select>
七、更新用户信息:
1、判断用户是否登录
2、取出用户的id和username
3、判断邮箱是否重复
4、不重复则更新用户信息并将其放入到session中
具体实现代码如下:
Controller层:
//更新用户信息
@RequestMapping(value = "update_information.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> update_information(HttpSession session,User user){
User currentUser = (User)session.getAttribute(Const.CURRENT_USER); //取出当前用户
if(currentUser == null)
return ServerResponse.createByErrorMessage("用户未登录");
user.setId(currentUser.getId());
user.setUsername(currentUser.getUsername()); //取出id和username
ServerResponse<User> response = iUserService.updateInformation(user);
if(response.isSuccess()){ //如果更新成功
response.getData().setUsername(currentUser.getUsername());
session.setAttribute(Const.CURRENT_USER,response.getData()); //将其放入到session中
}
return response;
}
interface IUserService :
public interface IUserService {
ServerResponse<User> updateInformation(User user);
}
Service层:
//更新用户信息,更新完用户信息之后,将其放入到session中
public ServerResponse<User> updateInformation(User user){
//username是不能被更新的
//email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
if(resultCount > 0)
return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
User updateUser = new User();
updateUser.setId(user.getId());
updateUser.setEmail(user.getEmail());
updateUser.setPhone(user.getPhone());
updateUser.setQuestion(user.getQuestion());
updateUser.setAnswer(user.getAnswer());
int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
if(updateCount > 0)
return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
return ServerResponse.createByErrorMessage("更新个人信息失败");
}
Dao层:
UserMapper:
public interface UserMapper {
int checkEmailByUserId(@Param(value="email")String email,@Param(value="userId")Integer userId);
}
<select id="checkEmailByUserId" resultType="int" parameterType="map">
select count(1) from mmall_user
where email = #{email}
and id != #{userId}
</select>
八、获取用户信息(强制登录):
1、判断用户是否登录
2、如果未登录,则强制登录
3、登录则将用户信息取出
具体实现代码如下:
Controller层:
@RequestMapping(value = "get_information.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> get_information(HttpSession session){
User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
if(currentUser == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"未登录,需要强制登录status=10");
}
return iUserService.getInformation(currentUser.getId());
}
interface IUserService :
public interface IUserService {
ServerResponse<User> getInformation(Integer userId);
}
Service层:
public ServerResponse<User> getInformation(Integer userId){
User user = userMapper.selectByPrimaryKey(userId);
if(user == null){
return ServerResponse.createByErrorMessage("找不到当前用户");
}
user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
return ServerResponse.createBySuccess(user);
}
Dao层:
UserMapper:
public interface UserMapper {
User selectByPrimaryKey(Integer id);
}
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from mmall_user
where id = #{id,jdbcType=INTEGER}
</select>
九、管理员登录:
1、判断管理员是否存在
具体实现代码如下:
Controller层:
@Controller
@RequestMapping("/manage/user")
public class UserManageController {
@Autowired
private IUserService iUserService;
@RequestMapping(value="login.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> login(String username, String password, HttpSession session){
ServerResponse<User> response = iUserService.login(username,password);
if(response.isSuccess()){
User user = response.getData();
if(user.getRole() == Const.Role.ROLE_ADMIN){
//说明登录的是管理员
session.setAttribute(Const.CURRENT_USER,user);
return response;
}else{
return ServerResponse.createByErrorMessage("不是管理员,无法登录");
}
}
return response;
}
}
interface IUserService :
public interface IUserService {
ServerResponse checkAdminRole(User user);
}
Service层:
/**
* 校验是否是管理员
* @param user
* @return
*/
public ServerResponse checkAdminRole(User user){
if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
return ServerResponse.createBySuccess();
}
return ServerResponse.createByError();
}