mirror of
https://git.coastit.co.za/caitlin/CRM_ENVR.git
synced 2026-07-12 12:07:06 +02:00
1adc4806fa
Security Fixes
File Change
.env.local Placeholder JWT secret (rotate to random value: openssl rand -base64 64)
src/middleware.ts Removed /api/auth/me bypass; API routes return JSON 401 (not 302 redirect)
src/lib/auth.ts sameSite: "lax" → "strict" (create + destroy cookie); SVG name chars are pre-computed (no injection)
src/lib/avatar.ts Added sanitizeName() — strips non-alphanumeric/safe chars, max 50 chars
src/app/api/users/route.ts POST restricted to super_admin; validates role against whitelist ["sales","admin","super_admin","dev"]; validates active defaults to true
src/app/api/users/[id]/route.ts DELETE restricted to super_admin; blocks self-deletion
src/app/api/leads/[id]/route.ts GET: non-admin users filtered by assigned_to; PATCH: ownership check + score validated 0-100 range
src/app/api/leads/route.ts DELETE: ownership + admin check; GET: ownership filter for non-admin users
src/app/api/conversations/[id]/messages/route.ts GET/POST: verify user is a conversation_participant before access
rust-ai/src/main.rs CORS: AllowOrigin::list(["localhost:3006", "127.0.0.1:3006"]) (was Any)
Performance Fixes
File Change
src/app/api/leads/route.ts Added limit (default 50), offset query params; ownership filter in SQL
src/app/api/users/route.ts Added limit (default 50), offset query params
src/app/api/conversations/route.ts Added LIMIT 50
src/app/api/leads/[id]/notes/route.ts Added limit (default 50), offset query params
src/app/api/conversations/[id]/messages/route.ts Added limit (default 100), offset, before query params
src/app/(dashboard)/chats/page.tsx Pruned to 5 cached conversations; useMemo wraps messages/conversation/filteredConversations; otherParticipant moved outside component; added 10MB file size limit; recordingChunksRef cleared on discard
src/app/(dashboard)/leads/[id]/page.tsx Optimistic status update rolls back on fetch failure
database/migrations/003_chat.sql Added composite index idx_messages_conversation_created on (conversation_id, created_at DESC)
Code Quality Fixes
File Change
src/lib/ai.ts Removed dead getInstructions()/updateInstructions() (called nonexistent /ai/instructions)
src/lib/auth.ts bcrypt.hash(password, 12) — kept (acceptable, OWASP-recommended)
src/app/login/page.tsx "Forgot password?" button now shows alert to contact admin (was no-op)
src/components/users/user-form-dialog.tsx Password min 6 → 8 chars
26 silent catch {} blocks across 16 files (see below) Added console.warn("...") context messages
147 lines
4.3 KiB
TypeScript
147 lines
4.3 KiB
TypeScript
"use client"
|
|
|
|
import { createContext, useContext, useState, useCallback, useMemo, useEffect, ReactNode } from "react"
|
|
import { Notification, NotificationType } from "@/types"
|
|
|
|
interface NotificationContextValue {
|
|
notifications: Notification[]
|
|
unreadCount: number
|
|
unreadChatCount: number
|
|
addNotification: (type: NotificationType, title: string, description: string, link?: string) => void
|
|
markAsRead: (id: string) => void
|
|
markAllAsRead: () => void
|
|
dismiss: (id: string) => void
|
|
}
|
|
|
|
const NotificationContext = createContext<NotificationContextValue | null>(null)
|
|
|
|
export function NotificationProvider({ children }: { children: ReactNode }) {
|
|
const [notifications, setNotifications] = useState<Notification[]>([])
|
|
const [loading, setLoading] = useState(true)
|
|
const [unreadChatCount, setUnreadChatCount] = useState(0)
|
|
|
|
useEffect(() => {
|
|
async function fetchNotifications() {
|
|
try {
|
|
const res = await fetch("/api/notifications")
|
|
if (!res.ok) return
|
|
const data = await res.json()
|
|
if (data.notifications) {
|
|
setNotifications(data.notifications)
|
|
}
|
|
} catch {
|
|
console.warn("Failed to fetch notifications in notification provider")
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
fetchNotifications()
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
async function fetchUnread() {
|
|
try {
|
|
const res = await fetch("/api/conversations")
|
|
if (!res.ok) return
|
|
const data = await res.json()
|
|
if (!cancelled) {
|
|
const list = data.conversations || []
|
|
const total = list.reduce((sum: number, c: any) => sum + (c.unread || 0), 0)
|
|
setUnreadChatCount(total)
|
|
}
|
|
} catch {
|
|
console.warn("Failed to fetch unread conversations in notification provider")
|
|
}
|
|
}
|
|
fetchUnread()
|
|
const id = setInterval(fetchUnread, 5000)
|
|
return () => { cancelled = true; clearInterval(id) }
|
|
}, [])
|
|
|
|
const unreadCount = useMemo(
|
|
() => notifications.filter((n) => !n.read).length,
|
|
[notifications]
|
|
)
|
|
|
|
const addNotification = useCallback(
|
|
async (type: NotificationType, title: string, description: string, link?: string) => {
|
|
const notif: Notification = {
|
|
id: `temp-${Date.now()}`,
|
|
type,
|
|
title,
|
|
description,
|
|
timestamp: new Date().toISOString(),
|
|
read: false,
|
|
link,
|
|
}
|
|
setNotifications((prev) => [notif, ...prev])
|
|
try {
|
|
await fetch("/api/notifications", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ type, title, description, link }),
|
|
})
|
|
} catch {
|
|
console.warn("Failed to add notification in notification provider")
|
|
}
|
|
},
|
|
[]
|
|
)
|
|
|
|
const markAsRead = useCallback(async (id: string) => {
|
|
if (id.startsWith("temp-")) return
|
|
setNotifications((prev) =>
|
|
prev.map((n) => (n.id === id ? { ...n, read: true } : n))
|
|
)
|
|
try {
|
|
await fetch(`/api/notifications/${id}`, { method: "PATCH" })
|
|
} catch {
|
|
console.warn("Failed to mark notification as read in notification provider")
|
|
}
|
|
}, [])
|
|
|
|
const markAllAsRead = useCallback(async () => {
|
|
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })))
|
|
try {
|
|
await fetch("/api/notifications", { method: "PATCH" })
|
|
} catch {
|
|
console.warn("Failed to mark all notifications as read in notification provider")
|
|
}
|
|
}, [])
|
|
|
|
const dismiss = useCallback(async (id: string) => {
|
|
setNotifications((prev) => prev.filter((n) => n.id !== id))
|
|
if (id.startsWith("temp-")) return
|
|
try {
|
|
await fetch(`/api/notifications/${id}`, { method: "DELETE" })
|
|
} catch {
|
|
console.warn("Failed to dismiss notification in notification provider")
|
|
}
|
|
}, [])
|
|
|
|
return (
|
|
<NotificationContext.Provider
|
|
value={{
|
|
notifications,
|
|
unreadCount,
|
|
unreadChatCount,
|
|
addNotification,
|
|
markAsRead,
|
|
markAllAsRead,
|
|
dismiss,
|
|
}}
|
|
>
|
|
{children}
|
|
</NotificationContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useNotifications(): NotificationContextValue {
|
|
const ctx = useContext(NotificationContext)
|
|
if (!ctx) {
|
|
throw new Error("useNotifications must be used within a NotificationProvider")
|
|
}
|
|
return ctx
|
|
}
|