feat(auth): implement 3-attempt login rate limiting, 15-minute account lockout countdown timer, and admin manual unlock capability
This commit is contained in:
1 parent
a577f2d672
commit
ccea9d7f09
5 files changed
+157
-31
No files matched your search
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<ManagedUser>[] {
|
||||
return [
|
||||
{
|
||||
@@ -28,7 +32,7 @@ export function getColumns({
|
||||
},
|
||||
{
|
||||
header: "Account Name",
|
||||
className: "w-[22%] text-center",
|
||||
className: "w-[20%] text-center",
|
||||
accessor: (row) => (
|
||||
<span className="text-sm font-medium text-slate-200">
|
||||
{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) => <code className="text-xs text-slate-400 font-mono">{row.username}</code>
|
||||
},
|
||||
{
|
||||
@@ -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 (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-rose-500/10 text-rose-400 border border-rose-500/30 uppercase tracking-wider">
|
||||
<Lock className="w-3 h-3" /> Locked
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 uppercase tracking-wider">
|
||||
Active
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
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 <span className="text-xs text-slate-500 italic">No device assigned</span>;
|
||||
@@ -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 (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => !isSelf && onEditClick(row)}
|
||||
disabled={!!isDisabled}
|
||||
title={isSelf ? "Cannot edit your own account from here" : undefined}
|
||||
className="text-xs text-blue-400 hover:text-blue-300 disabled:opacity-50 disabled:cursor-not-allowed hover:underline font-medium cursor-pointer"
|
||||
>
|
||||
{isSelf ? "👤 (You)" : "⚙️ Edit User"}
|
||||
</button>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{isLocked && onUnlockClick && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onUnlockClick(row)}
|
||||
disabled={isUnlocking}
|
||||
title="Unlock account access"
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-semibold text-emerald-400 bg-emerald-400/10 border border-emerald-400/30 hover:bg-emerald-400/20 transition-all cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{isUnlocking ? <Loader2 className="w-3 h-3 animate-spin" /> : <Unlock className="w-3 h-3" />}
|
||||
<span>Unlock</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => !isSelf && onEditClick(row)}
|
||||
disabled={!!isDisabled}
|
||||
title={isSelf ? "Cannot edit your own account from here" : undefined}
|
||||
className="text-xs text-blue-400 hover:text-blue-300 disabled:opacity-50 disabled:cursor-not-allowed hover:underline font-medium cursor-pointer"
|
||||
>
|
||||
{isSelf ? "👤 (You)" : "⚙️ Edit"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<ManagedUser | null>(null);
|
||||
const [targetCompany, setTargetCompany] = useState<string | null>(null);
|
||||
const [viewAsLoading, setViewAsLoading] = useState<string | null>(null);
|
||||
const [unlockLoading, setUnlockLoading] = useState<string | number | null>(null);
|
||||
// Registry agents untuk lookup label agent (digunakan pada View-As banner)
|
||||
const [agentRegistry, setAgentRegistry] = useState<Record<string, string>>({});
|
||||
|
||||
@@ -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 (
|
||||
|
||||
+51
-10
@@ -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<number | null>(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 (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-center items-center relative overflow-hidden">
|
||||
{/* Background Glows */}
|
||||
@@ -67,8 +94,17 @@ export default function LoginPage() {
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-3 rounded-lg bg-red-500/10 border border-red-500/50 text-red-500 text-sm text-center">
|
||||
{error}
|
||||
<div className="mb-6 p-4 rounded-xl bg-red-500/10 border border-red-500/40 text-red-400 text-xs sm:text-sm space-y-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<ShieldAlert className="w-5 h-5 text-red-400 shrink-0 mt-0.5" />
|
||||
<div className="flex-1 font-medium leading-relaxed">{error}</div>
|
||||
</div>
|
||||
{isLockedOut && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2 border-t border-red-500/20 font-mono font-bold text-red-300 text-base">
|
||||
<Timer className="w-4 h-4 animate-pulse" />
|
||||
<span>Unlock in {formatSeconds(lockoutSeconds)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -77,9 +113,10 @@ export default function LoginPage() {
|
||||
<User className="absolute left-3 top-2.5 h-5 w-5 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
disabled={isLockedOut || loading}
|
||||
value={username}
|
||||
onChange={(e) => 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() {
|
||||
<Lock className="absolute left-3 top-2.5 h-5 w-5 text-muted-foreground" />
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
disabled={isLockedOut || loading}
|
||||
value={password}
|
||||
onChange={(e) => 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
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={isLockedOut || loading}
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-2.5 text-muted-foreground hover:text-white transition-colors focus:outline-none"
|
||||
className="absolute right-3 top-2.5 text-muted-foreground hover:text-white transition-colors focus:outline-none disabled:opacity-50"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
|
||||
</button>
|
||||
@@ -106,11 +145,13 @@ export default function LoginPage() {
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full py-2.5 px-4 bg-gradient-to-r from-red-600 to-blue-700 hover:from-red-500 hover:to-blue-600 text-white font-medium rounded-lg shadow-[0_0_15px_rgba(220,38,38,0.3)] hover:shadow-[0_0_20px_rgba(220,38,38,0.5)] transition-all duration-300 flex items-center justify-center mt-6"
|
||||
disabled={loading || isLockedOut}
|
||||
className="w-full py-2.5 px-4 bg-gradient-to-r from-red-600 to-blue-700 hover:from-red-500 hover:to-blue-600 text-white font-medium rounded-lg shadow-[0_0_15px_rgba(220,38,38,0.3)] hover:shadow-[0_0_20px_rgba(220,38,38,0.5)] transition-all duration-300 flex items-center justify-center mt-6 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? (
|
||||
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
) : isLockedOut ? (
|
||||
`Locked (${formatSeconds(lockoutSeconds)})`
|
||||
) : (
|
||||
"Sign In"
|
||||
)}
|
||||
|
||||
+16
-2
@@ -1,7 +1,7 @@
|
||||
// Admin User Management API helpers
|
||||
|
||||
export interface ManagedUser {
|
||||
id: number;
|
||||
id: string | number;
|
||||
username: string;
|
||||
role: 'SUPER_ADMIN' | 'EXECUTIVE' | 'AGENT_VIEWER' | 'SOC_ANALYST' | 'ENGINEER' | 'TENANT_ADMIN' | string;
|
||||
site_uuid: string | null;
|
||||
@@ -10,6 +10,8 @@ export interface ManagedUser {
|
||||
agent_uuids?: string[];
|
||||
account_name: string | null;
|
||||
profile_picture: string | null;
|
||||
login_attempts?: number;
|
||||
lockout_until?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -99,7 +101,7 @@ export async function updateAdminAgentUser(formData: FormData): Promise<{ ok: bo
|
||||
}
|
||||
|
||||
// DELETE /api/auth/admin/delete-agent-user/:id
|
||||
export async function deleteAdminAgentUser(userId: number): Promise<void> {
|
||||
export async function deleteAdminAgentUser(userId: string | number): Promise<void> {
|
||||
const res = await fetch('/api/auth/admin/delete-agent-user/' + userId, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
@@ -239,3 +241,15 @@ export function resolveAgentLabel(agentUuid: string, users: ManagedUser[]): stri
|
||||
return user?.account_name || agentUuid;
|
||||
}
|
||||
|
||||
export async function unlockUser(userId: string | number): Promise<{ ok: boolean; message?: string; error?: string }> {
|
||||
const res = await fetch('/api/auth/admin/unlock-user', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getViewAsHeaders(),
|
||||
},
|
||||
body: JSON.stringify({ user_id: userId }),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user