"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),utils_1=require("../utils"),utils_2=require("./utils"),db_1=require("@b/db");exports.metadata={summary:"Verifies the OTP or recovery code for login",operationId:"verifyLoginOTP",tags:["Auth"],description:"Verifies the OTP for login and returns a session token. If the OTP is invalid, the provided code is checked against the recovery codes.",requiresAuth:!1,logModule:"2FA",logTitle:"2FA login verification",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",format:"uuid",description:"ID of the user"},otp:{type:"string",description:"OTP or recovery code to verify"}},required:["id","otp"]}}}},responses:{200:{description:"OTP or recovery code verified successfully, user logged in",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Success message"}}}}}},400:{description:"Invalid request"},401:{description:"Unauthorized"}}};exports.default=async e=>{const{body:t,ctx:r}=e,{id:i,otp:s}=t;try{null==r||r.step("Validating 2FA login request");(0,utils_2.validateOtpRequest)(i,s);null==r||r.step("Looking up user with 2FA");const e=await(0,utils_2.getUserWith2FA)(i);let t=e.twoFactor.secret,o=!1;null==r||r.step("Checking secret encryption");if((0,utils_2.isEncrypted)(t))try{t=(0,utils_2.decrypt)(t)}catch(e){null==r||r.fail("Failed to decrypt 2FA secret");throw(0,error_1.createError)({statusCode:500,message:"Could not decrypt 2FA secret. User data may be corrupted."})}else{o=!0;null==r||r.step("Secret is in plaintext, will re-encrypt after verification","warn")}null==r||r.step("Verifying OTP code");if((0,utils_2.verifyOtp)(t,s)){if(o){null==r||r.step("Re-encrypting plaintext secret");const t=(0,utils_2.encrypt)(e.twoFactor.secret);await db_1.models.twoFactor.update({secret:t},{where:{id:e.twoFactor.id}})}}else{null==r||r.step("OTP verification failed, checking recovery codes");await(0,utils_2.consumeRecoveryCode)(e.twoFactor,s);null==r||r.step("Recovery code consumed successfully")}null==r||r.step("Generating session tokens");const c=await(0,utils_1.returnUserWithTokens)({user:e,message:"You have been logged in successfully"});null==r||r.success(`User ${e.email} logged in with 2FA`);return c}catch(e){null==r||r.fail(e.message||"2FA login failed");throw e}};