在线教育项目用户登录和注册(四)

简介: 在线教育项目用户登录和注册(四)

5.2 登录成功:生成token

  • 准备工作已完成

image.png

  • 登录成功,将 EduUser 转换成token,并响应给用户

image.png

 @PostMapping("/login")
    public BaseResult login(@RequestBody EduUser eduUser) {
        //1 校验验证码
        // 1.1 获得redis
        String redisName = "login_verify_code_" + eduUser.getUsername();
        String redisVerifyCode = stringRedisTemplate.opsForValue().get(redisName);
        // 1.2 删除redis
        stringRedisTemplate.delete(redisName);
        // 1.3 校验:无效
        if(redisVerifyCode == null) {
            return BaseResult.error("验证码无效");
        }
        // 1.4 校验:错误
        if(!redisVerifyCode.equalsIgnoreCase(eduUser.getVerifycode())) {
            return BaseResult.error("验证码错误");
        }
        //2 通过service用户登录
        EduUser loginUser = eduUserService.login(eduUser);
        //3 提示
        if(loginUser != null) {
            if("0".equals(loginUser.getStatus())) {
                return BaseResult.error("用户未激活,请先激活");
            }
            if("2".equals(loginUser.getStatus())) {
                return BaseResult.error("临时冻结,36小时");
            }
            if("3".equals(loginUser.getStatus())) {
                return BaseResult.error("该账号已冻结");
            }
            // 需要设置token
            //String token = "admin-token";
            String token = JwtUtils.generateToken(loginUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());
            return BaseResult.ok("登录成功").append("token", token);
        }
        return BaseResult.error("用户名或密码不匹配");
    }

5.3 查询详情:获得token

5.3.1 基本流程

  • 登录成功后,默认跳转到 / 页面

image.png

访问 / ,在路由中配置跳转的位置

image.png

  • 在跳转 / 页面前,执行vuex中 user/getInfo

16612f255315468ba7dbe250b1bf02b5.png

通过vuex执行ajax请求,查询详情

image.png

5.3.2 查询详情

  • 修改 EduUserController 添加方法

image.png

   @GetMapping("/info")
    public BaseResult info( String token) {
        try {
            //1 通过token 获得用户信息
            EduUser eduUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), EduUser.class);
            //2 模拟数据
/*        Map<String,Object> map = new HashMap<>();
        if("admin-token".equalsIgnoreCase(token)) {
            map.put("roles", Arrays.asList("admin"));        //角色的值必须是数组
            map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            map.put("name","张三三");
        } else {
            // 非管理员的权限
        }*/
            //3 真实数据
            Map<String,Object> map = new HashMap<>();
            if(eduUser.getRoles() != null) {
                map.put("roles", eduUser.getRoles().split(","));        //角色的值必须是数组
            } else {
                map.put("roles", Arrays.asList("editor"));        //没有权限的固定:editor
            }
            map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");    //需要完善用户头像
            map.put("name",eduUser.getUsername());
            // 数据返回  baseResult.data --> Map
            return BaseResult.ok("获得权限成功", map);
        } catch (Exception e) {
            return BaseResult.error("获得权限失败");
        }
    }

5.4 过滤器

5.4.1 配置yml

sc:
  jwt:
    secret: sc@Login(Auth}*^31)&czxy% # 登录校验的密钥
    pubKeyPath: D:/rsa/rsa.pub # 公钥地址
    priKeyPath: D:/rsa/rsa.pri # 私钥地址
    expire: 360 # 过期时间,单位分钟
  filter:
    allowPaths:
      - swagger
      - /api-docs
      - /user/login
      - /user/info
      - /user/register
      - /user/sendemail
      - /user/verifycode

5.4.2 配置类

image.png

FilterProperties

package com.czxy.zx.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@Data
@ConfigurationProperties(prefix = "sc.filter")
public class FilterProperties {
    private List<String> allowPaths;
}

JwtProperties

package com.czxy.zx.config;
import com.czxy.zx.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@Configuration
@ConfigurationProperties(prefix = "sc.jwt")
@Data
public class JwtProperties {
    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private Integer expire;
    private PublicKey publicKey;
    private PrivateKey privateKey;
    @PostConstruct      //初始化方法注解
    public void init() {
        try {
            File pubFile = new File(pubKeyPath);
            File priFile = new File(priKeyPath);
            if(!pubFile.exists() || ! priFile.exists()) {
                RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
            }
            // 获得公钥和私钥对象
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.4.3 过滤器

package com.czxy.zx.filter;

import com.czxy.zx.config.FilterProperties;
import com.czxy.zx.config.JwtProperties;
import com.czxy.zx.domain.EduUser;
import com.czxy.zx.utils.JwtUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@Component
@EnableConfigurationProperties(FilterProperties.class)
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private FilterProperties filterProperties;
    @Resource
    private JwtProperties jwtProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //1 获得请求路径
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            System.out.println(path);
            //2 白名单
            List<String> allowPaths = filterProperties.getAllowPaths();
            for (String allowPath : allowPaths) {
                if(path.contains(allowPath)) {
                    // 放行
                    return chain.filter(exchange);
                }
            }
            //3 获得token
            String token = request.getHeaders().getFirst("X-Token");
            //4 校验token
            JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), EduUser.class);
            //5.1  成功,放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //5.2 失败,返回提示`token失效`
            ServerHttpResponse response = exchange.getResponse();
            // 响应状态 401 没有权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应数据的编码
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            // 响应“没有权限”提示
            DataBuffer wrap = response.bufferFactory().wrap("没有权限".getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Flux.just(wrap));
        }
    }
    @Override
    public int getOrder() {
        return 1;
    }
}

5.5 token 无效

image.png

c7bfedffe80140ae998bd69760f2035d.png

 MessageBox.confirm('没有权限,将重新登录', '重新登录提示框', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    }) 

6.作业:激活

6.1 分析

需求:

  • 用户点击链接后可以进行账号激活,将用户的状态0改成1
  • 用户重复点击,提示“账号已经激活,无需重复激活”
  • 需要防止其他人帮着激活
  • 激活成功了,跳转到登录页面,“账号已激活,请登录”
  • 1天不激活,激活链接失效,需要重新发送

c2f5727b215442ed84f8ae53add8d10f.png

6.2 完善用户注册

image.png

@PostMapping("/register")
    public BaseResult register(@RequestBody EduUser eduUser) {
        //1 校验
        // 1.1 密码
        if(StringUtils.isBlank(eduUser.getPassword())) {
            ExceptionUtils.cast("密码不能为空");
        }
        if(! eduUser.getPassword().equals(eduUser.getRepassword())) {
            ExceptionUtils.cast("确认密码和密码不一致");
        }
        // 1.2 验证码
        // 1) 获得redis验证码
        String key = "register" + eduUser.getUsername() ;
        String redisVerifyCode = stringRedisTemplate.opsForValue().get(key);
        // 2) 删除redis验证码
        stringRedisTemplate.delete(key);
        // 3) 无效
        if(redisVerifyCode == null) {
            ExceptionUtils.cast("验证码无效");
        }
        // 4) 不对
        if(! redisVerifyCode.equalsIgnoreCase(eduUser.getVerifycode())) {
            ExceptionUtils.cast("验证码错误");
        }
        //2 注册
        boolean register = eduUserService.register(eduUser);
        //3 成功,发送激活邮件
        if(register) {
            // 成功
            // 获得uuid值
            String uuidStr = UUID.randomUUID().toString().replace("-", "");
            // 将uuid存放到redis中,设置有效时间
            stringRedisTemplate.opsForValue().set(uuidStr,eduUser.getUsername(), 24, TimeUnit.HOURS);
            // 发送激活邮件
            UserEmail userEmail = new UserEmail();
            userEmail.setEmail(eduUser.getEmail());
            userEmail.setTitle("XXX平台激活邮件");
            // TODO 作业:用户激活
            //String url = "http://localhost:10010/user-service/user/active?username=" + eduUser.getUsername();
            String url = "http://localhost:9527/#/active?uuid=" + uuidStr;
            String msg = eduUser.getUsername() + ",你好:<br/>" +
                        "<a href='"+url+"'>点击</a>链接进行账号激活。<br/>" +
                        "如果不能点击,请复制下面的连接:" + url;
            userEmail.setText(msg);
            System.out.println(eduUser.getId());
            //3 发送邮件-将邮件信息存放mq
            String jsonStr = JSON.toJSONString(userEmail);
            rabbitTemplate.convertAndSend("", RabbitEmailConfig.QUEUE_NAME, jsonStr);
            return BaseResult.ok("注册成功,请进行账号激活");
        }
        return BaseResult.error("注册失败");
    }

6.3 用户激活

6.3.1 前端实现

  • 步骤:
  • 步骤1:编写激活页面
  • 步骤2:编写ajax函数
  • 步骤3:添加白名单
  • 步骤1:编写激活页面

image.png

 
         
  • 步骤2:编写ajax函数

image.png

 
         

步骤3:添加白名单

image.png

6.3.2 后端实现

image.png

 
         

6.4 完善用户登录

image.png

 
         
相关文章
|
机器学习/深度学习 运维 算法
Machine Learning机器学习之向量机(Support Vector Machine,SVM)
Machine Learning机器学习之向量机(Support Vector Machine,SVM)
|
3月前
|
存储 弹性计算 人工智能
2026年9月阿里云服务器租用价格表(一年/按月/按小时报价明细)
本文为2026年9月阿里云主流云服务(轻量服务器、ECS、GPU实例)的实时价格参考与选型指南,涵盖配置报价、计费模式对比及新用户优惠、地域降本等实用省钱技巧,助开发者高效决策。(239字)
599 0
|
6月前
|
存储 算法 Java
【JVM虚拟机】垃圾回收GC:垃圾收集器:G1:Region分区、Mixed GC、回收流程、适用场景(高频)(附《思维导图》+《面试高频考点清单》)
G1是JDK 9起默认的低延迟垃圾收集器,将堆划分为2048个可动态分配角色的Region,通过Mixed GC优先回收垃圾最多的区域,结合Remembered Set与SATB算法,在大堆(≥4GB)场景下实现可预测停顿(如≤200ms)与高吞吐平衡。
1022 2
|
人工智能 自然语言处理 数据可视化
2025年适合大型企业的BI产品及企业高效运用BI工具指南
本文将聚焦适合大型企业的BI产品选型,深入解析主流产品优势,并结合实践经验探讨企业如何用好BI工具,为各行业企业提供专业参考。
|
12月前
|
JSON 监控 API
日本股票 API 对接实战指南(实时行情与 IPO 专题)
随着巴菲特增持日本商社及日经225强势表现,日本股市备受关注。本文介绍如何通过StockTV API(countryId=35)快速接入日本股市实时行情、IPO新股日历与K线数据,支持秒级更新与多周期技术分析,助力开发者高效构建金融应用。
2493 156
|
12月前
|
数据采集 人工智能 数据可视化
2025年数据中台系统选型指南:热门推荐与能力盘点
2025年,数据中台成为企业数字化转型核心。本文深度解析瓴羊Dataphin、腾讯云WeData、华为云DataArts Studio、网易数帆EasyData及Talend Data Fabric五大主流平台,从产品能力、行业实践、技术优势等维度对比分析,助力企业实现数据标准化、治理高效化与消费便捷化,释放数据价值,提升竞争力。
|
12月前
|
存储 人工智能 BI
玄晶引擎AI手机双轨实践:基于阿里云生态的B/C端技术复用与落地
玄晶引擎依托阿里云,构建“云-边-端”协同架构,通过PAI、RPA等服务实现B端企业应用与C端个人助手的技术复用,形成“一套底座、双轨落地”的AI手机新范式,助力开发者高效降本、快速规模化。
953 12
|
存储 SQL 供应链
如何开发仓库管理系统中的出入库管理板块 ?(附架构图+流程图+代码参考)
本文详细介绍了仓库管理系统(WMS)中出入库管理模块的开发与实现。内容涵盖功能模块设计、业务流程梳理、技术实现技巧及实际应用效果,助力企业高效构建定制化仓库管理系统,提升库存管理效率与准确性。
|
存储 安全 索引
机械硬盘文件丢失为何大概率能恢复
本文详解机械硬盘数据恢复原理与方法,涵盖误删、格式化、分区丢失等常见问题,解析恢复成功率及操作步骤,助你了解如何有效找回丢失数据。
|
JavaScript API 数据安全/隐私保护
淘宝店铺订单相关API接口详解
本文详细介绍了淘宝店铺订单相关的三个关键API接口:订单列表、订单详情和订单物流。通过这些接口,开发者可以获取订单信息、买家详情、商品清单、支付信息及物流轨迹,支持多种筛选条件和复杂参数传递。此外,文章还强调了接口权限申请、数据安全处理及调用频率限制等注意事项,帮助开发者高效集成这些接口,提升电商系统的功能和用户体验。供稿者:Taobaoapi2014。 (239字符)
1184 0

热门文章

最新文章