feat: complete scheduled publishing, security remediation and DEV_TICKETS implementation
This commit is contained in:
1 parent
d6d4158cbe
commit
efb3c473c4
35 files changed
+685
-185
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AdminController } from './admin.controller';
|
||||
import { AdminService } from './admin.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
|
||||
describe('AdminController', () => {
|
||||
let controller: AdminController;
|
||||
@@ -8,7 +9,10 @@ describe('AdminController', () => {
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AdminController],
|
||||
providers: [{ provide: AdminService, useValue: {} }],
|
||||
providers: [
|
||||
{ provide: AdminService, useValue: {} },
|
||||
{ provide: SettingsService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AdminController>(AdminController);
|
||||
|
||||
@@ -509,8 +509,13 @@ export class AdminService {
|
||||
};
|
||||
|
||||
let resolvedCategorySlug = data.categorySlug;
|
||||
if (data.categoryId && (!resolvedCategorySlug || resolvedCategorySlug === 'general')) {
|
||||
const cat = await this.prisma.category.findUnique({ where: { id: data.categoryId } });
|
||||
if (
|
||||
data.categoryId &&
|
||||
(!resolvedCategorySlug || resolvedCategorySlug === 'general')
|
||||
) {
|
||||
const cat = await this.prisma.category.findUnique({
|
||||
where: { id: data.categoryId },
|
||||
});
|
||||
if (cat) {
|
||||
resolvedCategorySlug = cat.slug;
|
||||
}
|
||||
@@ -597,12 +602,19 @@ export class AdminService {
|
||||
}
|
||||
|
||||
if (data.ingredientList && Array.isArray(data.ingredientList)) {
|
||||
const uniqueIngs = Array.from(new Set(data.ingredientList.map((i: string) => i.trim()).filter(Boolean)));
|
||||
const uniqueIngs = Array.from(
|
||||
new Set(
|
||||
data.ingredientList.map((i: string) => i.trim()).filter(Boolean),
|
||||
),
|
||||
);
|
||||
if (uniqueIngs.length > 0) {
|
||||
const resolvedIngs = await this.resolveIngredientCards(uniqueIngs);
|
||||
await this.prisma.productIngredient.createMany({
|
||||
data: uniqueIngs.map((ingredient: string) => ({
|
||||
data: resolvedIngs.map((item) => ({
|
||||
productId: product.id,
|
||||
ingredient,
|
||||
ingredient: item.ingredient,
|
||||
ingredientCardId: item.ingredientCardId,
|
||||
ingredientCardSlug: item.ingredientCardSlug,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -672,7 +684,9 @@ export class AdminService {
|
||||
|
||||
let resolvedCategorySlug = data.categorySlug;
|
||||
if (data.categoryId && !resolvedCategorySlug) {
|
||||
const cat = await this.prisma.category.findUnique({ where: { id: data.categoryId } });
|
||||
const cat = await this.prisma.category.findUnique({
|
||||
where: { id: data.categoryId },
|
||||
});
|
||||
if (cat) {
|
||||
resolvedCategorySlug = cat.slug;
|
||||
}
|
||||
@@ -687,9 +701,11 @@ export class AdminService {
|
||||
scientificTagline: data.scientificTagline,
|
||||
description: data.description,
|
||||
shortDescription: data.shortDescription,
|
||||
ingredients: data.ingredients !== undefined ? data.ingredients : undefined,
|
||||
ingredients:
|
||||
data.ingredients !== undefined ? data.ingredients : undefined,
|
||||
categoryId: data.categoryId,
|
||||
categorySlug: resolvedCategorySlug !== undefined ? resolvedCategorySlug : undefined,
|
||||
categorySlug:
|
||||
resolvedCategorySlug !== undefined ? resolvedCategorySlug : undefined,
|
||||
buyPrice: data.buyPrice !== undefined ? data.buyPrice : undefined,
|
||||
marginRetailPercent:
|
||||
marginRetail !== undefined ? marginRetail : undefined,
|
||||
@@ -772,14 +788,26 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
if (data.ingredientList !== undefined && Array.isArray(data.ingredientList)) {
|
||||
await this.prisma.productIngredient.deleteMany({ where: { productId: id } });
|
||||
if (
|
||||
data.ingredientList !== undefined &&
|
||||
Array.isArray(data.ingredientList)
|
||||
) {
|
||||
await this.prisma.productIngredient.deleteMany({
|
||||
where: { productId: id },
|
||||
});
|
||||
if (data.ingredientList.length > 0) {
|
||||
const uniqueIngs = Array.from(new Set(data.ingredientList.map((i: string) => i.trim()).filter(Boolean)));
|
||||
const uniqueIngs = Array.from(
|
||||
new Set(
|
||||
data.ingredientList.map((i: string) => i.trim()).filter(Boolean),
|
||||
),
|
||||
);
|
||||
const resolvedIngs = await this.resolveIngredientCards(uniqueIngs);
|
||||
await this.prisma.productIngredient.createMany({
|
||||
data: uniqueIngs.map((ingredient: string) => ({
|
||||
data: resolvedIngs.map((item) => ({
|
||||
productId: id,
|
||||
ingredient,
|
||||
ingredient: item.ingredient,
|
||||
ingredientCardId: item.ingredientCardId,
|
||||
ingredientCardSlug: item.ingredientCardSlug,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -1781,4 +1809,47 @@ export class AdminService {
|
||||
totalMatched: products.length,
|
||||
};
|
||||
}
|
||||
|
||||
async resolveIngredientCards(ingredients: string[]): Promise<
|
||||
Array<{
|
||||
ingredient: string;
|
||||
ingredientCardId: string | null;
|
||||
ingredientCardSlug: string | null;
|
||||
}>
|
||||
> {
|
||||
if (!ingredients || ingredients.length === 0) return [];
|
||||
const allCards = await this.prisma.ingredient.findMany({
|
||||
select: { id: true, slug: true, nameFa: true, nameEn: true },
|
||||
});
|
||||
|
||||
const normalize = (str: string) =>
|
||||
str.toLowerCase().replace(/[()]/g, '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
return ingredients.map((rawIng) => {
|
||||
const clean = rawIng.trim();
|
||||
const norm = normalize(clean);
|
||||
|
||||
const matchedCard = allCards.find((card) => {
|
||||
const cardFaNorm = normalize(card.nameFa);
|
||||
const cardEnNorm = normalize(card.nameEn);
|
||||
const cardSlugNorm = normalize(card.slug.replace(/-/g, ' '));
|
||||
|
||||
return (
|
||||
norm === cardFaNorm ||
|
||||
norm === cardEnNorm ||
|
||||
norm === cardSlugNorm ||
|
||||
norm.includes(cardFaNorm) ||
|
||||
cardFaNorm.includes(norm) ||
|
||||
norm.includes(cardEnNorm) ||
|
||||
cardEnNorm.includes(norm)
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
ingredient: clean,
|
||||
ingredientCardId: matchedCard ? matchedCard.id : null,
|
||||
ingredientCardSlug: matchedCard ? matchedCard.slug : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Injectable, NotFoundException, OnModuleInit } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
OnModuleDestroy,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PaginationDto } from '../common/dto/pagination.dto';
|
||||
import { RevalidationService } from '../common/revalidation/revalidation.service';
|
||||
|
||||
@Injectable()
|
||||
export class BlogsService implements OnModuleInit {
|
||||
export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(BlogsService.name);
|
||||
private schedulerTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private revalidationService: RevalidationService,
|
||||
@@ -13,6 +22,21 @@ export class BlogsService implements OnModuleInit {
|
||||
|
||||
async onModuleInit() {
|
||||
await this.seedDefaultCategories();
|
||||
// Start background scheduled publishing worker (every 60 seconds)
|
||||
this.schedulerTimer = setInterval(() => {
|
||||
this.publishDueScheduledBlogs().catch((err) => {
|
||||
this.logger.error('Error in publishDueScheduledBlogs worker:', err);
|
||||
});
|
||||
}, 60000);
|
||||
// Run an initial check on startup
|
||||
this.publishDueScheduledBlogs().catch(() => {});
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
if (this.schedulerTimer) {
|
||||
clearInterval(this.schedulerTimer);
|
||||
this.schedulerTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async seedDefaultCategories() {
|
||||
@@ -22,7 +46,11 @@ export class BlogsService implements OnModuleInit {
|
||||
{ name: 'سلامت گوارش و متابولیسم', slug: 'digestion', order: 2 },
|
||||
{ name: 'مفاصل، استخوان و اسکلت', slug: 'joints-bones', order: 3 },
|
||||
{ name: 'پوست، مو و آلرژی', slug: 'skin-coat', order: 4 },
|
||||
{ name: 'ایمنی، پیشگیری و مراقبت بالینی', slug: 'health-prevention', order: 5 },
|
||||
{
|
||||
name: 'ایمنی، پیشگیری و مراقبت بالینی',
|
||||
slug: 'health-prevention',
|
||||
order: 5,
|
||||
},
|
||||
];
|
||||
|
||||
for (const cat of defaultCategories) {
|
||||
@@ -33,7 +61,10 @@ export class BlogsService implements OnModuleInit {
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[BlogsService] Failed to seed default blog categories:', err);
|
||||
console.warn(
|
||||
'[BlogsService] Failed to seed default blog categories:',
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +146,7 @@ export class BlogsService implements OnModuleInit {
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
} = data;
|
||||
@@ -138,15 +170,34 @@ export class BlogsService implements OnModuleInit {
|
||||
}
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || 'PUBLISHED';
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = 'SCHEDULED';
|
||||
finalIsPublished = false;
|
||||
finalPublishedAt = null;
|
||||
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
|
||||
finalStatus = 'PUBLISHED';
|
||||
finalIsPublished = true;
|
||||
finalPublishedAt = parsedScheduledAt;
|
||||
} else if (!finalPublishedAt && finalStatus === 'PUBLISHED') {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
publishedAt: publishedAt
|
||||
? new Date(publishedAt)
|
||||
: rest.status === 'PUBLISHED'
|
||||
? new Date()
|
||||
: null,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
@@ -177,18 +228,17 @@ export class BlogsService implements OnModuleInit {
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
} = data;
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(publishedAt !== undefined
|
||||
? { publishedAt: publishedAt ? new Date(publishedAt) : null }
|
||||
: {}),
|
||||
...(authorId ? { author: { connect: { id: authorId } } } : {}),
|
||||
...(categoryId !== undefined
|
||||
? categoryId
|
||||
@@ -197,6 +247,24 @@ export class BlogsService implements OnModuleInit {
|
||||
: {}),
|
||||
};
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
updatePayload.scheduledAt = parsedScheduledAt;
|
||||
|
||||
if (parsedScheduledAt && parsedScheduledAt > now) {
|
||||
updatePayload.status = 'SCHEDULED';
|
||||
updatePayload.isPublished = false;
|
||||
updatePayload.publishedAt = null;
|
||||
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
|
||||
updatePayload.status = 'PUBLISHED';
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
}
|
||||
|
||||
if (Array.isArray(tagNames)) {
|
||||
const tagConnectOrCreate = [];
|
||||
for (const tName of tagNames) {
|
||||
@@ -367,4 +435,61 @@ export class BlogsService implements OnModuleInit {
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes blogs that have reached their scheduled publication date
|
||||
*/
|
||||
async publishDueScheduledBlogs(): Promise<number> {
|
||||
const now = new Date();
|
||||
const dueBlogs = await this.prisma.blog.findMany({
|
||||
where: {
|
||||
status: 'SCHEDULED',
|
||||
scheduledAt: { lte: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
title: true,
|
||||
scheduledAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!dueBlogs || dueBlogs.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`Found ${dueBlogs.length} due scheduled blog(s) to publish automatically.`,
|
||||
);
|
||||
|
||||
let publishedCount = 0;
|
||||
for (const blog of dueBlogs) {
|
||||
try {
|
||||
const publishDate = blog.scheduledAt || now;
|
||||
await this.prisma.blog.update({
|
||||
where: { id: blog.id },
|
||||
data: {
|
||||
status: 'PUBLISHED',
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
publishedCount++;
|
||||
this.logger.log(
|
||||
`Successfully published scheduled blog [${blog.title}] (${blog.slug})`,
|
||||
);
|
||||
|
||||
// Immediate cache & sitemap revalidation
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
} catch (err: any) {
|
||||
this.logger.error(
|
||||
`Failed to publish scheduled blog [${blog.id}] (${blog.slug}): ${err?.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return publishedCount;
|
||||
}
|
||||
}
|
||||
@@ -19,24 +19,69 @@ export class CategoriesService implements OnModuleInit {
|
||||
private async seedDefaultCategories() {
|
||||
try {
|
||||
const defaultCategories = [
|
||||
{ name: 'مفاصل و استخوان', slug: 'joints', description: 'مکملهای ارتوپدی و مفاصل حاوی عصاره صدف سبز و GAG' },
|
||||
{ name: 'سیستم ایمنی و گوارش', slug: 'immune', description: 'تقویت سیستم دفاعی بدن و پروبیوتیکهای تخصصی' },
|
||||
{ name: 'ویتامینها و انرژیبخشها', slug: 'energy', description: 'مولتیویتامینها و تونیکهای انرژیبخش' },
|
||||
{ name: 'مراقبتهای ویژه (پوست، دندان و چشم)', slug: 'special-care', description: 'محلولهای نقره، قطرههای شستشو و ژل دندان' },
|
||||
{ name: 'تقویت عمومی', slug: 'general', description: 'مکملهای پایهای و روزانه سگ و گربه' },
|
||||
{ name: 'تغذیه تخصصی', slug: 'nutrition', description: 'شیر خشک، پودر خون گاو و مکملهای تخصصی پرورش' },
|
||||
{ name: 'مکملهای غذایی و درمانی', slug: 'supplements', description: 'طیف کامل مکملهای گرید دارویی Canina' },
|
||||
{
|
||||
name: 'مفاصل و استخوان',
|
||||
slug: 'joints',
|
||||
description: 'مکملهای ارتوپدی و مفاصل حاوی عصاره صدف سبز و GAG',
|
||||
},
|
||||
{
|
||||
name: 'سیستم ایمنی و گوارش',
|
||||
slug: 'immune',
|
||||
description: 'تقویت سیستم دفاعی بدن و پروبیوتیکهای تخصصی',
|
||||
},
|
||||
{
|
||||
name: 'ویتامینها و انرژیبخشها',
|
||||
slug: 'energy',
|
||||
description: 'مولتیویتامینها و تونیکهای انرژیبخش',
|
||||
},
|
||||
{
|
||||
name: 'مراقبتهای ویژه (پوست، دندان و چشم)',
|
||||
slug: 'special-care',
|
||||
description: 'محلولهای نقره، قطرههای شستشو و ژل دندان',
|
||||
},
|
||||
{
|
||||
name: 'تقویت عمومی',
|
||||
slug: 'general',
|
||||
description: 'مکملهای پایهای و روزانه سگ و گربه',
|
||||
},
|
||||
{
|
||||
name: 'تغذیه تخصصی',
|
||||
slug: 'nutrition',
|
||||
description: 'شیر خشک، پودر خون گاو و مکملهای تخصصی پرورش',
|
||||
},
|
||||
{
|
||||
name: 'مکملهای غذایی و درمانی',
|
||||
slug: 'supplements',
|
||||
description: 'طیف کامل مکملهای گرید دارویی Canina',
|
||||
},
|
||||
];
|
||||
|
||||
for (const cat of defaultCategories) {
|
||||
await this.prisma.category.upsert({
|
||||
const savedCat = await this.prisma.category.upsert({
|
||||
where: { slug: cat.slug },
|
||||
update: { name: cat.name, description: cat.description },
|
||||
create: { name: cat.name, slug: cat.slug, description: cat.description },
|
||||
create: {
|
||||
name: cat.name,
|
||||
slug: cat.slug,
|
||||
description: cat.description,
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically connect products with matching categorySlug
|
||||
await this.prisma.product.updateMany({
|
||||
where: {
|
||||
categorySlug: cat.slug,
|
||||
},
|
||||
data: {
|
||||
categoryId: savedCat.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[CategoriesService] Failed to seed default categories:', err);
|
||||
console.warn(
|
||||
'[CategoriesService] Failed to seed default categories:',
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,9 +66,18 @@ export class MediaService {
|
||||
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const ext = path.extname(originalname).toLowerCase();
|
||||
const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.pdf'];
|
||||
const ALLOWED_EXTENSIONS = [
|
||||
'.jpg',
|
||||
'.jpeg',
|
||||
'.png',
|
||||
'.webp',
|
||||
'.gif',
|
||||
'.pdf',
|
||||
];
|
||||
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
||||
throw new BadRequestException('پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).');
|
||||
throw new BadRequestException(
|
||||
'پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).',
|
||||
);
|
||||
}
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
@@ -183,8 +183,10 @@ export class SslService {
|
||||
.toLowerCase();
|
||||
|
||||
// SEC-009: Strict domain validation preventing SSRF
|
||||
const DOMAIN_REGEX = /^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
|
||||
const IP_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
||||
const DOMAIN_REGEX =
|
||||
/^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
|
||||
const IP_REGEX =
|
||||
/^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
||||
|
||||
if (
|
||||
!cleanDomain ||
|
||||
@@ -196,7 +198,8 @@ export class SslService {
|
||||
) {
|
||||
return resolve({
|
||||
onlineCheck: false,
|
||||
error: 'فرمت نام دامنه نامعتبر است یا آدرسهای IP و داخلی مجاز نیستند.',
|
||||
error:
|
||||
'فرمت نام دامنه نامعتبر است یا آدرسهای IP و داخلی مجاز نیستند.',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,11 @@ export class AuthController {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
}
|
||||
|
||||
private setAuthCookies(res?: Response, accessToken?: string, refreshToken?: string) {
|
||||
private setAuthCookies(
|
||||
res?: Response,
|
||||
accessToken?: string,
|
||||
refreshToken?: string,
|
||||
) {
|
||||
if (!res || typeof res.cookie !== 'function') return;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
if (accessToken) {
|
||||
@@ -117,7 +121,11 @@ export class AuthController {
|
||||
) {
|
||||
const result = await this.authService.verifyOtp(verifyOtpDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -136,7 +144,11 @@ export class AuthController {
|
||||
) {
|
||||
const result = await this.authService.register(registerDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -153,7 +165,11 @@ export class AuthController {
|
||||
) {
|
||||
const result = await this.authService.login(loginDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -170,7 +186,11 @@ export class AuthController {
|
||||
) {
|
||||
const result = await this.authService.adminLogin(body);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -178,7 +198,9 @@ export class AuthController {
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post('refresh-token')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'دریافت جفت توکن جدید با استفاده از توکن تازهسازی' })
|
||||
@ApiOperation({
|
||||
summary: 'دریافت جفت توکن جدید با استفاده از توکن تازهسازی',
|
||||
})
|
||||
@ApiOkResponse({ description: 'توکنهای جدید با موفقیت صادر شدند' })
|
||||
@ApiBadRequestResponse({ description: 'توکن نامعتبر یا منقضی است' })
|
||||
async refreshToken(
|
||||
@@ -193,7 +215,11 @@ export class AuthController {
|
||||
}
|
||||
const result = await this.authService.refreshToken(token);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -213,7 +239,11 @@ export class AuthController {
|
||||
) {
|
||||
const result = await this.authService.refresh(req.user);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,10 @@ describe('AuthService', () => {
|
||||
});
|
||||
|
||||
it('should delete OTP, find or create user and sign JWT', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
mockRedis.get.mockImplementation(async (key: string) => {
|
||||
if (key.startsWith('otp_attempts:')) return null;
|
||||
return '12345';
|
||||
});
|
||||
const mockUser = { id: 'user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
|
||||
@@ -116,7 +119,10 @@ describe('AuthService', () => {
|
||||
});
|
||||
|
||||
it('should create new user if user does not exist', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
mockRedis.get.mockImplementation(async (key: string) => {
|
||||
if (key.startsWith('otp_attempts:')) return null;
|
||||
return '12345';
|
||||
});
|
||||
mockPrisma.user.findUnique.mockResolvedValue(null);
|
||||
const newUser = { id: 'new-user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.create.mockResolvedValue(newUser);
|
||||
|
||||
@@ -150,17 +150,41 @@ export class AuthService {
|
||||
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
|
||||
const phoneNumber = normalizeMobile(verifyOtpDto.phoneNumber);
|
||||
const code = String(verifyOtpDto.code).trim();
|
||||
const attemptsKey = `otp_attempts:${phoneNumber}`;
|
||||
|
||||
// SEC-007: Check failed attempts to prevent brute-forcing OTP
|
||||
const currentAttempts = await this.redisService.get(attemptsKey);
|
||||
if (currentAttempts && Number(currentAttempts) >= 5) {
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'تعداد تلاشهای ناموفق بیش از حد مجاز است. لطفاً پس از چند دقیقه دوباره کد جدید دریافت کنید.',
|
||||
error: 'TOO_MANY_OTP_ATTEMPTS',
|
||||
});
|
||||
}
|
||||
|
||||
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
|
||||
|
||||
if (!savedCode || savedCode !== code) {
|
||||
const attempts = await this.redisService.incr(attemptsKey, 300);
|
||||
const remaining = Math.max(0, 5 - attempts);
|
||||
if (remaining === 0) {
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'کد تایید به دلیل ۵ بار تلاش ناموفق باطل شد. لطفاً کد جدید دریافت کنید.',
|
||||
error: 'TOO_MANY_OTP_ATTEMPTS',
|
||||
});
|
||||
}
|
||||
throw new BadRequestException({
|
||||
message: 'کد وارد شده اشتباه یا منقضی شده است',
|
||||
message: `کد وارد شده اشتباه یا منقضی شده است. (${remaining} تلاش باقیمانده)`,
|
||||
error: 'INVALID_OTP',
|
||||
});
|
||||
}
|
||||
|
||||
// Success - clear OTP and attempts
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
await this.redisService.del(attemptsKey);
|
||||
|
||||
let user = await this.prisma.user.findUnique({
|
||||
where: { mobile: phoneNumber },
|
||||
@@ -346,11 +370,10 @@ export class AuthService {
|
||||
Buffer.from(crypto.createHash('sha256').update(adminEmail).digest()),
|
||||
);
|
||||
|
||||
const passwordMatches =
|
||||
crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
|
||||
);
|
||||
const passwordMatches = crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
|
||||
);
|
||||
|
||||
if (emailMatches && passwordMatches) {
|
||||
const payload = {
|
||||
@@ -391,7 +414,9 @@ export class AuthService {
|
||||
secret: getJwtRefreshSecret(),
|
||||
});
|
||||
} catch {
|
||||
throw new UnauthorizedException('توکن تازهسازی نامعتبر یا منقضی شده است');
|
||||
throw new UnauthorizedException(
|
||||
'توکن تازهسازی نامعتبر یا منقضی شده است',
|
||||
);
|
||||
}
|
||||
|
||||
const userId = decoded.sub;
|
||||
@@ -405,7 +430,9 @@ export class AuthService {
|
||||
const tokenKey = `refresh_token:${userId}:${tokenId}`;
|
||||
const tokenValid = await this.redisService.get(tokenKey);
|
||||
if (!tokenValid) {
|
||||
throw new UnauthorizedException('توکن تازهسازی باطل شده است. لطفاً مجدداً وارد شوید');
|
||||
throw new UnauthorizedException(
|
||||
'توکن تازهسازی باطل شده است. لطفاً مجدداً وارد شوید',
|
||||
);
|
||||
}
|
||||
|
||||
// Invalidate old token (Rotation)
|
||||
@@ -492,7 +519,9 @@ export class AuthService {
|
||||
|
||||
// If token payload has jti and sub, also invalidate the refresh token in Redis
|
||||
if (decoded && decoded.sub && decoded.jti) {
|
||||
await this.redisService.del(`refresh_token:${decoded.sub}:${decoded.jti}`);
|
||||
await this.redisService.del(
|
||||
`refresh_token:${decoded.sub}:${decoded.jti}`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
await this.redisService.set(`bl_token:${token}`, '1', 15 * 60);
|
||||
|
||||
@@ -49,7 +49,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (rawToken) {
|
||||
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
|
||||
if (isBlacklisted) {
|
||||
throw new UnauthorizedException('این توکن باطل شده است. لطفاً مجدداً وارد شوید');
|
||||
throw new UnauthorizedException(
|
||||
'این توکن باطل شده است. لطفاً مجدداً وارد شوید',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -182,6 +182,17 @@ export class BlogsService {
|
||||
throw new NotFoundException('مقاله یافت نشد');
|
||||
}
|
||||
|
||||
// Public route must not expose scheduled, draft, or future published posts
|
||||
const now = new Date();
|
||||
const isReady =
|
||||
blog.isPublished &&
|
||||
blog.status === 'PUBLISHED' &&
|
||||
(!blog.publishedAt || blog.publishedAt <= now);
|
||||
|
||||
if (!isReady) {
|
||||
throw new NotFoundException('مقاله یافت نشد');
|
||||
}
|
||||
|
||||
// Fetch related products safely
|
||||
let relatedProducts: any[] = [];
|
||||
if (
|
||||
|
||||
@@ -46,10 +46,23 @@ export class RolesGuard implements CanActivate {
|
||||
}
|
||||
}
|
||||
|
||||
const userRoleLower = user.role.toLowerCase();
|
||||
const hasRole = requiredRoles.some(
|
||||
(r) => r.toLowerCase() === userRoleLower,
|
||||
);
|
||||
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, '');
|
||||
|
||||
const userRoleNorm = normalizeRole(user.role);
|
||||
const hasRole = requiredRoles.some((r) => {
|
||||
const requiredNorm = normalizeRole(r);
|
||||
// Direct normalized match
|
||||
if (requiredNorm === userRoleNorm) return true;
|
||||
// Superadmin satisfies admin
|
||||
if (
|
||||
(userRoleNorm === 'superadmin' || userRoleNorm === 'adminsuper') &&
|
||||
requiredNorm === 'admin'
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
|
||||
}
|
||||
|
||||
@@ -9,7 +9,9 @@ export class RevalidationService {
|
||||
process.env.FRONTEND_INTERNAL_URL ||
|
||||
process.env.FRONTEND_URL ||
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(process.env.NODE_ENV === 'production' ? 'http://frontend_prod:8080' : 'http://localhost:3000');
|
||||
(process.env.NODE_ENV === 'production'
|
||||
? 'http://frontend_prod:8080'
|
||||
: 'http://localhost:3000');
|
||||
return raw.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
@@ -17,9 +19,13 @@ export class RevalidationService {
|
||||
const secret = process.env.REVALIDATION_SECRET;
|
||||
if (!secret) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('REVALIDATION_SECRET is required in production environment.');
|
||||
throw new Error(
|
||||
'REVALIDATION_SECRET is required in production environment.',
|
||||
);
|
||||
}
|
||||
this.logger.warn('REVALIDATION_SECRET is not defined in environment variables.');
|
||||
this.logger.warn(
|
||||
'REVALIDATION_SECRET is not defined in environment variables.',
|
||||
);
|
||||
return '';
|
||||
}
|
||||
return secret;
|
||||
@@ -108,6 +114,7 @@ export class RevalidationService {
|
||||
this.revalidateTag('blogs'),
|
||||
this.revalidateTag('home-data'),
|
||||
this.revalidatePath('/blog'),
|
||||
this.revalidatePath('/sitemap.xml'),
|
||||
this.revalidatePath('/'),
|
||||
];
|
||||
|
||||
|
||||
@@ -230,7 +230,7 @@ export class OrdersService {
|
||||
});
|
||||
}
|
||||
|
||||
return tx.order.create({
|
||||
const newOrder = await tx.order.create({
|
||||
data: {
|
||||
userId,
|
||||
couponId,
|
||||
@@ -252,6 +252,17 @@ export class OrdersService {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (couponId) {
|
||||
await tx.coupon
|
||||
.update({
|
||||
where: { id: couponId },
|
||||
data: { usedCount: { increment: 1 } },
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
return newOrder;
|
||||
});
|
||||
|
||||
// Send Order Confirmation SMS for wallet orders
|
||||
@@ -570,8 +581,11 @@ export class OrdersService {
|
||||
throw new NotFoundException('سفارش مورد نظر یافت نشد');
|
||||
}
|
||||
|
||||
if (['shipped', 'delivered'].includes(order.status)) {
|
||||
throw new BadRequestException('این سفارش قبلاً پرداخت و تکمیل شده است');
|
||||
const ALLOWED_RETRY_STATUSES = ['pending_payment', 'failed'];
|
||||
if (!ALLOWED_RETRY_STATUSES.includes(order.status)) {
|
||||
throw new BadRequestException(
|
||||
'تنها سفارشهای در انتظار پرداخت یا ناموفق قابلیت پرداخت مجدد دارند.',
|
||||
);
|
||||
}
|
||||
|
||||
const selectedMethod = paymentMethod || order.paymentMethod || 'online';
|
||||
|
||||
@@ -219,10 +219,19 @@ export class PaymentController {
|
||||
return res.status(HttpStatus.OK).json(result);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('verify-status/:trackId')
|
||||
@ApiOperation({ summary: 'استعلام و دریافت وضعیت تراکنش پرداخت با TrackID' })
|
||||
async getTransactionStatus(@Param('trackId') trackId: string) {
|
||||
return this.paymentService.getTransaction(trackId);
|
||||
async getTransactionStatus(
|
||||
@Req() req: { user: { id: string; role?: string } },
|
||||
@Param('trackId') trackId: string,
|
||||
) {
|
||||
const isAdmin =
|
||||
req.user?.role === 'Admin' ||
|
||||
req.user?.role === 'ADMIN' ||
|
||||
req.user?.role === 'SuperAdmin';
|
||||
return this.paymentService.getTransaction(trackId, req.user?.id, isAdmin);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
@@ -452,6 +453,16 @@ export class PaymentService {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Increment coupon usedCount if coupon was applied
|
||||
if (transaction.order && transaction.order.couponId) {
|
||||
await tx.coupon
|
||||
.update({
|
||||
where: { id: transaction.order.couponId },
|
||||
data: { usedCount: { increment: 1 } },
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. If it's a Wallet Top-up
|
||||
@@ -765,7 +776,11 @@ export class PaymentService {
|
||||
/**
|
||||
* 5. Get Payment Transaction Details by TrackID
|
||||
*/
|
||||
async getTransaction(trackId: string) {
|
||||
async getTransaction(
|
||||
trackId: string,
|
||||
requestingUserId?: string,
|
||||
isAdmin = false,
|
||||
) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { trackId },
|
||||
include: {
|
||||
@@ -784,6 +799,21 @@ export class PaymentService {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
if (
|
||||
!isAdmin &&
|
||||
requestingUserId &&
|
||||
transaction.userId &&
|
||||
transaction.userId !== requestingUserId
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'شما دسترسی به اطلاعات این تراکنش را ندارید',
|
||||
);
|
||||
}
|
||||
|
||||
const maskedCard = transaction.cardNumber
|
||||
? transaction.cardNumber.replace(/(\d{6})\d{6}(\d{4})/, '$1******$2')
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: transaction.id,
|
||||
trackId: transaction.trackId,
|
||||
@@ -793,11 +823,7 @@ export class PaymentService {
|
||||
message: transaction.message,
|
||||
gateway: transaction.gateway,
|
||||
type: transaction.type,
|
||||
cardNumber: transaction.cardNumber,
|
||||
ipAddress: transaction.ipAddress,
|
||||
userAgent: transaction.userAgent,
|
||||
rawRequest: transaction.rawRequest,
|
||||
rawResponse: transaction.rawResponse,
|
||||
cardNumber: isAdmin ? transaction.cardNumber : maskedCard,
|
||||
paidAt: transaction.paidAt,
|
||||
createdAt: transaction.createdAt,
|
||||
order: transaction.order,
|
||||
@@ -806,9 +832,17 @@ export class PaymentService {
|
||||
id: transaction.user.id,
|
||||
firstName: transaction.user.firstName,
|
||||
lastName: transaction.user.lastName,
|
||||
mobile: transaction.user.mobile,
|
||||
mobile: isAdmin ? transaction.user.mobile : undefined,
|
||||
}
|
||||
: null,
|
||||
...(isAdmin
|
||||
? {
|
||||
ipAddress: transaction.ipAddress,
|
||||
userAgent: transaction.userAgent,
|
||||
rawRequest: transaction.rawRequest,
|
||||
rawResponse: transaction.rawResponse,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,13 @@ export class PrescriptionsController {
|
||||
notes?: string;
|
||||
},
|
||||
) {
|
||||
if (
|
||||
!body?.fileUrl ||
|
||||
typeof body.fileUrl !== 'string' ||
|
||||
!body.fileUrl.trim()
|
||||
) {
|
||||
throw new BadRequestException('آدرس فایل نسخه الزامی است.');
|
||||
}
|
||||
const userId = req.user?.id || req.user?.userId || null;
|
||||
return this.prescriptionsService.create(userId, body);
|
||||
}
|
||||
|
||||
@@ -235,7 +235,9 @@ export class ProductsService {
|
||||
petTypes: Array.from(
|
||||
new Set(
|
||||
petTypesDb
|
||||
.map((p) => (p.suitableFor === 'هر دو' ? 'سگ و گربه' : p.suitableFor))
|
||||
.map((p) =>
|
||||
p.suitableFor === 'هر دو' ? 'سگ و گربه' : p.suitableFor,
|
||||
)
|
||||
.filter(Boolean),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -100,9 +100,18 @@ export const CANONICAL_ALIASES: Record<string, string[]> = {
|
||||
charity_round_step: ['CHARITY_ROUND_STEP', 'charityRoundStep'],
|
||||
charityRoundStep: ['CHARITY_ROUND_STEP', 'charity_round_step'],
|
||||
|
||||
CHARITY_DONATION_ENABLED: ['charity_donation_enabled', 'charityDonationEnabled'],
|
||||
charity_donation_enabled: ['CHARITY_DONATION_ENABLED', 'charityDonationEnabled'],
|
||||
charityDonationEnabled: ['CHARITY_DONATION_ENABLED', 'charity_donation_enabled'],
|
||||
CHARITY_DONATION_ENABLED: [
|
||||
'charity_donation_enabled',
|
||||
'charityDonationEnabled',
|
||||
],
|
||||
charity_donation_enabled: [
|
||||
'CHARITY_DONATION_ENABLED',
|
||||
'charityDonationEnabled',
|
||||
],
|
||||
charityDonationEnabled: [
|
||||
'CHARITY_DONATION_ENABLED',
|
||||
'charity_donation_enabled',
|
||||
],
|
||||
|
||||
// Zibal Gateway & Tokens
|
||||
ZIBAL_EBANK_TOKEN: [
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiBearerAuth,
|
||||
@@ -202,9 +204,11 @@ export class UsersController {
|
||||
return this.usersService.setDefaultAddress(req.user.id, addressId);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'ADMIN', 'SuperAdmin')
|
||||
@ApiBearerAuth()
|
||||
@Post('wallet/top-up')
|
||||
@ApiOperation({ summary: 'شارژ کیف پول کاربر' })
|
||||
@ApiOperation({ summary: 'شارژ دستی کیف پول کاربر (فقط مدیر سیستم)' })
|
||||
@ApiCreatedResponse({
|
||||
description: 'کیف پول با موفقیت شارژ شد',
|
||||
schema: {
|
||||
@@ -222,12 +226,13 @@ export class UsersController {
|
||||
@ApiBadRequestResponse({ description: 'مبلغ نامعتبر است' })
|
||||
async topUpWallet(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() body: { amount: number },
|
||||
@Body() body: { amount: number; targetUserId?: string },
|
||||
) {
|
||||
const amount = Number(body.amount);
|
||||
if (!amount || amount <= 0) {
|
||||
throw new BadRequestException('مبلغ شارژ باید بزرگتر از صفر باشد');
|
||||
}
|
||||
return this.usersService.topUpWallet(req.user.id, amount);
|
||||
const targetUserId = body.targetUserId || req.user.id;
|
||||
return this.usersService.topUpWallet(targetUserId, amount);
|
||||
}
|
||||
}
|
||||
@@ -30,64 +30,6 @@ export class UsersService {
|
||||
) {}
|
||||
|
||||
async findById(id: string) {
|
||||
if (id === '12345678-1234-1234-1234-123456789012') {
|
||||
const dbUser = await this.prisma.user.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
pets: {
|
||||
include: {
|
||||
medicalConditions: true,
|
||||
reminders: {
|
||||
include: {
|
||||
completions: true,
|
||||
},
|
||||
},
|
||||
healthLogs: true,
|
||||
},
|
||||
},
|
||||
orders: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 50,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (dbUser) {
|
||||
const { password, ...safeUser } = dbUser;
|
||||
return {
|
||||
...safeUser,
|
||||
hasPassword: !!password,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
firstName: 'مدیر',
|
||||
lastName: 'سیستم',
|
||||
email: process.env.ADMIN_EMAIL || 'admin@canina.ir',
|
||||
mobile: '09120000000',
|
||||
role: 'Admin',
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
charityDonationTotal: new Prisma.Decimal(0),
|
||||
pets: [],
|
||||
orders: [],
|
||||
addresses: [],
|
||||
walletTransactions: [],
|
||||
hasPassword: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
|
||||
@@ -13,6 +13,8 @@ import { VideosService } from './videos.service';
|
||||
import { CreateVideoDto } from './dto/create-video.dto';
|
||||
import { GetVideosQueryDto } from './dto/get-videos-query.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
@@ -42,7 +44,8 @@ export class VideosController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'ADMIN', 'SuperAdmin')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'افزودن ویدئوی جدید (ادمین)' })
|
||||
create(@Body() createVideoDto: CreateVideoDto) {
|
||||
@@ -50,7 +53,8 @@ export class VideosController {
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'ADMIN', 'SuperAdmin')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'ویرایش ویدئو (ادمین)' })
|
||||
update(
|
||||
@@ -61,7 +65,8 @@ export class VideosController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'ADMIN', 'SuperAdmin')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'حذف ویدئو (ادمین)' })
|
||||
remove(@Param('id') id: string) {
|
||||
|
||||
Reference in new issue
Block a user