Skip to content

Commit

Permalink
feat: jwt 密钥持久化存数据库
Browse files Browse the repository at this point in the history
  • Loading branch information
Mereithhh committed Mar 17, 2023
1 parent 4444d54 commit 6440732
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 27 deletions.
1 change: 1 addition & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"markdown-it": "^13.0.1",
"markdown-it-katex": "^2.0.3",
"markdown-it-task-lists": "^2.1.1",
"mongodb": "^5.1.0",
"mongoose": "^7.0.1",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
Expand Down
15 changes: 10 additions & 5 deletions packages/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ import { Pipeline, PipelineSchema } from './scheme/pipeline.schema';
import { PipelineProvider } from './provider/pipeline/pipeline.provider';
import { PipelineController } from './controller/admin/pipeline/pipeline.controller';
import { TokenController } from './controller/admin/token/token.controller';
import { initJwt } from './utils/initJwt';

@Module({
imports: [
Expand All @@ -106,11 +107,15 @@ import { TokenController } from './controller/admin/token/token.controller';
{ name: Category.name, schema: CategorySchema },
{ name: Pipeline.name, schema: PipelineSchema },
]),
JwtModule.register({
secret: config.jwtSecret,
signOptions: {
expiresIn: 3600 * 24 * 7,
},
JwtModule.registerAsync({
useFactory: async () => {
return {
secret: await initJwt(),
signOptions: {
expiresIn: 3600 * 24 * 7,
},
};
}
}),
ScheduleModule.forRoot(),
],
Expand Down
13 changes: 7 additions & 6 deletions packages/server/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { makeSalt } from 'src/utils/crypto';
import { loadConfig } from 'src/utils/loadConfig';

export interface Config {
mongoUrl: string;
jwtSecret: string;
staticPath: string;
codeRunnerPath: string;
pluginRunnerPath: string;
Expand All @@ -12,8 +10,8 @@ export interface Config {
log: string;
}

export const config: Config = {
mongoUrl: loadConfig('database.url', () => {
export const loadMongoUrl = () => {
return loadConfig('database.url', () => {
const db = {
host: loadConfig('database.host', 'mongo'),
port: loadConfig('database.port', '27017'),
Expand All @@ -28,8 +26,11 @@ export const config: Config = {
authInfo = `${db.user}:${db.passwd}@`;

return `mongodb://${authInfo}${db.host}:${db.port}/${db.name}?authSource=admin`;
}),
jwtSecret: makeSalt(),
})
}

export const config: Config = {
mongoUrl: loadMongoUrl(),
staticPath: loadConfig('static.path', '/app/static'),
demo: loadConfig('demo', false),
walineDB: loadConfig('waline.db', 'waline'),
Expand Down
5 changes: 5 additions & 0 deletions packages/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ import { json } from 'express';
import { UserProvider } from './provider/user/user.provider';
import { SettingProvider } from './provider/setting/setting.provider';
import { WebsiteProvider } from './provider/website/website.provider';
import { initJwt } from './utils/initJwt';

async function bootstrap() {
const jwtSecret = await initJwt();
global.jwtSecret = jwtSecret;


const app = await NestFactory.create<NestExpressApplication>(AppModule);

app.use(json({ limit: '50mb' }));
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/provider/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { config } from 'src/config/index';
import { MetaProvider } from '../meta/meta.provider';
import { UserProvider } from '../user/user.provider';

Expand All @@ -14,7 +13,8 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
super({
// 获取请求header token值
jwtFromRequest: ExtractJwt.fromHeader('token'),
secretOrKey: config.jwtSecret,
// 从 initJwtSecret 获取 jwt 密钥
secretOrKey : global.jwtSecret,
});
}

Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/provider/waline/waline.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export class WalineProvider {
const otherEnv = {
SITE_NAME: siteInfo?.siteName || undefined,
SITE_URL: siteInfo?.baseUrl || undefined,
JWT_TOKEN: config.jwtSecret || makeSalt(),
JWT_TOKEN: global.jwtSecret || makeSalt(),
};
const walineConfig = await this.settingProvider.getWalineSetting();
const walineConfigEnv = this.mapConfig2Env(walineConfig);
Expand Down
18 changes: 18 additions & 0 deletions packages/server/src/utils/initJwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { loadMongoUrl } from "src/config"
import { MongoClient } from "mongodb";
import { makeSalt } from "./crypto";
export const initJwt = async () => {
const mongoUrl = await loadMongoUrl();
const client = new MongoClient(mongoUrl);
await client.connect();
const db = client.db();
const collection = db.collection("settings");
const jwtSetting = await collection.findOne({ type: "jwt" });
if (jwtSetting) {
return jwtSetting.value.secret;
}else {
const secret = makeSalt();
await collection.insertOne({ type: "jwt", value: { secret } });
return secret;
}
}
18 changes: 5 additions & 13 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6440732

Please sign in to comment.