Commit 2d7f04c1 authored by nanahira's avatar nanahira

auth module

parent a27d3224
......@@ -13,3 +13,8 @@ s3:
secretAccessKey: tttt
bucket: nanahira
pathPrefix: test-koishi/
jwt:
secretOrPrivateKey: 'secret'
signOptions:
expiresIn: '1d'
centerAccount: '1111111111'
\ No newline at end of file
This diff is collapsed.
......@@ -7,6 +7,10 @@ import { Adapter } from 'koishi';
import { AdapterConfig } from './onebot-improved/utils';
import { MessageService } from './message/message.service';
import S3Assets from '@koishijs/plugin-assets-s3';
import { JwtModule, JwtModuleOptions } from '@nestjs/jwt';
import { AuthService } from './auth/auth.service';
import { BotService } from './bot/bot.service';
import { CENTER_ACCOUNT_TOKEN } from './utility/constant';
@Module({
imports: [
......@@ -17,11 +21,10 @@ import S3Assets from '@koishijs/plugin-assets-s3';
}),
KoishiModule.registerAsync({
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const onebotConfig =
configService.get<Adapter.PluginConfig<AdapterConfig, BotConfig>>(
'onebot',
);
useFactory: (configService: ConfigService) => {
const onebotConfig = configService.get<
Adapter.PluginConfig<AdapterConfig, BotConfig>
>('onebot');
const s3Config = configService.get<S3Assets.Config>('s3');
return {
prefix: '__never_prefix',
......@@ -35,7 +38,22 @@ import S3Assets from '@koishijs/plugin-assets-s3';
};
},
}),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) =>
configService.get<JwtModuleOptions>('jwt'),
}),
],
providers: [
MessageService,
AuthService,
BotService,
{
provide: CENTER_ACCOUNT_TOKEN,
inject: [ConfigService],
useFactory: (configService: ConfigService) =>
configService.get<string>('centerAccount'),
},
],
providers: [MessageService],
})
export class AppModule {}
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { ConsoleLogger, Injectable } from '@nestjs/common';
import { BotService } from '../bot/bot.service';
import { JwtService } from '@nestjs/jwt';
import { BlankReturnMessageDto } from '../dto/ReturnMessage.dto';
import { InjectCenterAccount } from '../utility/constant';
@Injectable()
export class AuthService extends ConsoleLogger {
constructor(
private readonly botService: BotService,
private readonly jwt: JwtService,
@InjectCenterAccount()
private readonly centerAccount: string,
) {
super('AuthService');
}
async sendCode(selfId: string) {
const bot = this.botService.getBot(selfId);
if (!bot) {
throw new BlankReturnMessageDto(404, 'Bot not found').toException();
}
try {
const code = await this.jwt.signAsync({ sub: selfId });
await bot.sendPrivateMessage(this.centerAccount, `您的密钥是:\n${code}`);
} catch (e) {
this.error(`sendCode error for ${selfId}: ${e.message}`);
throw new BlankReturnMessageDto(500, 'Send message failed').toException();
}
}
async verify(token: string) {
try {
const { sub } = await this.jwt.verifyAsync<{ sub: string }>(token);
return sub;
} catch (e) {
throw new BlankReturnMessageDto(403, 'Invalid token').toException();
}
}
}
import { Test, TestingModule } from '@nestjs/testing';
import { BotService } from './bot.service';
describe('BotService', () => {
let service: BotService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [BotService],
}).compile();
service = module.get<BotService>(BotService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { Injectable } from '@nestjs/common';
import { WireContextService } from 'koishi-nestjs';
import { Bot } from 'koishi';
@Injectable()
export class BotService {
@WireContextService()
private bots: Bot[];
private botMap = new Map<string, Bot>();
getBot(id: string): Bot {
if (this.botMap.has(id)) {
return this.botMap.get(id);
}
const bot = this.bots.find((bot) => bot.selfId === id);
if (!bot) {
return;
}
this.botMap.set(id, bot);
return bot;
}
}
......@@ -6,12 +6,16 @@ import {
import { UseEvent, WireContextService } from 'koishi-nestjs';
import { Session } from 'koishi';
import S3Assets from '@koishijs/plugin-assets-s3';
import { InjectCenterAccount } from '../utility/constant';
@Injectable()
export class MessageService
extends ConsoleLogger
implements OnApplicationBootstrap {
constructor() {
constructor(
@InjectCenterAccount()
private readonly centerAccount: string,
) {
super('message');
}
......@@ -23,6 +27,9 @@ export class MessageService
@UseEvent('message')
async onMessage(session: Session) {
if (session.targetId === this.centerAccount) {
return;
}
let content = session.content;
if (this.assets) {
try {
......@@ -34,7 +41,7 @@ export class MessageService
}
// targetId, for private messages only
const fromId = session.userId;
const targetId = session.targetId || session.selfId;
const targetId = session.targetId || session.guildId;
this.log(
`Received message from ${session.username}(${fromId}) to ${targetId}: ${content}`,
);
......
......@@ -4,18 +4,28 @@ import { Adapter } from 'koishi';
import S3Assets from '@koishijs/plugin-assets-s3';
import { AdapterConfig } from '../onebot-improved/utils';
import { BotConfig } from '../onebot-improved';
import { JwtModuleOptions } from '@nestjs/jwt';
export interface Config {
host: string;
port: number;
onebot: Adapter.PluginConfig<AdapterConfig, BotConfig>;
s3?: S3Assets.Config;
jwt: JwtModuleOptions;
centerAccount: string;
}
const defaultConfig: Config = {
host: '::',
port: 3000,
onebot: { bots: [] },
jwt: {
secretOrPrivateKey: 'secret',
signOptions: {
expiresIn: '1d',
},
},
centerAccount: '1111111111',
};
export async function loadConfig(): Promise<Config> {
......
import { Inject } from '@nestjs/common';
export const CENTER_ACCOUNT_TOKEN = 'center_account_token';
export const InjectCenterAccount = () => Inject(CENTER_ACCOUNT_TOKEN);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment