This commit is contained in:
xion 2025-03-30 20:02:00 +08:00
parent 60c5a986ed
commit 162d4c72b4
6 changed files with 97 additions and 22 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@kevisual/code-center-module", "name": "@kevisual/code-center-module",
"version": "0.0.16", "version": "0.0.17",
"description": "", "description": "",
"main": "dist/system.mjs", "main": "dist/system.mjs",
"module": "dist/system.mjs", "module": "dist/system.mjs",

View File

@ -4,7 +4,9 @@
import { UserServices, User, UserInit, UserModel } from './models/user.ts'; import { UserServices, User, UserInit, UserModel } from './models/user.ts';
import { Org, OrgInit, OrgModel } from './models/org.ts'; import { Org, OrgInit, OrgModel } from './models/org.ts';
import { addAuth } from './middleware/auth.ts'; import { addAuth } from './middleware/auth.ts';
import { checkAuth, getLoginUser } from './middleware/auth-manual.ts';
export { User, Org, UserServices, UserInit, OrgInit, UserModel, OrgModel }; export { User, Org, UserServices, UserInit, OrgInit, UserModel, OrgModel };
/** /**
* user成功, * user成功,
*/ */
@ -13,4 +15,5 @@ export const authCan = 'auth-can';
* user成功 * user成功
*/ */
export const auth = 'auth'; export const auth = 'auth';
export { addAuth };
export { addAuth, checkAuth, getLoginUser };

View File

@ -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 });
};
/**
* tokentoken不存在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;
}
};

View File

@ -1,9 +1,15 @@
import { Redis } from 'ioredis'; import { Redis } from 'ioredis';
import { useConfig } from '@kevisual/use-config'; import { useConfig } from '@kevisual/use-config/env';
import { useContextKey } from '@kevisual/use-config/context'; import { useContextKey } from '@kevisual/use-config/context';
const config = useConfig<{ const configEnv = useConfig();
redis: ConstructorParameters<typeof Redis>;
}>(); 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 连接 // 配置 Redis 连接
export const redis = new Redis({ export const redis = new Redis({
host: 'localhost', // Redis 服务器的主机名或 IP 地址 host: 'localhost', // Redis 服务器的主机名或 IP 地址
@ -16,7 +22,6 @@ export const redis = new Redis({
return Math.min(times * 50, 2000); // 每次重试时延迟增加 return Math.min(times * 50, 2000); // 每次重试时延迟增加
}, },
maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试) maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试)
...config.redis,
}); });
useContextKey('redis', () => redis); useContextKey('redis', () => redis);
// 监听连接事件 // 监听连接事件

View File

@ -1,19 +1,16 @@
import { useConfig } from '@kevisual/use-config'; import { useConfig } from '@kevisual/use-config/env';
import { Sequelize } from 'sequelize'; import { Sequelize } from 'sequelize';
import { useContextKey, useContext } from '@kevisual/use-config/context'; import { useContextKey } from '@kevisual/use-config/context';
type PostgresConfig = { const configEnv = useConfig();
postgres: {
username: string;
password: string;
host: string;
port: number;
database: string;
};
};
const config = useConfig<PostgresConfig>();
const postgresConfig = config.postgres; 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,
};
if (!postgresConfig) { if (!postgresConfig) {
console.error('postgres config is required'); console.error('postgres config is required');

View File

@ -1,7 +1,6 @@
/** /**
* redis和sequelize的初始化放到库当中 * redis和sequelize的初始化放到库当中
*/ */
import { useConfig } from '@kevisual/use-config';
import { app } from './app.ts'; import { app } from './app.ts';
import * as sequelizeLib from './modules/sequelize.ts'; import * as sequelizeLib from './modules/sequelize.ts';
export const sequelize = useContextKey('sequelize', () => sequelizeLib.sequelize); 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 * as redisLib from './modules/redis.ts';
import { useContextKey } from '@kevisual/use-config/context'; import { useContextKey } from '@kevisual/use-config/context';
useConfig();
export const redis = useContextKey('redis', () => redisLib.redis); export const redis = useContextKey('redis', () => redisLib.redis);
export const redisPublisher = useContextKey('redisPublisher', () => redisLib.redisPublisher); export const redisPublisher = useContextKey('redisPublisher', () => redisLib.redisPublisher);