第十二章 Redis短信登录实战(基于Session)

ops/2024/10/11 5:03:43/

目录

一、User类

二、ThreadLocal类 

三、用户业务逻辑接口 

四、用户业务逻辑接口实现类 

五、用户控制层 

六、用户登录拦截器 

七、拦截器配置类 

八、隐藏敏感信息的代码调整 


完整的项目资源共享地址,当中包含了代码、资源文件以及Nginx(Windows版)和完整的配置:

链接:https://pan.quark.cn/s/5c28484d7882
提取码:cJxQ

其中对于短信登录这块代码已经做了优化,通过Redis实现短信验证码登录,想要按照Session方式进行登录来学习Session的短信验证码登录流程的,可以将工程相关代码按下述的代码进行修改调整。 

一、User类

package com.hmdp.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_user")
public class User implements Serializable {private static final long serialVersionUID = 1L;/*** 主键*/@TableId(value = "id", type = IdType.AUTO)private Long id;/*** 手机号码*/private String phone;/*** 密码,加密存储*/private String password;/*** 昵称,默认是随机字符*/private String nickName;/*** 用户头像*/private String icon = "";/*** 创建时间*/private LocalDateTime createTime;/*** 更新时间*/private LocalDateTime updateTime;}

二、ThreadLocal类 

package com.hmdp.utils;import com.hmdp.entity.User;public class UserHolder {private static final ThreadLocal<User> tl = new ThreadLocal<>();public static void saveUser(User user){tl.set(user);}public static User getUser(){return tl.get();}public static void removeUser(){tl.remove();}
}

三、用户业务逻辑接口 

package com.hmdp.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;import javax.servlet.http.HttpSession;public interface IUserService extends IService<User> {Result sendCode(String phone, HttpSession session);Result login(LoginFormDTO loginForm, HttpSession session);
}

四、用户业务逻辑接口实现类 

package com.hmdp.service.impl;import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result sendCode(String phone, HttpSession session) {// 1.校验手机号if (RegexUtils.isPhoneInvalid(phone)) {// 2.如果不符合,返回错误信息return Result.fail("手机号格式错误!");}// 3.符合,生成验证码String code = RandomUtil.randomNumbers(6);// 4.保存验证码到 sessionsession.setAttribute("code:" + phone, code);// 5.发送验证码log.debug("发送短信验证码成功,验证码:{}", code);// 返回okreturn Result.ok();}@Overridepublic Result login(LoginFormDTO loginForm, HttpSession session) {// 1.校验手机号String phone = loginForm.getPhone();if (RegexUtils.isPhoneInvalid(phone)) {// 2.如果不符合,返回错误信息return Result.fail("手机号格式错误!");}// 2. 校验验证码Object cacheCode = session.getAttribute("code:" + loginForm.getPhone());String code = loginForm.getCode();// 3. 不一致则报错if (cacheCode == null || !cacheCode.toString().equals(code)) {return Result.fail("验证码错误");}// 4. 一致,则根据手机号查询用户User user = query().eq("phone", phone).one();// 5. 判断用户是否存在if (user == null) {// 6. 不存在则创建用户并保存createUserWithPhone(phone);}// 7. 保存用户信息到session中session.setAttribute("user", user);// 8.返回tokenreturn Result.ok();}private User createUserWithPhone(String phone) {// 1.创建用户User user = new User();user.setPhone(phone);user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));// 2.保存用户save(user);return user;}
}

五、用户控制层 

package com.hmdp.controller;import com.hmdp.dto.Result;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {@Resourceprivate IUserService userService;/*** 发送手机验证码*/@PostMapping("code")public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {// 发送短信验证码并保存验证码return userService.sendCode(phone, session);}/*** 登录功能* @param loginForm 登录参数,包含手机号、验证码;或者手机号、密码*/@PostMapping("/login")public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){// 实现登录功能return userService.login(loginForm, session);}@GetMapping("/me")public Result me(){// 获取当前登录的用户并返回User user = UserHolder.getUser();return Result.ok(user);}
}

六、用户登录拦截器 

package com.hmdp.utils;import com.hmdp.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 1. 获取SessionHttpSession session = request.getSession();// 2. 获取session中的用户Object user = session.getAttribute("user");// 3. 判断用户是否存在if (user == null) {// 4. 不存在则拦截并返回401状态码response.setStatus(401);return false;}// 5. 存在则保存用户信息到ThreadLocalUserHolder.saveUser((User) user);return true;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// 移除用户UserHolder.removeUser();}
}

七、拦截器配置类 

package com.hmdp.config;import com.hmdp.utils.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MvcConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 登录拦截器registry.addInterceptor(new LoginInterceptor()).excludePathPatterns("/shop/**","/voucher/**","/shop-type/**","/upload/**","/blog/hot","/user/code","/user/login");}
}

八、隐藏敏感信息的代码调整 

上述代码中存入Session中的用户信息涉及到了很多的敏感字段,如手机号、密码等,会有安全风险,所以对代码优化如下:

package com.hmdp.dto;import lombok.Data;@Data
public class UserDTO {private Long id;private String nickName;private String icon;
}
package com.hmdp.utils;import com.hmdp.dto.UserDTO;public class UserHolder {private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();public static void saveUser(UserDTO user){tl.set(user);}public static UserDTO getUser(){return tl.get();}public static void removeUser(){tl.remove();}
}
package com.hmdp.controller;import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {@Resourceprivate IUserService userService;@Resourceprivate IUserInfoService userInfoService;/*** 发送手机验证码*/@PostMapping("code")public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {// 发送短信验证码并保存验证码return userService.sendCode(phone, session);}/*** 登录功能* @param loginForm 登录参数,包含手机号、验证码;或者手机号、密码*/@PostMapping("/login")public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){// 实现登录功能return userService.login(loginForm, session);}@GetMapping("/me")public Result me(){// 获取当前登录的用户并返回UserDTO user = UserHolder.getUser();return Result.ok(user);}
}
package com.hmdp.utils;import com.hmdp.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 1. 获取SessionHttpSession session = request.getSession();// 2. 获取session中的用户Object user = session.getAttribute("user");// 3. 判断用户是否存在if (user == null) {// 4. 不存在则拦截并返回401状态码response.setStatus(401);return false;}// 5. 存在则保存用户信息到ThreadLocalUserHolder.saveUser((UserDTO) user);return true;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// 移除用户UserHolder.removeUser();}
}


http://www.ppmy.cn/ops/123815.html

相关文章

《Electron 基础知识》设置 Vue 中引用的文件路径别名

vite.renderer.config.mjs 文件中配置 代码第1行&#xff0c;引入 resolve &#xff1b;代码第 6 - 10 行&#xff0c;设置路径别名&#xff0c;注意没有后缀 /&#xff1b; import { resolve } from pathexport default defineConfig((env) > {return {resolve: {alias: …

Java LeetCode 每日一题

3162. 优质数对的总数 I package JavaExercise20241010;public class JavaExercise { }class Solution {public int numberOfPairs(int[] nums1, int[] nums2, int k) {int sum 0;int length1 nums1.length;int length2 nums2.length;for (int i 0; i < length1; i) {f…

免费气象可视化的前端框架概述

用于气象可视化的前端框架&#xff0c;通常需要具备处理大规模数据、交互性和动态更新的能力。以下是一些适合气象数据可视化的前端框架&#xff1a; 1. D3.js 简介: D3.js 是一个非常流行的 JavaScript 数据可视化库&#xff0c;可以将气象数据转化为交互式图表和地图。它非…

【Flutter】- 核心语法

文章目录 知识回顾前言源码分析1. 有状态组件2. 无状态组件3. 组件生命周期4. 常用组件Container组件Text组件Image组件布局组件row colum stack expandedElevntButton按钮拓展知识总结知识回顾 【Flutter】- 基础语法 前言 Flutter是以组件化的思想构建客户端页面的,类似于…

关于相机的一些零碎知识点

热成像&#xff0c;英文为Thermal Imaging&#xff0c;例如型号500T&#xff0c;其实指的就是热成像500分辨率。 相机的CMOS&#xff0c;英文为Complementary Metal Oxide Semiconductor&#xff0c;是数码相机的核心成像部件&#xff0c;是一种互补金属氧化物导体器件。 DPI…

Python爱心射线(完整代码)

目录 系列目录 写在前面​ 完整代码 下载代码 代码分析 写在后面 系列目录 序号直达链接表白系列1Python制作一个无法拒绝的表白界面2Python满屏飘字表白代码3

云数据库价格贵吗?云数据库租用价格表

云数据库价格贵吗&#xff1f;这是许多企业在考虑迁移到云端时常问的问题。实际上&#xff0c;云数据库的价格并不是一成不变的&#xff0c;主要取决于多种因素&#xff0c;包括业务需求、所选配置、服务提供商以及使用时长等。 首先&#xff0c;不同的云服务提供商会提供多样化…

JS中的浅拷贝手段

1.slice方法 let arr [1,2,3] let newArr arr.slice(); newArr[0] 100; console.log(arr);//[1,2,3]当修改newArr的时候&#xff0c;arr的值并不改变&#xff0c;什么原因&#xff1f;因为这里newArr是arr浅拷贝后的结果&#xff0c;newArr和arr现在引用的已经不是同一块空…