Преглед изворни кода

Bugfix: Simplify login and startMailVerify functions, improve error handling and validation

BedirhanOZCAN пре 1 месец
родитељ
комит
76e40e9694

+ 1 - 22
src/actions/auth/login/index.ts

@@ -1,34 +1,13 @@
 import jwt from "jsonwebtoken";
 import jwt from "jsonwebtoken";
-import {
-    plainToInstance
-} from "class-transformer";
-import {
-    validate
-} from "class-validator";
 import {
 import {
     User
     User
 } from "../../../models/User";
 } from "../../../models/User";
 import {
 import {
-    LoginResult,
-    LoginInput
+    LoginResult, LoginInput
 } from "./types";
 } from "./types";
 import redis from "../../../config/redis";
 import redis from "../../../config/redis";
-import {
-    formatValidationErrors
-} from "../../../utils";
 
 
 const login = async (input: LoginInput): Promise<LoginResult> => {
 const login = async (input: LoginInput): Promise<LoginResult> => {
-    const dto = plainToInstance(LoginInput, input);
-    const errors = await validate(dto);
-
-    if (errors.length > 0) {
-        const formattedErrors = formatValidationErrors(errors);
-        return {
-            code: 400,
-            message: formattedErrors[0],
-        };
-    }
-
     const {
     const {
         password,
         password,
         mail
         mail

+ 2 - 11
src/actions/auth/startMailVerify/index.ts

@@ -3,12 +3,10 @@ import {
 } from "../../../models/User";
 } from "../../../models/User";
 import redis from "../../../config/redis";
 import redis from "../../../config/redis";
 import {
 import {
-    StartMailVerifyResult,
-    StartMailVerifyInput
+    StartMailVerifyResult, StartMailVerifyInput
 } from "./types";
 } from "./types";
 import {
 import {
-    verificationCode,
-    TTL_SECONDS
+    verificationCode, TTL_SECONDS
 } from "../../../utils";
 } from "../../../utils";
 // import { sendMail } from "../../../utils/mailer"; // mail gönderme fonskiyonu bu şekilde ilerde import edilecek.
 // import { sendMail } from "../../../utils/mailer"; // mail gönderme fonskiyonu bu şekilde ilerde import edilecek.
 
 
@@ -18,13 +16,6 @@ const startMailVerify = async (input: StartMailVerifyInput): Promise<StartMailVe
             userID
             userID
         } = input;
         } = input;
 
 
-        if (!userID) {
-            return {
-                message: "userID-required",
-                code: 400,
-            };
-        }
-
         const user = await User.findById(userID);
         const user = await User.findById(userID);
         if (!user) {
         if (!user) {
             return {
             return {

+ 8 - 2
src/actions/auth/startMailVerify/types.ts

@@ -1,5 +1,11 @@
-export interface StartMailVerifyInput {
-    userID: string;
+import {
+    IsNotEmpty, IsString
+} from "class-validator";
+
+export class StartMailVerifyInput {
+    @IsString({ message: "userID must be a string" })
+    @IsNotEmpty({ message: "userID is required" })
+    userID!: string;
 }
 }
 
 
 export interface StartMailVerifyResult {
 export interface StartMailVerifyResult {

+ 26 - 23
src/controllers/authController.ts

@@ -17,7 +17,7 @@ import {
 
 
 export const register = async (req: Request, res: Response): Promise<void> => {
 export const register = async (req: Request, res: Response): Promise<void> => {
     const result = await _register(req.body);
     const result = await _register(req.body);
-    
+
     res.status(result.code)
     res.status(result.code)
         .json({
         .json({
             message: result.message,
             message: result.message,
@@ -27,15 +27,7 @@ export const register = async (req: Request, res: Response): Promise<void> => {
 
 
 export const login = async (req: Request, res: Response): Promise<void> => {
 export const login = async (req: Request, res: Response): Promise<void> => {
     try {
     try {
-        const {
-            password,
-            mail
-        } = req.body;
-
-        const result = await _login({
-            password,
-            mail
-        });
+        const result = await _login(req.body);
 
 
         res.status(result.code).json({
         res.status(result.code).json({
             message: result.message,
             message: result.message,
@@ -46,12 +38,11 @@ export const login = async (req: Request, res: Response): Promise<void> => {
         });
         });
 
 
     } catch (error) {
     } catch (error) {
-        console.error("Login error:", error);
-        res.status(500)
-            .json({
-                message: "server-error",
-                code: 500,
-            });
+        console.error("Login controller error:", error);
+        res.status(500).json({
+            message: "server-error",
+            code: 500,
+        });
     }
     }
 };
 };
 
 
@@ -104,15 +95,27 @@ export const refreshToken = async (req: Request, res: Response): Promise<void> =
         });
         });
 };
 };
 
 
-export const startMailVerify = async (req: Request, res: Response): Promise<void> => {
+export const validateToken = async (req: AuthRequest, res: Response): Promise<void> => {
     try {
     try {
-        const {
-            userID
-        } = req.body;
-
-        const result = await _startMailVerify({
-            userID
+        res.status(200).json({
+            message: "token-valid",
+            code: 200,
+            payload: {
+                user: req.context
+            }
+        });
+    } catch (error) {
+        console.error("Validate token error:", error);
+        res.status(500).json({
+            message: "server-error",
+            code: 500
         });
         });
+    }
+};
+
+export const startMailVerify = async (req: Request, res: Response): Promise<void> => {
+    try {
+        const result = await _startMailVerify(req.body);
 
 
         res.status(result.code).json({
         res.status(result.code).json({
             message: result.message,
             message: result.message,

+ 6 - 12
src/routes/authRoutes.ts

@@ -4,6 +4,7 @@ import {
 import {
 import {
     finishMailVerify,
     finishMailVerify,
     startMailVerify,
     startMailVerify,
+    validateToken,
     refreshToken,
     refreshToken,
     register,
     register,
     logout,
     logout,
@@ -12,13 +13,13 @@ import {
 } from "../controllers/authController";
 } from "../controllers/authController";
 import {
 import {
     authMiddleware,
     authMiddleware,
-    AuthRequest
 } from "../middlewares/authMiddleware";
 } from "../middlewares/authMiddleware";
 import {
 import {
-    validateBody 
+    validateBody
 } from "../middlewares/validateBody";
 } from "../middlewares/validateBody";
 import {
 import {
     FinishMailVerifyInput,
     FinishMailVerifyInput,
+    StartMailVerifyInput,
     RefreshTokenInput,
     RefreshTokenInput,
     RegisterInput,
     RegisterInput,
     LoginInput
     LoginInput
@@ -27,20 +28,13 @@ import {
 const router = Router();
 const router = Router();
 
 
 router.post("/finish-mail-verify", validateBody(FinishMailVerifyInput), finishMailVerify);
 router.post("/finish-mail-verify", validateBody(FinishMailVerifyInput), finishMailVerify);
+router.post("/start-mail-verify", validateBody(StartMailVerifyInput), startMailVerify);
 router.post("/refresh-token", validateBody(RefreshTokenInput), refreshToken);
 router.post("/refresh-token", validateBody(RefreshTokenInput), refreshToken);
 router.post("/register", validateBody(RegisterInput), register);
 router.post("/register", validateBody(RegisterInput), register);
 router.post("/login", validateBody(LoginInput), login);
 router.post("/login", validateBody(LoginInput), login);
-router.post("/start-mail-verify", startMailVerify);
 router.post("/logout", authMiddleware, logout);
 router.post("/logout", authMiddleware, logout);
-router.get("/me", authMiddleware, me);
 
 
-router.get("/validate-token", authMiddleware, (req: AuthRequest, res) => {
-    res.status(200)
-        .json({
-            message: "token-valid",
-            context: req.context,
-            code: 200
-        });
-});
+router.get("/validate-token", authMiddleware, validateToken);
+router.get("/me", authMiddleware, me);
 
 
 export default router;
 export default router;