添加用户

This commit is contained in:
2024-09-28 16:43:59 +08:00
parent 1505c25166
commit 962d89ff29
12 changed files with 303 additions and 42 deletions

View File

@@ -41,7 +41,7 @@ RouterCodeModel.init(
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
comment: '用户code id',
comment: 'code id',
},
path: {
type: DataTypes.STRING,

View File

@@ -1,24 +1,60 @@
import { useConfig } from '@abearxiong/use-config';
import { sequelize } from '@/modules/sequelize.ts';
import { DataTypes, Model } from 'sequelize';
import { createToken, checkToken } from '@abearxiong/auth/token';
import { cryptPwd } from '@abearxiong/auth';
import { nanoid } from 'nanoid';
import { CustomError } from '@abearxiong/router';
const config = useConfig<{ tokenSecret: string }>();
export class User extends Model {
declare id: number;
username: string;
password: string;
salt: string;
remark: string;
declare id: string;
declare username: string;
declare password: string;
declare salt: string;
declare needChangePassword: boolean;
declare description: string;
declare data: any;
async createToken() {
const { id, username } = this;
const expireTime = 60 * 60 * 24 * 7; // 7 days
const now = new Date().getTime();
const token = await createToken({ id, username }, config.tokenSecret);
return { token, expireTime: now + expireTime };
}
static async verifyToken(token: string) {
return await checkToken(token, config.tokenSecret);
}
static createUser(username: string, password?: string, description?: string) {
const user = User.findOne({ where: { username } });
if (user) {
throw new CustomError('User already exists');
}
const salt = nanoid(6);
let needChangePassword = !password;
password = password || '123456';
const cPassword = cryptPwd(password, salt);
return User.create({ username, password: cPassword, description, salt, needChangePassword });
}
createPassword(password: string) {
const salt = this.salt;
const cPassword = cryptPwd(password, salt);
this.password = cPassword;
return cPassword;
}
}
User.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
@@ -28,28 +64,44 @@ User.init(
type: DataTypes.STRING,
allowNull: false,
},
remark: {
description: {
type: DataTypes.STRING,
},
needChangePassword: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
data: {
type: DataTypes.JSON,
defaultValue: {},
},
},
{
sequelize,
tableName: 'cf_user',
},
);
// User.sync({ alter: true });
User.sync({ alter: true, logging: false })
.then((res) => {
// initializeUser();
})
.catch((err) => {
console.error('Sync User error', err);
});
export const initializeUser = async () => {
const w = await User.findOne();
const w = await User.findAndCountAll();
console.info('[User count]', w.count);
const password = '2e8a305521bba54f49638ed25e46adf3'; //123456
const salt = '123';
const users = [{ username: 'admin' }, { username: 'user' }, { username: 'root' }];
if (!w) {
if (w.count < 1) {
const newUsers = await User.bulkCreate(
users.map((user) => {
return {
...user,
password,
needChangePassword: true,
salt,
};
}),
@@ -57,3 +109,5 @@ export const initializeUser = async () => {
console.info('[create new Users]', newUsers);
}
};
// initializeUser();

View File

@@ -1,3 +1,12 @@
import './demo/index.ts';
import './admin/index.ts';
import './routes/index.ts';
import './routes/index.ts';
import { app } from './app.ts';
import { useConfig } from '@abearxiong/use-config';
import { createAuthRoute } from '@abearxiong/auth';
const config = useConfig<{ tokenSecret: string }>();
createAuthRoute({
app,
secret: config.tokenSecret,
});

View File

@@ -10,6 +10,9 @@ export type ContainerPublish = {
};
export type Container = Partial<InstanceType<typeof ContainerModel>>;
/**
* 用户代码容器
*/
export class ContainerModel extends Model {
declare id: string;
declare title: string;

View File

@@ -7,3 +7,5 @@ import './resource/index.ts';
import './prompt-graph/index.ts';
import './agent/index.ts';
import './user/index.ts';

View File

@@ -18,18 +18,23 @@ type PageNodeData = {
[key: string]: any;
};
export interface PageData {
edges: any[];
nodes: PageNodeData[];
viewport: any;
[key: string]: any;
}
/**
* 页面数据
*/
export class PageModel extends Model {
declare id: string;
declare title: string;
declare description: string;
declare type: string;
declare data: PageData;
declare uid: string;
}
PageModel.init(
{

View File

@@ -28,6 +28,9 @@ export type Resource = {
uid?: string;
};
/**
* 资源管理
*/
export class ResourceModel extends Model {
declare id: string;
declare name: string;

1
src/routes/user/index.ts Normal file
View File

@@ -0,0 +1 @@
import './list.ts'

119
src/routes/user/list.ts Normal file
View File

@@ -0,0 +1,119 @@
import { app } from '@/app.ts';
import { User } from '@/models/user.ts';
import { CustomError } from '@abearxiong/router';
app
.route('user', 'list')
.define(async (ctx) => {
const users = await User.findAll({
attributes: ['id', 'username', 'description', 'needChangePassword'],
order: [['updatedAt', 'DESC']],
logging: false,
});
ctx.body = users;
})
.addTo(app);
app
.route('user', 'login')
.define(async (ctx) => {
const { username, password } = ctx.query;
const user = await User.findOne({ where: { username } });
if (!user) {
new CustomError(401, 'User not found');
}
if (user.password !== password) {
new CustomError(401, 'Password error');
}
const token = await user.createToken();
ctx.body = token;
})
.addTo(app);
app
.route('user', 'auth')
.define(async (ctx) => {
const { checkToken: token } = ctx.query;
try {
const result = await User.verifyToken(token);
ctx.body = result?.payload || {};
} catch (e) {
new CustomError(401, 'Token InValid ');
}
})
.addTo(app);
app
.route('user', 'updateSelf', {
middleware: ['auth'],
})
.define(async (ctx) => {
const { username, password, description } = ctx.query;
const state = ctx.state?.tokenUser || {};
const { id } = state;
const user = await User.findByPk(id);
if (!user) {
throw new CustomError(500, 'user not found');
}
if (username) {
user.username = username;
}
if (password) {
user.createPassword(password);
}
if (description) {
user.description = description;
}
await user.save();
ctx.body = {
id: user.id,
username: user.username,
description: user.description,
needChangePassword: user.needChangePassword,
};
})
.addTo(app);
app
.route('user', 'update', {
middleware: ['auth'],
})
.define(async (ctx) => {
const { id, username, password, description } = ctx.query;
const user = await User.findByPk(id);
if (!user) {
throw new CustomError(500, 'user not found');
}
if (username) {
user.username = username;
}
if (password) {
user.createPassword(password);
}
if (description) {
user.description = description;
}
await user.save();
ctx.body = {
id: user.id,
username: user.username,
description: user.description,
needChangePassword: user.needChangePassword,
};
})
.addTo(app);
app.route('user', 'add').define(async (ctx) => {
const { username, password, description } = ctx.query;
if (!username) {
throw new CustomError(400, 'username is required');
}
const user = await User.createUser(username, password, description);
const token = await user.createToken();
ctx.body = {
id: user.id,
username: user.username,
description: user.description,
needChangePassword: user.needChangePassword,
token,
};
});

35
src/scripts/add-uid.ts Normal file
View File

@@ -0,0 +1,35 @@
import { AiAgent } from '@/models/agent.ts';
import { RouterCodeModel } from '@/models/code.ts';
import { Prompt } from '@/models/prompt.ts';
import { User } from '@/models/user.ts';
import { ContainerModel } from '@/routes/container/models/index.ts';
import { PageModel } from '@/routes/page/models/index.ts';
import { ResourceModel } from '@/routes/resource/models/index.ts';
// declare uid: string;
// uid: {
// type: DataTypes.UUID,
// allowNull: true,
// },
// 系统表
export const stystemTables = [AiAgent, RouterCodeModel, Prompt];
export const userTables = [ContainerModel, PageModel, ResourceModel];
const rootUid = '14206305-8b5c-44cc-b177-766cfe2e452f';
const updateUser = async () => {
const updateTables = [...userTables] as any[];
for (let Table of updateTables) {
// const res = await ContainerModel.update({ uid: rootUid }, { where: { uid: null } });
try {
const list = await Table.update({ uid: rootUid }, { where: { uid: null } });
console.log('update--', list.length);
} catch (e) {
console.log(e);
}
}
};
// updateUser();