From 162d4c72b409530c6789ea8b3efcc7963715bed8 Mon Sep 17 00:00:00 2001 From: xion Date: Sun, 30 Mar 2025 20:02:00 +0800 Subject: [PATCH] temp --- package.json | 2 +- src/core-models.ts | 5 ++- src/middleware/auth-manual.ts | 72 +++++++++++++++++++++++++++++++++++ src/modules/redis.ts | 15 +++++--- src/modules/sequelize.ts | 23 +++++------ src/system.ts | 2 - 6 files changed, 97 insertions(+), 22 deletions(-) create mode 100644 src/middleware/auth-manual.ts diff --git a/package.json b/package.json index 81e5f87..5568c26 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/code-center-module", - "version": "0.0.16", + "version": "0.0.17", "description": "", "main": "dist/system.mjs", "module": "dist/system.mjs", diff --git a/src/core-models.ts b/src/core-models.ts index 9697d1c..58ae4ec 100644 --- a/src/core-models.ts +++ b/src/core-models.ts @@ -4,7 +4,9 @@ import { UserServices, User, UserInit, UserModel } from './models/user.ts'; import { Org, OrgInit, OrgModel } from './models/org.ts'; import { addAuth } from './middleware/auth.ts'; +import { checkAuth, getLoginUser } from './middleware/auth-manual.ts'; export { User, Org, UserServices, UserInit, OrgInit, UserModel, OrgModel }; + /** * 可以不需要user成功, 有则赋值,交给下一个中间件 */ @@ -13,4 +15,5 @@ export const authCan = 'auth-can'; * 必须需要user成功 */ export const auth = 'auth'; -export { addAuth }; + +export { addAuth, checkAuth, getLoginUser }; diff --git a/src/middleware/auth-manual.ts b/src/middleware/auth-manual.ts new file mode 100644 index 0000000..9c3c54c --- /dev/null +++ b/src/middleware/auth-manual.ts @@ -0,0 +1,72 @@ +import { User } from '../models/user.ts'; +import http from 'http'; +import cookie from 'cookie'; +export const error = (msg: string, code = 500) => { + return JSON.stringify({ code, message: msg }); +}; +/** + * 手动验证token,如果token不存在,则返回401 + * @param req + * @param res + * @returns + */ +export const checkAuth = async (req: http.IncomingMessage, res: http.ServerResponse) => { + let token = (req.headers?.['authorization'] as string) || (req.headers?.['Authorization'] as string) || ''; + const url = new URL(req.url || '', 'http://localhost'); + const resNoPermission = () => { + res.statusCode = 401; + res.end(error('Invalid authorization')); + return { tokenUser: null, token: null }; + }; + if (!token) { + token = url.searchParams.get('token') || ''; + } + if (!token) { + const parsedCookies = cookie.parse(req.headers.cookie || ''); + token = parsedCookies.token || ''; + } + if (!token) { + return resNoPermission(); + } + if (token) { + token = token.replace('Bearer ', ''); + } + let tokenUser; + try { + tokenUser = await User.verifyToken(token); + } catch (e) { + console.log('checkAuth error', e); + res.statusCode = 401; + res.end(error('Invalid token')); + return { tokenUser: null, token: null }; + } + return { tokenUser, token }; +}; + +/** + * 获取登录用户,有则获取,无则返回null + * @param req + * @returns + */ +export const getLoginUser = async (req: http.IncomingMessage) => { + let token = (req.headers?.['authorization'] as string) || (req.headers?.['Authorization'] as string) || ''; + const url = new URL(req.url || '', 'http://localhost'); + if (!token) { + token = url.searchParams.get('token') || ''; + } + if (!token) { + const parsedCookies = cookie.parse(req.headers.cookie || ''); + token = parsedCookies.token || ''; + } + + if (token) { + token = token.replace('Bearer ', ''); + } + let tokenUser; + try { + tokenUser = await User.verifyToken(token); + return { tokenUser, token }; + } catch (e) { + return null; + } +}; diff --git a/src/modules/redis.ts b/src/modules/redis.ts index 5d04b4b..424c356 100644 --- a/src/modules/redis.ts +++ b/src/modules/redis.ts @@ -1,9 +1,15 @@ import { Redis } from 'ioredis'; -import { useConfig } from '@kevisual/use-config'; +import { useConfig } from '@kevisual/use-config/env'; import { useContextKey } from '@kevisual/use-config/context'; -const config = useConfig<{ - redis: ConstructorParameters; -}>(); +const configEnv = useConfig(); + +const redisConfig = { + host: configEnv.REDIS_HOST || 'localhost', + port: configEnv.REDIS_PORT ? parseInt(configEnv.REDIS_PORT) : 6379, + password: configEnv.REDIS_PASSWORD || undefined, + db: configEnv.REDIS_DB ? parseInt(configEnv.REDIS_DB) : 0, +}; + // 配置 Redis 连接 export const redis = new Redis({ host: 'localhost', // Redis 服务器的主机名或 IP 地址 @@ -16,7 +22,6 @@ export const redis = new Redis({ return Math.min(times * 50, 2000); // 每次重试时延迟增加 }, maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试) - ...config.redis, }); useContextKey('redis', () => redis); // 监听连接事件 diff --git a/src/modules/sequelize.ts b/src/modules/sequelize.ts index 97c3a99..60da5be 100644 --- a/src/modules/sequelize.ts +++ b/src/modules/sequelize.ts @@ -1,19 +1,16 @@ -import { useConfig } from '@kevisual/use-config'; +import { useConfig } from '@kevisual/use-config/env'; import { Sequelize } from 'sequelize'; -import { useContextKey, useContext } from '@kevisual/use-config/context'; +import { useContextKey } from '@kevisual/use-config/context'; -type PostgresConfig = { - postgres: { - username: string; - password: string; - host: string; - port: number; - database: string; - }; +const configEnv = useConfig(); + +const postgresConfig = { + username: configEnv.POSTGRES_USERNAME, + password: configEnv.POSTGRES_PASSWORD, + host: configEnv.POSTGRES_HOST, + port: configEnv.POSTGRES_PORT ? parseInt(configEnv.POSTGRES_PORT) : 5432, + database: configEnv.POSTGRES_DATABASE, }; -const config = useConfig(); - -const postgresConfig = config.postgres; if (!postgresConfig) { console.error('postgres config is required'); diff --git a/src/system.ts b/src/system.ts index bb864b6..9bd75b8 100644 --- a/src/system.ts +++ b/src/system.ts @@ -1,7 +1,6 @@ /** * 直接开发业务代码,把redis和sequelize的初始化放到库当中。 */ -import { useConfig } from '@kevisual/use-config'; import { app } from './app.ts'; import * as sequelizeLib from './modules/sequelize.ts'; export const sequelize = useContextKey('sequelize', () => sequelizeLib.sequelize); @@ -11,7 +10,6 @@ import { Org, OrgInit, OrgModel } from './models/org.ts'; import * as redisLib from './modules/redis.ts'; import { useContextKey } from '@kevisual/use-config/context'; -useConfig(); export const redis = useContextKey('redis', () => redisLib.redis); export const redisPublisher = useContextKey('redisPublisher', () => redisLib.redisPublisher);