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") @Schema(description = "登录终端 0:web 1:app 2:pc")
private Integer terminal; private Integer terminal;
@NotEmpty(message = "用户名不可为空") // @NotEmpty(message = "用户名不可为空")
@Schema(description = "用户名") @Schema(description = "用户名")
private String userName; private String userName;
@NotEmpty(message = "用户密码不可为空") // @NotEmpty(message = "用户密码不可为空")
@Schema(description = "用户密码") @Schema(description = "用户密码")
private String password; 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 IMClient imClient;
private final SensitiveFilterUtil sensitiveFilterUtil; 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 @Override
public LoginVO login(LoginDTO dto) { public LoginVO login(LoginDTO dto) {
User user = this.findUserByUserName(dto.getUserName()); // 生成游客唯一标识UUID
if (Objects.isNull(user)) { String guestUuid = UUID.randomUUID().toString();
throw new GlobalException("用户不存在");
} // 生成游客用户名,例如 guest_随机6位数字
if(user.getIsCustomer() == 2){ String guestUserName = "guest_" + UUID.randomUUID().toString().substring(0, 6);
throw new GlobalException("用户不存在");
} // 创建游客用户记录
if (user.getIsBanned()) { User guestUser = new User();
String tip = String.format("您的账号因'%s'已被管理员封禁,请联系客服!",user.getReason()); guestUser.setUserName(guestUserName);
throw new GlobalException(tip); guestUser.setNickName(guestUserName); // 默认昵称为“游客”
} guestUser.setPassword(""); // 游客无需密码,可为空
if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) { guestUser.setUuid(guestUuid); // 保存唯一标识
throw new GlobalException(ResultCode.PASSWOR_ERROR); // guestUser.setCreateTime(LocalDateTime.now());
} // 保存到数据库
// 生成token this.save(guestUser);
UserSession session = BeanUtils.copyProperties(user, UserSession.class); Long customerServiceId = this.getRandomCustomerServiceId();
session.setUserId(user.getId());
session.setTerminal(dto.getTerminal());
String strJson = JSON.toJSONString(session); // 创建会话信息
String accessToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getAccessTokenExpireIn(), UserSession guestSession = new UserSession();
jwtProperties.getAccessTokenSecret()); guestSession.setUserId(guestUser.getId());
String refreshToken = JwtUtil.sign(user.getId(), strJson, jwtProperties.getRefreshTokenExpireIn(), guestSession.setUserName(guestUser.getUserName());
jwtProperties.getRefreshTokenSecret()); 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(); LoginVO vo = new LoginVO();
vo.setAccessToken(accessToken); vo.setAccessToken(accessToken);
vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn()); vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn());
vo.setRefreshToken(refreshToken); vo.setRefreshToken(refreshToken);
vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn()); vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn());
vo.setCustomerServiceId(customerServiceId == null ? -1 : customerServiceId);
// 设置当前登录的游客用户信息
vo.setUser(guestUser);
log.info("游客登录成功,userId:{}, uuid:{}", guestUser.getId(), guestUuid);
return vo; 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 @Override
public LoginVO loginCustom(LoginDTO dto) { 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; package com.bx.implatform.vo;
import com.bx.implatform.entity.User;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
@ -19,4 +20,10 @@ public class LoginVO {
@Schema(description = "refreshToken过期时间(秒)") @Schema(description = "refreshToken过期时间(秒)")
private Integer refreshTokenExpiresIn; 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(() => { this.refreshToken(loginInfo).then(() => {
// #ifdef H5 // #ifdef H5
// //
uni.switchTab({ // uni.switchTab({
url: "/pages/chat/chat" // url: "/pages/chat/chat"
// })
uni.navigateTo({
url: "/pages/chat/chat-box?chatIdx=0"
}) })
// #endif // #endif
// //

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

@ -1,57 +1,14 @@
<template> <template>
<view class="login"> <view>
<!-- 主要内容区域 -->
<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> </template>
<script> <script>
import UNI_APP from '@/.env.js'; import UNI_APP from '@/.env.js';
// APP
let GLOBAL_AUTO_LOGIN_LOCK = false;
export default { export default {
data() { data() {
return { return {
@ -59,55 +16,98 @@ export default {
userNameFocused: false, userNameFocused: false,
passwordFocused: false, passwordFocused: false,
dataForm: { dataForm: {
terminal: 1, // APP terminal: 1,
userName: '', userName: '',
password: '' password: ''
} }
} }
}, },
methods: { methods: {
submit() { autoLogin() {
if (!this.dataForm.userName) { // ========================
return uni.showToast({ //
title: "请输入您的账号", // ========================
icon: "none" if (GLOBAL_AUTO_LOGIN_LOCK) return;
}) GLOBAL_AUTO_LOGIN_LOCK = true;
}
if (!this.dataForm.password) { console.log("【自动登录】只执行唯一一次");
return uni.showToast({
title: "请输入您的密码", //
icon: "none" 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({ this.$http({
url: '/login', url: '/login',
data: this.dataForm, data: this.dataForm,
method: 'POST' method: 'POST'
}).then(loginInfo => { }).then(loginInfo => {
console.log("登录成功,自动跳转到聊天页面...")
uni.setStorageSync("userName", this.dataForm.userName);
uni.setStorageSync("password", this.dataForm.password);
uni.setStorageSync("isAgree", this.isAgree); uni.setStorageSync("isAgree", this.isAgree);
uni.setStorageSync("loginInfo", loginInfo); uni.setStorageSync("loginInfo", loginInfo);
// App.vue
getApp().$vm.init() getApp().$vm.init()
// console.log("loginInfo", loginInfo);
uni.switchTab({ this.$http({
url: "/pages/chat/chat" 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(); getApp().$vm.unloadStore();
}).catch(err => {
console.log("自动登录失败", err);
});
// uni.navigateTo({ url: "/pages/chat/chat-box?chatIdx=0" });
}, },
onSwitchShowPwd() { onSwitchShowPwd() {
this.isShowPwd = !this.isShowPwd; this.isShowPwd = !this.isShowPwd;
}
}, },
},
onLoad() { onLoad() {
this.dataForm.userName = uni.getStorageSync("userName");
this.dataForm.password = uni.getStorageSync("password"); //
setTimeout(() => {
this.autoLogin();
}, 50);
},
onShow() {
//
} }
} }
</script> </script>

Loading…
Cancel
Save