feat: user can set and update username with 2 step authentication

This commit is contained in:
2025-10-24 17:13:11 +05:30
parent 84d6dc0f8a
commit 2eec1b2e30
7 changed files with 476 additions and 21 deletions

View File

@@ -137,4 +137,44 @@ scp -P 9022 Smsservice/smsserviceapplication.jar <username>@localhost:/home/<use
- **2** → Read Only
-**null** → not configured consider as disabled
## 8. NGINX setup:
- sudo vi /etc/nginx/conf.d/ib.conf
- sudo cat /etc/nginx/conf.d/ib.conf
```
server {
listen 80;
server_name _;
return 301 https://$host$request_uri; # redirect all HTTP to HTTPS
}
server {
listen 443 ssl;
server_name _;
ssl_certificate /etc/nginx/ssl/IB.crt;
ssl_certificate_key /etc/nginx/ssl/IB.key;
# Your chosen log files
error_log /var/log/nginx/ib_error.log warn;
access_log /var/log/nginx/ib_access.log;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
```
- sudo nginx -t
- sudo systemctl reload nginx

View File

@@ -20,7 +20,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
{ label: "Change Login Password", href: "/settings/change_login_password" },
{ label: "Change transaction Password", href: "/settings/change_txn_password" },
{ label: "Set transaction Password", href: "/settings/set_txn_password" },
{ label: "Set userId", href: "/settings/user_id" },
{ label: "Preferred Name", href: "/settings/user_id" },
];
useEffect(() => {
const token = localStorage.getItem("access_token");

View File

@@ -1,18 +1,403 @@
"use client";
import React, { useEffect, useState } from "react";
import { Group, Loader, Paper, Text } from "@mantine/core";
import {
TextInput,
Button,
Title,
Paper,
Group,
Text,
List,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconUser, IconRefresh } from "@tabler/icons-react";
import { generateCaptcha } from "@/app/captcha";
import { sendOtp, verifyOtp } from "@/app/_util/otp";
export default function SetPreferredNameSimple() {
const [preferredName, setPreferredName] = useState("");
const [confirmName, setConfirmName] = useState("");
const [preferredNameError, setPreferredNameError] = useState<string | null>(null);
const [confirmNameError, setConfirmNameError] = useState<string | null>(null);
const [captcha, setCaptcha] = useState("");
const [captchaInput, setCaptchaInput] = useState("");
const [otp, setOtp] = useState("");
const [otpValidated, setOtpValidated] = useState(false);
const [countdown, setCountdown] = useState(180);
const [timerActive, setTimerActive] = useState(false);
const [step, setStep] = useState<"form" | "otp" | "final">("form");
const [existingName, setExistingName] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
export default function ChangePassword() {
return (
<Paper shadow="sm" radius="md" p="md" withBorder h={400} >
<Group>
<Text fw={700} size="lg">
The feature will be available soon...
const icon = <IconUser size={18} stroke={1.5} />;
// 🟢 Fetch name + generate captcha on mount
useEffect(() => {
checkPreferredName();
regenerateCaptcha();
}, []);
// 🟢 OTP timer
useEffect(() => {
let interval: number | undefined;
if (timerActive && countdown > 0) {
interval = window.setInterval(() => {
setCountdown((prev) => prev - 1);
}, 1000);
}
if (countdown === 0) {
if (interval) clearInterval(interval);
setTimerActive(false);
}
return () => {
if (interval) clearInterval(interval);
};
}, [timerActive, countdown]);
// 🟢 API: Fetch preferred name
async function checkPreferredName() {
try {
const token = localStorage.getItem("access_token");
const response = await fetch("/api/auth/user_name", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || "Failed to fetch preferred name");
setExistingName(data.user_name || null);
} catch (err) {
console.error(err);
setExistingName(null);
} finally {
setLoading(false);
}
}
// 🟢 Captcha
const regenerateCaptcha = async () => {
const newCaptcha = await generateCaptcha();
setCaptcha(newCaptcha);
setCaptchaInput("");
};
// 🟢 Live Validation (kept from your previous version)
function onPreferredNameChange(value: string) {
const sanitized = value.replace(/[^A-Za-z0-9@_]/g, "").slice(0, 11);
setPreferredName(sanitized);
if (sanitized.length > 0 && (sanitized.length < 5 || sanitized.length > 11)) {
setPreferredNameError("Preferred Name must be 511 characters.");
} else {
setPreferredNameError(null);
}
}
function onConfirmNameChange(value: string) {
const sanitized = value.replace(/[^A-Za-z0-9@_]/g, "").slice(0, 11);
setConfirmName(sanitized);
if (sanitized && sanitized !== preferredName) {
setConfirmNameError("Confirm name does not match Preferred Name.");
} else {
setConfirmNameError(null);
}
}
// 🟢 OTP
async function handleSendOtp() {
try {
await sendOtp({ type: "USERNAME_UPDATED" });
notifications.show({
title: "OTP Sent",
message: "An OTP has been sent to your registered mobile.",
color: "blue",
});
setStep("otp");
setCountdown(180);
setTimerActive(true);
} catch (err: any) {
notifications.show({
title: "Error",
message: err.message || "Failed to send OTP.",
color: "red",
});
}
}
async function handleVerifyOtp() {
try {
await verifyOtp(otp);
notifications.show({
title: "OTP Verified",
message: "OTP has been successfully verified.",
color: "green",
});
setOtpValidated(true);
setStep("final");
} catch {
notifications.show({
title: "Invalid OTP",
message: "The OTP entered is incorrect.",
color: "red",
});
}
}
// 🟢 Update Preferred Name API
async function handleUpdatePreferredName() {
const token = localStorage.getItem("access_token");
if (!token) {
notifications.show({
title: "Session Expired",
message: "Please log in again.",
color: "red",
});
return;
}
try {
const response = await fetch("/api/auth/user_name", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ user_name: preferredName }),
});
const result = await response.json();
if (!response.ok) throw new Error(result.message || "Failed to update preferred name");
notifications.show({
title: "Success",
message: "Preferred name updated successfully!",
color: "green",
});
resetForm();
await checkPreferredName(); // refresh
} catch (err: any) {
notifications.show({
title: "Error",
message: err.message || "Server error, please try again later.",
color: "red",
});
}
}
const resetForm = () => {
setPreferredName("");
setConfirmName("");
setCaptchaInput("");
setOtp("");
setOtpValidated(false);
setStep("form");
regenerateCaptcha();
};
// 🟢 Main Submit
const handleSubmit = async () => {
if (step === "form") {
if (!preferredName || !confirmName || !captchaInput) {
notifications.show({
title: "Missing Fields",
message: "Please fill all mandatory fields.",
color: "red",
});
return;
}
if (preferredNameError || confirmNameError) {
notifications.show({
title: "Invalid Input",
message: "Please correct highlighted fields before continuing.",
color: "red",
});
return;
}
if (captchaInput !== captcha) {
notifications.show({
title: "Invalid Captcha",
message: "Please enter correct captcha.",
color: "red",
});
regenerateCaptcha();
return;
}
await handleSendOtp();
return;
}
if (step === "otp") {
await handleVerifyOtp();
return;
}
if (step === "final") {
await handleUpdatePreferredName();
return;
}
};
if (loading) return <Text>Loading...</Text>;
return (
<Paper shadow="sm" radius="md" p="md" withBorder>
<Title order={3} mb="sm">
Set Preferred Name
</Title>
<div style={{ overflowY: "auto", maxHeight: "280px", paddingRight: 8 }}>
{existingName && (
<Text mb="sm">
<Text span fw={600}>Current Preferred Name: </Text>
<Text span>{existingName}</Text>
</Text>
)}
{!existingName && (
<Text mb="sm">
<Text span fw={500} c='red' >You have not set the user ID yet. Please set it first.</Text>
</Text>
)}
<Group grow>
<TextInput
label="Preferred Name"
placeholder="Enter preferred name (511 chars, only letters, numbers, @, _)"
value={preferredName}
onChange={(e) => onPreferredNameChange(e.currentTarget.value)}
withAsterisk
mb="xs"
maxLength={11}
readOnly={step !== "form"}
error={preferredNameError || undefined}
/>
<TextInput
label="Confirm Preferred Name"
placeholder="Re-enter preferred name"
value={confirmName}
onChange={(e) => onConfirmNameChange(e.currentTarget.value)}
withAsterisk
mb="xs"
rightSection={icon}
readOnly={step !== "form"}
error={confirmNameError || undefined}
/>
</Group>
{/* CAPTCHA */}
<div style={{ marginTop: 5 }}>
<label style={{ display: "block", marginBottom: 4, fontSize: "14px" }}>
Enter CAPTCHA <span style={{ color: "red" }}>*</span>
</label>
<div
style={{
display: "flex",
alignItems: "center",
gap: 10,
marginBottom: 5,
}}
>
<div
style={{
fontSize: "18px",
letterSpacing: "3px",
background: "#f3f4f6",
padding: "6px 12px",
borderRadius: "6px",
border: "1px solid #d1d5db",
userSelect: "none",
textDecoration: "line-through",
fontFamily: "cursive",
}}
>
{captcha}
</div>
<Button
size="xs"
variant="outline"
onClick={regenerateCaptcha}
style={{ height: 30, padding: "0 10px", lineHeight: "1" }}
disabled={step !== "form"}
>
Refresh
</Button>
<TextInput
placeholder="Enter above text"
value={captchaInput}
onChange={(e) => setCaptchaInput(e.currentTarget.value)}
withAsterisk
style={{ flexGrow: 1 }}
readOnly={step !== "form"}
/>
</div>
</div>
{/* OTP */}
{step !== "form" && (
<Group grow mt="sm">
<TextInput
label="OTP"
placeholder="Enter OTP"
value={otp}
onChange={(e) => setOtp(e.currentTarget.value)}
maxLength={6}
withAsterisk
disabled={otpValidated}
/>
{!otpValidated && (
timerActive ? (
<Text size="xs" c="dimmed" style={{ minWidth: "120px" }}>
Resend OTP in{" "}
{String(Math.floor(countdown / 60)).padStart(2, "0")}:
{String(countdown % 60).padStart(2, "0")}
</Text>
<Loader color="blue" type="bars" size="sm" />
</Group>
</Paper>
);
) : (
<IconRefresh
size={22}
style={{
cursor: "pointer",
color: "blue",
marginBottom: "6px",
}}
onClick={handleSendOtp}
/>
)
)}
</Group>
)}
</div>
{/* BUTTONS */}
<Group mt="md" gap="sm">
<Button onClick={handleSubmit}>
{step === "form" && "Submit"}
{step === "otp" && "Validate OTP"}
{step === "final" && "Set Preferred Name"}
</Button>
<Button variant="outline" color="gray" onClick={resetForm}>
Reset
</Button>
</Group>
<List size="sm" mt="xs" withPadding>
<List.Item>
Your Preferred Name must be 511 characters long and contain only
letters, numbers, and @ or _ symbols.
</List.Item>
<List.Item>
You can change your username a maximum of 5 times.
</List.Item>
</List>
</Paper>
);
}

View File

@@ -310,7 +310,17 @@ export default function SetLoginPwd() {
readOnly={captchaValidate}
/>
<Group mt="sm" align="center">
<Box style={{ backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive" }}>{captcha}</Box>
<Box style={{
backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive",
userSelect: "none",
pointerEvents: "none",
}}
onCopy={(e) => e.preventDefault()}
onContextMenu={(e) => e.preventDefault()}>
{captcha}</Box>
<Button size="xs" variant="light" onClick={regenerateCaptcha}>Refresh</Button>
</Group>
<TextInput

View File

@@ -334,7 +334,15 @@ export default function SetTransactionPwd() {
/>
{/* CAPTCHA */}
<Group mt="sm" align="center">
<Box style={{ backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive" }}>{captcha}</Box>
<Box style={{
backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive",
userSelect: "none",
pointerEvents: "none",
}}
onCopy={(e) => e.preventDefault()}
onContextMenu={(e) => e.preventDefault()}>
{captcha}</Box>
<Button size="xs" variant="light" onClick={regenerateCaptcha}>Refresh</Button>
</Group>
<TextInput

View File

@@ -10,11 +10,12 @@ interface SendOtpPayload {
date?: string;
userOtp?: string;
username?: string;
PreferName?: string;
}
function getStoredMobileNumber(): string {
const mobileNumber = localStorage.getItem('remitter_mobile_no');
// const mobileNumber = "7890544527";
// const mobileNumber = localStorage.getItem('remitter_mobile_no');
const mobileNumber = "6297421727";
if (!mobileNumber) throw new Error('Mobile number not found.');
return mobileNumber;
}

View File

@@ -45,8 +45,8 @@ export default function Login() {
}
try {
await sendOtp({ type: 'LOGIN_OTP', username: CIF, mobileNumber: mobile });
// await sendOtp({ type: 'LOGIN_OTP', username: CIF, mobileNumber: "7890544527" });
// await sendOtp({ type: 'LOGIN_OTP', username: CIF, mobileNumber: mobile });
await sendOtp({ type: 'LOGIN_OTP', username: CIF, mobileNumber: "6297421727" });
notifications.show({
color: 'orange',
title: 'OTP Required',
@@ -67,8 +67,8 @@ export default function Login() {
async function handleVerifyOtp(mobile?: string) {
try {
if (mobile) {
await verifyLoginOtp(otp, mobile);
// await verifyLoginOtp(otp, '7890544527');
// await verifyLoginOtp(otp, mobile);
await verifyLoginOtp(otp, '6297421727');
return true;
}
}
@@ -557,7 +557,18 @@ export default function Login() {
</Anchor> */}
</Box>
<Group align="center">
<Box style={{ backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive" }}>{captcha}</Box>
<Box style={{
backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive",
userSelect: "none",
pointerEvents: "none",
}}
onCopy={(e) => e.preventDefault()}
onContextMenu={(e) => e.preventDefault()}
>
{captcha}
</Box>
<Button size="xs" variant="light" onClick={regenerateCaptcha} disabled={otpRequired}>Refresh</Button>
</Group>
<TextInput