Browse Source

修改免登录功能

master
[yxf] 2 days ago
parent
commit
06faa42891
  1. 4
      im-platform/src/main/java/com/bx/implatform/dto/LoginDTO.java
  2. 115
      im-platform/src/main/java/com/bx/implatform/service/impl/UserServiceImpl.java
  3. 7
      im-platform/src/main/java/com/bx/implatform/vo/LoginVO.java
  4. 7
      im-uniapp/App.vue
  5. 146
      im-uniapp/pages/login/login.vue

4
im-platform/src/main/java/com/bx/implatform/dto/LoginDTO.java

@ -17,11 +17,11 @@ public class LoginDTO {
@Schema(description = "登录终端 0:web 1:app 2:pc")
private Integer terminal;
@NotEmpty(message = "用户名不可为空")
// @NotEmpty(message = "用户名不可为空")
@Schema(description = "用户名")
private String userName;
@NotEmpty(message = "用户密码不可为空")
// @NotEmpty(message = "用户密码不可为空")
@Schema(description = "用户密码")
private String password;

115
im-platform/src/main/java/com/bx/implatform/service/impl/UserServiceImpl.java

@ -50,38 +50,107 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
private final IMClient imClient;
private final SensitiveFilterUtil sensitiveFilterUtil;
// @Override
// public LoginVO login(LoginDTO dto) {
// User user = this.findUserByUserName(dto.getUserName());
// if (Objects.isNull(user)) {
// throw new GlobalException("用户不存在");
// }
// if(user.getIsCustomer() == 2){
// throw new GlobalException("用户不存在");
// }
// if (user.getIsBanned()) {
// String tip = String.format("您的账号因'%s'已被管理员封禁,请联系客服!",user.getReason());
// throw new GlobalException(tip);
// }
// if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
// throw new GlobalException(ResultCode.PASSWOR_ERROR);
// }
// // 生成token
// UserSession session = BeanUtils.copyProperties(user, UserSession.class);
// session.setUserId(user.getId());
// session.setTerminal(dto.getTerminal());
// String strJson = JSON.toJSONString(session);
// String accessToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getAccessTokenExpireIn(),
// jwtProperties.getAccessTokenSecret());
// String refreshToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getRefreshTokenExpireIn(),
// jwtProperties.getRefreshTokenSecret());
// LoginVO vo = new LoginVO();
// vo.setAccessToken(accessToken);
// vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn());
// vo.setRefreshToken(refreshToken);
// vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn());
// return vo;
// }
@Override
public LoginVO login(LoginDTO dto) {
User user = this.findUserByUserName(dto.getUserName());
if (Objects.isNull(user)) {
throw new GlobalException("用户不存在");
}
if(user.getIsCustomer() == 2){
throw new GlobalException("用户不存在");
}
if (user.getIsBanned()) {
String tip = String.format("您的账号因'%s'已被管理员封禁,请联系客服!",user.getReason());
throw new GlobalException(tip);
}
if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
throw new GlobalException(ResultCode.PASSWOR_ERROR);
}
// 生成token
UserSession session = BeanUtils.copyProperties(user, UserSession.class);
session.setUserId(user.getId());
session.setTerminal(dto.getTerminal());
String strJson = JSON.toJSONString(session);
String accessToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getAccessTokenExpireIn(),
jwtProperties.getAccessTokenSecret());
String refreshToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getRefreshTokenExpireIn(),
jwtProperties.getRefreshTokenSecret());
// 生成游客唯一标识UUID
String guestUuid = UUID.randomUUID().toString();
// 生成游客用户名,例如 guest_随机6位数字
String guestUserName = "guest_" + UUID.randomUUID().toString().substring(0, 6);
// 创建游客用户记录
User guestUser = new User();
guestUser.setUserName(guestUserName);
guestUser.setNickName(guestUserName); // 默认昵称为“游客”
guestUser.setPassword(""); // 游客无需密码,可为空
guestUser.setUuid(guestUuid); // 保存唯一标识
// guestUser.setCreateTime(LocalDateTime.now());
// 保存到数据库
this.save(guestUser);
Long customerServiceId = this.getRandomCustomerServiceId();
// 创建会话信息
UserSession guestSession = new UserSession();
guestSession.setUserId(guestUser.getId());
guestSession.setUserName(guestUser.getUserName());
guestSession.setTerminal(dto.getTerminal());
// guestSession.setUuid(guestUuid);
// 生成Token
String guestJson = JSON.toJSONString(guestSession);
String accessToken = JwtUtil.sign(
guestSession.getUserId(),
guestJson,
jwtProperties.getAccessTokenExpireIn(),
jwtProperties.getAccessTokenSecret()
);
String refreshToken = JwtUtil.sign(
guestSession.getUserId(),
guestJson,
jwtProperties.getRefreshTokenExpireIn(),
jwtProperties.getRefreshTokenSecret()
);
// 返回LoginVO
LoginVO vo = new LoginVO();
vo.setAccessToken(accessToken);
vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn());
vo.setRefreshToken(refreshToken);
vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn());
vo.setCustomerServiceId(customerServiceId == null ? -1 : customerServiceId);
// 设置当前登录的游客用户信息
vo.setUser(guestUser);
log.info("游客登录成功,userId:{}, uuid:{}", guestUser.getId(), guestUuid);
return vo;
}
public Long getRandomCustomerServiceId() {
LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
// 条件:is_customer = 2 表示客服
queryWrapper.eq(User::getIsCustomer, 2);
// 只查id字段,提升效率
queryWrapper.select(User::getId);
// 随机排序(mysql用rand())
queryWrapper.last("ORDER BY RAND() LIMIT 1");
User customerService = this.getOne(queryWrapper, false); // false=无结果不抛异常
return customerService == null ? null : customerService.getId();
}
@Override
public LoginVO loginCustom(LoginDTO dto) {

7
im-platform/src/main/java/com/bx/implatform/vo/LoginVO.java

@ -1,5 +1,6 @@
package com.bx.implatform.vo;
import com.bx.implatform.entity.User;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@ -19,4 +20,10 @@ public class LoginVO {
@Schema(description = "refreshToken过期时间(秒)")
private Integer refreshTokenExpiresIn;
@Schema(description = "分配的客服ID")
private Long customerServiceId;
@Schema(description = "当前登录用户信息")
private User user;
}

7
im-uniapp/App.vue

@ -468,8 +468,11 @@ export default {
this.refreshToken(loginInfo).then(() => {
// #ifdef H5
//
uni.switchTab({
url: "/pages/chat/chat"
// uni.switchTab({
// url: "/pages/chat/chat"
// })
uni.navigateTo({
url: "/pages/chat/chat-box?chatIdx=0"
})
// #endif
//

146
im-uniapp/pages/login/login.vue

@ -1,57 +1,14 @@
<template>
<view class="login">
<!-- 主要内容区域 -->
<view class="content">
<!-- Logo和标题区域 -->
<view class="header">
<view class="title">欢迎登录</view>
<view class="subtitle">登录您的账号开启聊天之旅</view>
</view>
<!-- 表单区域 -->
<view class="form-container">
<view class="form">
<view class="form-item" :class="{'focused': userNameFocused}">
<view class="icon-wrapper">
<view class="icon iconfont icon-username"></view>
</view>
<input class="input" type="text" v-model="dataForm.userName" placeholder="用户名"
@focus="userNameFocused = true" @blur="userNameFocused = false" />
</view>
<view class="form-item" :class="{'focused': passwordFocused}">
<view class="icon-wrapper">
<view class="icon iconfont icon-pwd"></view>
</view>
<input class="input" :type="isShowPwd?'text':'password'" v-model="dataForm.password"
placeholder="密码" @focus="passwordFocused = true" @blur="passwordFocused = false" />
<view class="icon-suffix iconfont" :class="isShowPwd?'icon-pwd-show':'icon-pwd-hide'"
@click="onSwitchShowPwd"></view>
</view>
</view>
<!-- 登录按钮 -->
<button class="submit-btn" @click="submit" type="primary">
<view class="btn-content">
<text class="btn-text">立即登录</text>
</view>
</button>
<!-- 底部导航 -->
<view class="nav-tool-bar">
<view class="nav-register">
<navigator url="/pages/register/register" class="register-link">
<text class="register-text">没有账号</text>
<text class="register-highlight">立即注册</text>
</navigator>
</view>
</view>
</view>
</view>
<view>
</view>
</template>
<script>
import UNI_APP from '@/.env.js';
// APP
let GLOBAL_AUTO_LOGIN_LOCK = false;
export default {
data() {
return {
@ -59,55 +16,98 @@ export default {
userNameFocused: false,
passwordFocused: false,
dataForm: {
terminal: 1, // APP
terminal: 1,
userName: '',
password: ''
}
}
},
methods: {
submit() {
if (!this.dataForm.userName) {
return uni.showToast({
title: "请输入您的账号",
icon: "none"
})
}
if (!this.dataForm.password) {
return uni.showToast({
title: "请输入您的密码",
icon: "none"
autoLogin() {
// ========================
//
// ========================
if (GLOBAL_AUTO_LOGIN_LOCK) return;
GLOBAL_AUTO_LOGIN_LOCK = true;
console.log("【自动登录】只执行唯一一次");
//
const loginInfo = uni.getStorageSync("loginInfo");
// const userName = uni.getStorageSync("userName") || "";
// const password = uni.getStorageSync("password") || "";
//
if (loginInfo) {
uni.navigateTo({
url: "/pages/chat/chat-box?chatIdx=0"
})
return;
}
//
// if (!userName || !password) {
// console.log("");
// return;
// }
//
// this.dataForm.userName = userName;
// this.dataForm.password = password;
this.$http({
url: '/login',
data: this.dataForm,
method: 'POST'
}).then(loginInfo => {
console.log("登录成功,自动跳转到聊天页面...")
uni.setStorageSync("userName", this.dataForm.userName);
uni.setStorageSync("password", this.dataForm.password);
uni.setStorageSync("isAgree", this.isAgree);
uni.setStorageSync("loginInfo", loginInfo);
// App.vue
getApp().$vm.init()
//
uni.switchTab({
url: "/pages/chat/chat"
console.log("loginInfo", loginInfo);
this.$http({
url: "/friend/add?friendId=" + loginInfo.customerServiceId,
method: "POST"
}).then((data) => {
let friend = {
id: loginInfo.user.id,
nickName: loginInfo.user.nickName,
headImage: loginInfo.user.headImageThumb,
online: loginInfo.user.online,
delete: false
}
this.friendStore.addFriend(friend);
uni.navigateTo({
url: "/pages/chat/chat-box?chatIdx=0"
})
}).catch((e) => {
console.log("登录失败:", e);
})
//
getApp().$vm.unloadStore();
}).catch(err => {
console.log("自动登录失败", err);
});
// uni.navigateTo({ url: "/pages/chat/chat-box?chatIdx=0" });
},
onSwitchShowPwd() {
this.isShowPwd = !this.isShowPwd;
}
},
},
onLoad() {
this.dataForm.userName = uni.getStorageSync("userName");
this.dataForm.password = uni.getStorageSync("password");
//
setTimeout(() => {
this.autoLogin();
}, 50);
},
onShow() {
//
}
}
</script>

Loading…
Cancel
Save