fix: 微信登陆随机账号

This commit is contained in:
abearxiong 2025-04-03 20:20:42 +08:00
parent f09549b61e
commit 197d6415d3

View File

@ -3,9 +3,11 @@ import { useContextKey } from '@kevisual/use-config/context';
import { UserModel } from '@kevisual/code-center-module';
import { Buffer } from 'buffer';
import { CustomError } from '@kevisual/router';
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
const User = useContextKey<typeof UserModel>('UserModel');
export class WxServices {
token: WxTokenResponse;
wxToken: WxTokenResponse;
// 创建一个webToken用户登录
webToken: string;
accessToken: string;
@ -16,12 +18,31 @@ export class WxServices {
constructor() {
//
}
async checkUserExist(username: string) {
const user = await User.findOne({
where: {
username,
},
});
return !!user;
}
async randomUsername() {
const a = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
const b = customAlphabet('1234567890', 10);
const random = '@' + a(4) + '' + b(4);
const user = await this.checkUserExist(random);
if (user) {
return this.randomUsername();
}
return random;
}
async login(code: string) {
const token = await fetchToken(code);
console.log('login token', token);
if (!token.unionid) {
throw new CustomError(400, 'code is invalid, wxdata can not be found');
}
this.wxToken = token;
const unionid = token.unionid;
let user = await User.findOne({
where: {
@ -41,7 +62,8 @@ export class WxServices {
console.log('mp-user login openid update=============', token.openid, token.unionid);
}
if (!user) {
user = await User.createUser(unionid, unionid.slice(0, 8));
const username = await this.randomUsername();
user = await User.createUser(username, nanoid(10));
user.data = {
...user.data,
// @ts-ignore
@ -72,7 +94,11 @@ export class WxServices {
async checkHasUser() {}
async getUserInfo() {
const userInfo = await getUserInfo(this.token.access_token, this.token.openid);
try {
if (!this.wxToken) {
throw new CustomError(400, 'wxToken is not set');
}
const userInfo = await getUserInfo(this.wxToken.access_token, this.wxToken.openid);
const { nickname, headimgurl } = userInfo;
this.user.nickname = nickname;
try {
@ -82,6 +108,9 @@ export class WxServices {
console.error('Error downloading or converting image:', error);
}
await this.user.save();
} catch (error) {
console.error('Error getting user info:', error);
}
}
/**
* base64