From efcad4996d235acbf0f7fc5b8beb491ab9e8c639 Mon Sep 17 00:00:00 2001 From: Debanjum Singh Solanky Date: Thu, 25 Jul 2024 18:19:58 +0530 Subject: [PATCH] Add phone number verification for Whatsapp to new settings page --- src/interface/web/app/settings/page.tsx | 49 +++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/interface/web/app/settings/page.tsx b/src/interface/web/app/settings/page.tsx index e249a77a..641e1410 100644 --- a/src/interface/web/app/settings/page.tsx +++ b/src/interface/web/app/settings/page.tsx @@ -180,7 +180,6 @@ export default function SettingsView() { const [userConfig, setUserConfig] = useState(null); const [number, setNumber] = useState(undefined); const [otp, setOTP] = useState(""); - const [isValidNumber, setIsValidNumber] = useState(false); const [numberValidationState, setNumberValidationState] = useState(PhoneNumberValidationState.Verified); const { toast } = useToast(); const cardClassName = "w-1/3 grid grid-flow-column border border-gray-300 shadow-md rounded-lg"; @@ -204,6 +203,50 @@ export default function SettingsView() { return () => window.removeEventListener('resize', handleResize); }, []); + const sendOTP = async () => { + try { + const response = await fetch(`/api/phone?phone_number=${number}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }); + if (!response.ok) throw new Error('Failed to send OTP'); + + setNumberValidationState(PhoneNumberValidationState.VerifyOTP); + } catch (error) { + console.error('Error sending OTP:', error); + toast({ + title: "📱 Phone", + description: "Failed to send OTP. Try again or contact us at team@khoj.dev", + }); + } + }; + + const verifyOTP = async () => { + try { + const response = await fetch(`/api/phone/verify?code=${otp}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }); + if (!response.ok) throw new Error('Failed to verify OTP'); + + setNumberValidationState(PhoneNumberValidationState.Verified); + toast({ + title: "📱 Phone", + description: "Phone number verified", + }); + } catch (error) { + console.error('Error verifying OTP:', error); + toast({ + title: "📱 Phone", + description: "Failed to verify OTP. Try again or contact us at team@khoj.dev", + }); + } + }; + const setSubscription = async (state: string) => { try { const url = `/api/subscription?email=${userConfig?.username}&operation=${state}`; @@ -466,7 +509,7 @@ export default function SettingsView() { @@ -475,7 +518,7 @@ export default function SettingsView() { variant="outline" className="border border-green-400" disabled={!number || number === userConfig.phone_number || !isValidPhoneNumber(number)} - onClick={() => setNumberValidationState(PhoneNumberValidationState.VerifyOTP)} + onClick={sendOTP} > {!number || number === userConfig.phone_number || !isValidPhoneNumber(number) ? "Update"