Explorar el Código

Refactor registration configuration handling to prioritize environment variable; streamline registration checks in AuthService and update endpoint response.

Ethanfly hace 10 horas
padre
commit
6d9a0c28c7
Se han modificado 2 ficheros con 19 adiciones y 15 borrados
  1. 4 11
      server/src/routes/auth.ts
  2. 15 4
      server/src/services/AuthService.ts

+ 4 - 11
server/src/routes/auth.ts

@@ -9,11 +9,13 @@ const router = Router();
 const authService = new AuthService();
 
 // 获取注册配置(公开接口)
-router.get('/config', (req, res) => {
+router.get('/config', (_req, res) => {
+  // 环境变量优先,必须明确设置为 'true' 才开放注册
+  const allowRegistration = process.env.ALLOW_REGISTRATION === 'true';
   res.json({
     success: true,
     data: {
-      allowRegistration: process.env.ALLOW_REGISTRATION !== 'false',
+      allowRegistration,
     },
   });
 });
@@ -54,15 +56,6 @@ router.post(
     validateRequest,
   ],
   asyncHandler(async (req, res) => {
-    // 检查是否开放注册
-    const allowRegistration = process.env.ALLOW_REGISTRATION !== 'false';
-    if (!allowRegistration) {
-      return res.status(403).json({
-        success: false,
-        message: '注册功能已关闭,请联系管理员',
-      });
-    }
-    
     const { username, password, email, nickname } = req.body;
     
     const result = await authService.register({ username, password, email, nickname });

+ 15 - 4
server/src/services/AuthService.ts

@@ -87,11 +87,22 @@ export class AuthService {
    */
   async register(data: RegisterRequest) {
     // 检查是否开放注册
-    const allowRegistration = await this.configRepository.findOne({
-      where: { configKey: 'allow_registration' },
-    });
+    // 优先使用环境变量,如果没有设置则从数据库读取
+    let isRegistrationAllowed = false;
+    
+    const envValue = process.env.ALLOW_REGISTRATION;
+    if (envValue !== undefined) {
+      // 环境变量已设置,使用环境变量的值
+      isRegistrationAllowed = envValue === 'true';
+    } else {
+      // 环境变量未设置,从数据库读取
+      const dbConfig = await this.configRepository.findOne({
+        where: { configKey: 'allow_registration' },
+      });
+      isRegistrationAllowed = dbConfig?.configValue === 'true';
+    }
 
-    if (allowRegistration?.configValue !== 'true') {
+    if (!isRegistrationAllowed) {
       throw new AppError('注册功能已关闭', HTTP_STATUS.FORBIDDEN, ERROR_CODES.REGISTRATION_DISABLED);
     }