From ccea9d7f09fd38fea9b26696c221f8c943cb9bed Mon Sep 17 00:00:00 2001 From: Rafif Riqullah Siregar Date: Fri, 31 Jul 2026 10:01:06 +0700 Subject: [PATCH] feat(auth): implement 3-attempt login rate limiting, 15-minute account lockout countdown timer, and admin manual unlock capability --- backend/routes/auth/core.js | 20 +++++- src/app/(dashboard)/user-accounts/columns.tsx | 69 +++++++++++++++---- src/app/(dashboard)/user-accounts/page.tsx | 20 +++++- src/app/login/page.tsx | 61 +++++++++++++--- src/lib/admin-api.ts | 18 ++++- 5 files changed, 157 insertions(+), 31 deletions(-) diff --git a/backend/routes/auth/core.js b/backend/routes/auth/core.js index 871c47e..7fea3c4 100644 --- a/backend/routes/auth/core.js +++ b/backend/routes/auth/core.js @@ -29,7 +29,12 @@ router.post('/login', async (req, res) => { // Check if account is currently locked out if (user.lockout_until && user.lockout_until > new Date()) { const remainingTime = Math.ceil((user.lockout_until - new Date()) / 60000); - return res.status(403).json({ error: `Account is temporarily locked. Please try again in ${remainingTime} minute(s).` }); + const remainingSeconds = Math.ceil((user.lockout_until - new Date()) / 1000); + return res.status(403).json({ + error: `Account is temporarily locked due to 3 failed login attempts. Please try again in ${remainingTime} minute(s).`, + lockout_until: user.lockout_until, + lockout_seconds: remainingSeconds, + }); } const isValid = bcrypt.compareSync(password, user.password_hash); @@ -38,10 +43,19 @@ router.post('/login', async (req, res) => { if (user.login_attempts >= 3) { user.lockout_until = new Date(Date.now() + 15 * 60 * 1000); // 15 mins lockout await user.save(); - return res.status(403).json({ error: 'Account is temporarily locked. Please try again in 15 minute(s).' }); + return res.status(403).json({ + error: 'Account is temporarily locked due to 3 failed login attempts. Please try again in 15 minute(s).', + lockout_until: user.lockout_until, + lockout_seconds: 900, + }); } else { await user.save(); - return res.status(401).json({ error: 'Invalid Password' }); + const attemptsLeft = 3 - user.login_attempts; + const attemptsMsg = attemptsLeft === 1 ? '1 attempt remaining before lockout.' : `${attemptsLeft} attempts remaining before lockout.`; + return res.status(401).json({ + error: `Invalid password. ${attemptsMsg}`, + attempts_left: attemptsLeft, + }); } } diff --git a/src/app/(dashboard)/user-accounts/columns.tsx b/src/app/(dashboard)/user-accounts/columns.tsx index 56dccb7..fae8afb 100644 --- a/src/app/(dashboard)/user-accounts/columns.tsx +++ b/src/app/(dashboard)/user-accounts/columns.tsx @@ -3,22 +3,26 @@ import { Column } from "@/components/ui/DataTable"; import { type ManagedUser } from "@/lib/admin-api"; -import { Eye, Loader2 } from "lucide-react"; +import { Eye, Loader2, Lock, Unlock } from "lucide-react"; interface GetColumnsProps { role: string | null; currentUsername?: string | null; viewAsLoading?: string | null; + unlockLoading?: string | null; onEditClick: (user: ManagedUser) => void; onViewAsClick?: (user: ManagedUser) => void; + onUnlockClick?: (user: ManagedUser) => void; } export function getColumns({ role, currentUsername, viewAsLoading, + unlockLoading, onEditClick, onViewAsClick, + onUnlockClick, }: GetColumnsProps): Column[] { return [ { @@ -28,7 +32,7 @@ export function getColumns({ }, { header: "Account Name", - className: "w-[22%] text-center", + className: "w-[20%] text-center", accessor: (row) => ( {row.account_name || row.username} @@ -37,7 +41,7 @@ export function getColumns({ }, { header: "Username", - className: "w-[18%] text-center", + className: "w-[16%] text-center", accessor: (row) => {row.username} }, { @@ -56,9 +60,28 @@ export function getColumns({ ); } }, + { + header: "Status", + className: "w-[12%] text-center", + accessor: (row) => { + const isLocked = row.lockout_until && new Date(row.lockout_until) > new Date(); + if (isLocked) { + return ( + + Locked + + ); + } + return ( + + Active + + ); + } + }, { header: "Assigned Devices", - className: "w-[15%] text-center", + className: "w-[14%] text-center", accessor: (row) => { const uuids = row.agent_uuids || []; if (uuids.length === 0) return No device assigned; @@ -75,7 +98,6 @@ export function getColumns({ accessor: (row) => { const isSelf = currentUsername && row.username === currentUsername; const isCompanyAdmin = row.role === "COMPANY_ADMIN"; - // View-As tersedia untuk COMPANY_OPERATOR dan COMPANY_VIEWER (bukan diri sendiri, bukan admin) const canViewAs = onViewAsClick && !isSelf && !isCompanyAdmin && @@ -107,20 +129,37 @@ export function getColumns({ }, { header: "Actions", - className: "w-[12%] text-center", + className: "w-[15%] text-center", accessor: (row) => { const isSelf = currentUsername && row.username === currentUsername; + const isLocked = row.lockout_until && new Date(row.lockout_until) > new Date(); const isDisabled = role === "EXECUTIVE" || isSelf; + const isUnlocking = unlockLoading === row.id; + return ( - +
+ {isLocked && onUnlockClick && ( + + )} + +
); } } diff --git a/src/app/(dashboard)/user-accounts/page.tsx b/src/app/(dashboard)/user-accounts/page.tsx index 19430bd..9db14f6 100644 --- a/src/app/(dashboard)/user-accounts/page.tsx +++ b/src/app/(dashboard)/user-accounts/page.tsx @@ -3,7 +3,7 @@ import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Loader2, Users, Plus } from "lucide-react"; -import { getAdminUsers, getViewAsHeaders, startViewAsUser, type ManagedUser } from "@/lib/admin-api"; +import { getAdminUsers, getViewAsHeaders, startViewAsUser, unlockUser, type ManagedUser } from "@/lib/admin-api"; import { HelpTrigger } from "@/components/help/HelpTrigger"; import ExternalAccountModal from "@/components/admin/ExternalAccountModal"; @@ -23,6 +23,7 @@ export default function UserAccountsPage() { const [modalUser, setModalUser] = useState(null); const [targetCompany, setTargetCompany] = useState(null); const [viewAsLoading, setViewAsLoading] = useState(null); + const [unlockLoading, setUnlockLoading] = useState(null); // Registry agents untuk lookup label agent (digunakan pada View-As banner) const [agentRegistry, setAgentRegistry] = useState>({}); @@ -138,13 +139,30 @@ export default function UserAccountsPage() { } }; + const handleUnlockUser = async (user: ManagedUser) => { + setUnlockLoading(user.id); + try { + const res = await unlockUser(user.id); + if (res.ok) { + await loadData(); + } else { + alert('Failed to unlock user: ' + (res.error || 'Unknown error')); + } + } catch (err: any) { + alert('Failed to unlock user: ' + err.message); + } finally { + setUnlockLoading(null); + } + }; const columns = getColumns({ role, currentUsername, viewAsLoading, + unlockLoading: unlockLoading !== null ? String(unlockLoading) : null, onEditClick: handleEditClick, onViewAsClick: (role === "SUPER_ADMIN" || role === "COMPANY_ADMIN") ? handleViewAsUser : undefined, + onUnlockClick: (role === "SUPER_ADMIN" || role === "COMPANY_ADMIN" || role === "TENANT_ADMIN") ? handleUnlockUser : undefined, }); return ( diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 24137f1..c6634f9 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -1,9 +1,8 @@ "use client"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; -import { Lock, User, Eye, EyeOff } from "lucide-react"; -import Image from "next/image"; +import { Lock, User, Eye, EyeOff, ShieldAlert, Timer } from "lucide-react"; export default function LoginPage() { const [username, setUsername] = useState(""); @@ -11,10 +10,33 @@ export default function LoginPage() { const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [showPassword, setShowPassword] = useState(false); + const [lockoutSeconds, setLockoutSeconds] = useState(null); const router = useRouter(); + useEffect(() => { + if (lockoutSeconds === null || lockoutSeconds <= 0) return; + const interval = setInterval(() => { + setLockoutSeconds((prev) => { + if (prev === null || prev <= 1) { + clearInterval(interval); + setError(""); + return null; + } + return prev - 1; + }); + }, 1000); + return () => clearInterval(interval); + }, [lockoutSeconds]); + + const formatSeconds = (sec: number) => { + const mins = Math.floor(sec / 60); + const secs = sec % 60; + return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`; + }; + const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); + if (lockoutSeconds !== null && lockoutSeconds > 0) return; setError(""); setLoading(true); @@ -35,6 +57,9 @@ export default function LoginPage() { } if (!res.ok) { + if (data.lockout_seconds) { + setLockoutSeconds(data.lockout_seconds); + } throw new Error(data.error || data.message || "Login failed"); } @@ -51,6 +76,8 @@ export default function LoginPage() { } }; + const isLockedOut = lockoutSeconds !== null && lockoutSeconds > 0; + return (
{/* Background Glows */} @@ -67,8 +94,17 @@ export default function LoginPage() {
{error && ( -
- {error} +
+
+ +
{error}
+
+ {isLockedOut && ( +
+ + Unlock in {formatSeconds(lockoutSeconds)} +
+ )}
)} @@ -77,9 +113,10 @@ export default function LoginPage() { setUsername(e.target.value)} - className="w-full pl-10 pr-4 py-2.5 bg-background border border-border rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all" + className="w-full pl-10 pr-4 py-2.5 bg-background border border-border rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all disabled:opacity-50" placeholder="Username" required /> @@ -89,16 +126,18 @@ export default function LoginPage() { setPassword(e.target.value)} - className="w-full pl-10 pr-10 py-2.5 bg-background border border-border rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all" + className="w-full pl-10 pr-10 py-2.5 bg-background border border-border rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all disabled:opacity-50" placeholder="Password" required /> @@ -106,11 +145,13 @@ export default function LoginPage() {