Commit 2d7f04c1 authored by nanahira's avatar nanahira

auth module

parent a27d3224
...@@ -12,4 +12,9 @@ s3: ...@@ -12,4 +12,9 @@ s3:
accessKeyId: zzzz accessKeyId: zzzz
secretAccessKey: tttt secretAccessKey: tttt
bucket: nanahira bucket: nanahira
pathPrefix: test-koishi/ pathPrefix: test-koishi/
\ No newline at end of file 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'; ...@@ -7,6 +7,10 @@ import { Adapter } from 'koishi';
import { AdapterConfig } from './onebot-improved/utils'; import { AdapterConfig } from './onebot-improved/utils';
import { MessageService } from './message/message.service'; import { MessageService } from './message/message.service';
import S3Assets from '@koishijs/plugin-assets-s3'; 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({ @Module({
imports: [ imports: [
...@@ -17,11 +21,10 @@ import S3Assets from '@koishijs/plugin-assets-s3'; ...@@ -17,11 +21,10 @@ import S3Assets from '@koishijs/plugin-assets-s3';
}), }),
KoishiModule.registerAsync({ KoishiModule.registerAsync({
inject: [ConfigService], inject: [ConfigService],
useFactory: async (configService: ConfigService) => { useFactory: (configService: ConfigService) => {
const onebotConfig = const onebotConfig = configService.get<
configService.get<Adapter.PluginConfig<AdapterConfig, BotConfig>>( Adapter.PluginConfig<AdapterConfig, BotConfig>
'onebot', >('onebot');
);
const s3Config = configService.get<S3Assets.Config>('s3'); const s3Config = configService.get<S3Assets.Config>('s3');
return { return {
prefix: '__never_prefix', prefix: '__never_prefix',
...@@ -35,7 +38,22 @@ import S3Assets from '@koishijs/plugin-assets-s3'; ...@@ -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 {} 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 { ...@@ -6,12 +6,16 @@ import {
import { UseEvent, WireContextService } from 'koishi-nestjs'; import { UseEvent, WireContextService } from 'koishi-nestjs';
import { Session } from 'koishi'; import { Session } from 'koishi';
import S3Assets from '@koishijs/plugin-assets-s3'; import S3Assets from '@koishijs/plugin-assets-s3';
import { InjectCenterAccount } from '../utility/constant';
@Injectable() @Injectable()
export class MessageService export class MessageService
extends ConsoleLogger extends ConsoleLogger
implements OnApplicationBootstrap { implements OnApplicationBootstrap {
constructor() { constructor(
@InjectCenterAccount()
private readonly centerAccount: string,
) {
super('message'); super('message');
} }
...@@ -23,6 +27,9 @@ export class MessageService ...@@ -23,6 +27,9 @@ export class MessageService
@UseEvent('message') @UseEvent('message')
async onMessage(session: Session) { async onMessage(session: Session) {
if (session.targetId === this.centerAccount) {
return;
}
let content = session.content; let content = session.content;
if (this.assets) { if (this.assets) {
try { try {
...@@ -34,7 +41,7 @@ export class MessageService ...@@ -34,7 +41,7 @@ export class MessageService
} }
// targetId, for private messages only // targetId, for private messages only
const fromId = session.userId; const fromId = session.userId;
const targetId = session.targetId || session.selfId; const targetId = session.targetId || session.guildId;
this.log( this.log(
`Received message from ${session.username}(${fromId}) to ${targetId}: ${content}`, `Received message from ${session.username}(${fromId}) to ${targetId}: ${content}`,
); );
......
...@@ -4,18 +4,28 @@ import { Adapter } from 'koishi'; ...@@ -4,18 +4,28 @@ import { Adapter } from 'koishi';
import S3Assets from '@koishijs/plugin-assets-s3'; import S3Assets from '@koishijs/plugin-assets-s3';
import { AdapterConfig } from '../onebot-improved/utils'; import { AdapterConfig } from '../onebot-improved/utils';
import { BotConfig } from '../onebot-improved'; import { BotConfig } from '../onebot-improved';
import { JwtModuleOptions } from '@nestjs/jwt';
export interface Config { export interface Config {
host: string; host: string;
port: number; port: number;
onebot: Adapter.PluginConfig<AdapterConfig, BotConfig>; onebot: Adapter.PluginConfig<AdapterConfig, BotConfig>;
s3?: S3Assets.Config; s3?: S3Assets.Config;
jwt: JwtModuleOptions;
centerAccount: string;
} }
const defaultConfig: Config = { const defaultConfig: Config = {
host: '::', host: '::',
port: 3000, port: 3000,
onebot: { bots: [] }, onebot: { bots: [] },
jwt: {
secretOrPrivateKey: 'secret',
signOptions: {
expiresIn: '1d',
},
},
centerAccount: '1111111111',
}; };
export async function loadConfig(): Promise<Config> { 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