Sharkey/packages/backend/src/server/api/endpoints/admin/accounts/create.ts

43 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-09-18 03:27:08 +09:00
import { Inject, Injectable } from '@nestjs/common';
import { IsNull } from 'typeorm';
2022-09-18 03:27:08 +09:00
import { Endpoint } from '@/server/api/endpoint-base.js';
2022-09-21 05:33:11 +09:00
import type { UsersRepository } from '@/models/index.js';
2022-09-18 03:27:08 +09:00
import { SignupService } from '@/core/SignupService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { localUsernameSchema, passwordSchema } from '@/models/entities/User.js';
import { DI } from '@/di-symbols.js';
2022-01-03 02:12:50 +09:00
// eslint-disable-next-line import/no-default-export
2022-09-18 03:27:08 +09:00
@Injectable()
2023-05-22 01:43:00 +00:00
export default class extends Endpoint<'admin/accounts/create'> {
name = 'admin/accounts/create' as const;
2022-09-18 03:27:08 +09:00
constructor(
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private userEntityService: UserEntityService,
private signupService: SignupService,
) {
2023-05-22 01:43:00 +00:00
super(async (ps, _me) => {
2022-09-18 03:27:08 +09:00
const me = _me ? await this.usersRepository.findOneByOrFail({ id: _me.id }) : null;
const noUsers = (await this.usersRepository.countBy({
host: IsNull(),
})) === 0;
if (!noUsers && !me?.isRoot) throw new Error('access denied');
2022-09-18 03:27:08 +09:00
const { account, secret } = await this.signupService.signup({
username: ps.username,
password: ps.password,
ignorePreservedUsernames: true,
2022-09-18 03:27:08 +09:00
});
2023-05-22 01:43:00 +00:00
const res = await this.userEntityService.pack<true, true>(account, account, {
2022-09-18 03:27:08 +09:00
detail: true,
includeSecrets: true,
});
2023-05-22 01:43:00 +00:00
return { ...res, token: secret };
2022-09-18 03:27:08 +09:00
});
}
}