文章目录
- 1. 前端用户信息保存
- 2. 登录页面添加
- 3. 后端实现
1. 前端用户信息保存
使用pinia持久化保存用户名密码
src/stores/remember-me.js
// 定义 store
import { defineStore } from "pinia"
import {reactive} from 'vue'export const useRememberMeStore = defineStore('rememberMe', () => {const rememberMe = reactive({username: '',password: ''})const setRememberMe = (newusername: string, newpassword: string) => {rememberMe.username = newusernamerememberMe.password = newpassword}const removeRememberMe = () => {rememberMe.username = ''rememberMe.password = ''}return {rememberMe, setRememberMe, removeRememberMe}
},
{persist: true // 持久化存储
}
)
2. 登录页面添加
import { useRememberMeStore } from '@/stores/remember-me'
const rememberMeStore = useRememberMeStore()// 查询本地是否保存用户信息const getRemember = () => {if (rememberMeStore.rememberMe.username && rememberMeStore.rememberMe.password) {loginForm.username = atob(rememberMeStore.rememberMe.username)loginForm.password = atob(rememberMeStore.rememberMe.password)console.log(rememberMeStore.rememberMe.username, rememberMeStore.rememberMe.password)}}getRemember()// 保存用户信息const setRememberMe = (username: string, password: string) => {rememberMeStore.setRememberMe(btoa(username), btoa(password))}
在登录成功后保存记住信息
3. 后端实现
修改后端代码:
@Overridepublic LoginVo login(LoginDto loginDto) {SysUser user = getUserByName(loginDto.getUsername());if (ObjectUtil.isNull(user)) {throw new ServiceException(HttpStatus.UNAUTHORIZED,"认证失败!");}if (!BCryptUtils.checkpw(loginDto.getPassword(), user.getPassword())) {throw new ServiceException(HttpStatus.UNAUTHORIZED,"密码错误!");}LoginVo loginVo = null;try {loginVo= getLoginVo(user);} catch (Exception e) {e.printStackTrace();throw new ServiceException(HttpStatus.UNAUTHORIZED, "用户相关信息错误");}// 登录,获取tokenInfo , 存储用户sessionif (loginDto.getRememberMe()) {StpUtil.login(user.getId()); // 记住登录} else {StpUtil.login(user.getId(), false); // 登录}// 设置用户信息StpUtil.getSession().set("userInfo", new UserInfo(user.getId(), user.getUsername()));// 获取tokenSaTokenInfo tokenInfo = StpUtil.getTokenInfo();loginVo.setSaTokenInfo(tokenInfo);return loginVo;}