Files
my2/server/api/products/index.get.ts
Bastian Masanek ff9960edef Add role-based visibility and management features for products
- Introduced a role-based visibility system for products, ensuring that only users with approved roles can view specific products.
- Added new database tables for roles, user roles, and product role visibility to manage access control.
- Implemented utility functions for role management, including fetching approved roles, checking product visibility, and assigning roles to users and products.
- Updated API endpoints to filter products based on user roles, enhancing security and user experience.
- Prepared the database schema for future role request and approval workflows in upcoming phases.
2025-11-02 10:17:40 +01:00

70 lines
2.1 KiB
TypeScript

/**
* GET /api/products
*
* Returns a list of products visible to the current user based on their roles.
*
* Role-based Visibility (MVP):
* - Unauthenticated users: See NO products (empty array)
* - Authenticated users: See products assigned to their approved roles
* - Products WITHOUT role assignments: NOT visible (opt-in visibility)
*
* Query Parameters:
* - category: Filter by category (optional, comma-separated for multiple)
*
* Phase 2/3: This will be extended with role request/approval workflow
*/
import { eq, and, inArray } from 'drizzle-orm'
import { products } from '../../database/schema'
import { getVisibleProductIdsForUser } from '../../utils/roles'
export default defineEventHandler(async (event) => {
const db = useDatabase()
const query = getQuery(event)
const categoryParam = query.category as string | undefined
try {
// Get user session (if authenticated)
const { user } = await getUserSession(event)
// MVP: Unauthenticated users cannot see any products
if (!user) {
return []
}
// Get product IDs visible to this user (based on approved roles)
const visibleProductIds = await getVisibleProductIdsForUser(user.id)
// If user has no approved roles or no products are assigned to their roles
if (visibleProductIds.length === 0) {
return []
}
// Build where conditions
const conditions = [
eq(products.active, true),
inArray(products.id, visibleProductIds), // Role-based filtering
]
// Filter by category if provided
if (categoryParam) {
const categories = categoryParam.split(',').map((c) => c.trim())
conditions.push(inArray(products.category, categories))
}
// Fetch products with filters
const visibleProducts = await db.query.products.findMany({
where: and(...conditions),
orderBy: (products, { asc }) => [asc(products.category), asc(products.name)],
})
return visibleProducts
} catch (error) {
console.error('Error fetching products:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to fetch products',
})
}
})