feat: user org and fix bugs
This commit is contained in:
98
src/routes/user/org.ts
Normal file
98
src/routes/user/org.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { app, sequelize } from '@/app.ts';
|
||||
import { Org } from '@/models/org.ts';
|
||||
import { User } from '@/models/user.ts';
|
||||
import { CustomError } from '@abearxiong/router';
|
||||
import { Op } from 'sequelize';
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'org',
|
||||
key: 'list',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const tokenUser = ctx.state.tokenUser;
|
||||
const list = await Org.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
where: {
|
||||
users: {
|
||||
[Op.contains]: [
|
||||
{
|
||||
uid: tokenUser.id,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
ctx.body = list;
|
||||
return ctx;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'org',
|
||||
key: 'get',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const id = ctx.query.id;
|
||||
if (!id) {
|
||||
throw new CustomError('id is required');
|
||||
}
|
||||
ctx.body = await Org.findByPk(id);
|
||||
return ctx;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'org',
|
||||
key: 'update',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const tokenUser = ctx.state.tokenUser;
|
||||
const { username, description } = ctx.query.data;
|
||||
if (!username) {
|
||||
throw new CustomError('username is required');
|
||||
}
|
||||
const user = await User.createOrg(username, tokenUser.id, description);
|
||||
ctx.body = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
description: user.description,
|
||||
};
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'org',
|
||||
key: 'delete',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const tokenUser = ctx.state.tokenUser;
|
||||
const id = ctx.query.id;
|
||||
if (!id) {
|
||||
throw new CustomError('id is required');
|
||||
}
|
||||
const org = await Org.findByPk(id);
|
||||
if (!org) {
|
||||
throw new CustomError('org not found');
|
||||
}
|
||||
const username = org.username;
|
||||
const users = org.users;
|
||||
const owner = users.find((u) => u.role === 'owner');
|
||||
if (owner.uid !== tokenUser.id) {
|
||||
throw new CustomError('Permission denied');
|
||||
}
|
||||
await org.destroy({ force: true });
|
||||
const orgUser = await User.findOne({
|
||||
where: { username },
|
||||
});
|
||||
await orgUser.destroy({ force: true });
|
||||
ctx.body = 'success';
|
||||
})
|
||||
.addTo(app);
|
||||
Reference in New Issue
Block a user