11import { NextRequest , NextResponse } from "next/server" ;
2- import { getServerSession } from "next-auth" ;
3- import { authOptions } from "@/lib/auth" ;
42import { rateLimitMiddleware } from "@/lib/middleware/rate-limit-middleware" ;
53import { TemplateService } from "@/lib/db/services/templateService" ;
4+ import { getAuthenticatedUser } from "@/lib/helpers/apiAuth" ;
65
76// GET /api/templates - Get all templates
87async function handleGetTemplates ( request : NextRequest ) : Promise < NextResponse > {
@@ -44,9 +43,9 @@ async function handleCreateTemplate(
4443 request : NextRequest ,
4544) : Promise < NextResponse > {
4645 try {
47- // Check authentication
48- const session = await getServerSession ( authOptions ) ;
49- if ( ! session ?. user ) {
46+ // Check authentication (supports both session and API token)
47+ const user = await getAuthenticatedUser ( request ) ;
48+ if ( ! user ) {
5049 return NextResponse . json (
5150 { error : "Unauthorized - Please login to create templates" } ,
5251 { status : 401 } ,
@@ -60,32 +59,34 @@ async function handleCreateTemplate(
6059 return NextResponse . json ( { error : "Invalid JSON" } , { status : 400 } ) ;
6160 }
6261
63- const { name, description, content, category, tags } =
62+ // Accept both 'name' and 'title' for compatibility
63+ const { name, title, description, content, category, tags } =
6464 ( body as Record < string , unknown > ) ?? { } ;
6565
66- if ( typeof name !== "string" || typeof content !== "string" ) {
66+ // Use 'name' if provided, otherwise use 'title'
67+ const templateName = ( name as string ) || ( title as string ) ;
68+
69+ if ( typeof templateName !== "string" || typeof content !== "string" ) {
6770 return NextResponse . json (
68- { error : "Name and content are required" } ,
71+ { error : "Name/title and content are required" } ,
6972 { status : 400 } ,
7073 ) ;
7174 }
7275
7376 // Validate required fields
74- if ( ! name || ! content ) {
77+ if ( ! templateName || ! content ) {
7578 return NextResponse . json (
76- { error : "Name and content are required" } ,
79+ { error : "Name/title and content are required" } ,
7780 { status : 400 } ,
7881 ) ;
7982 }
8083
8184 // Create template in database
8285 const newTemplate = await TemplateService . createTemplate ( {
83- name,
84- description : typeof description === "string" ? description : "" ,
86+ name : templateName , // Use the resolved name
8587 content,
8688 category : ( typeof category === "string" ? category : "general" ) as "email" | "blog" | "social" | "general" ,
8789 tags : Array . isArray ( tags ) ? tags . map ( String ) : [ ] ,
88- createdAt : new Date ( ) . toISOString ( ) ,
8990 } ) ;
9091
9192 return NextResponse . json (
0 commit comments