aboutsummaryrefslogtreecommitdiff
path: root/src/app/api/user/profile-image/route.ts
blob: aabc337d3d4d8ebd101831e853e1eb0b12820403 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { NextRequest, NextResponse } from "next/server"
import { getServerSession } from "next-auth/next"
import sharp from "sharp"
import { authOptions } from "@/lib/auth"
import dbConnect from "@/lib/mongodb"
import User from "@/model/User"
import { uploadToMinio, deleteFromMinio } from "@/lib/minio"

// Configuration
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10MB
const ALLOWED_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']
const OUTPUT_WIDTH = 400
const OUTPUT_HEIGHT = 400
const OUTPUT_QUALITY = 80

export async function POST(request: NextRequest) {
  try {
    // Check authentication
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401 }
      )
    }

    // Parse FormData
    const formData = await request.formData()
    const file = formData.get('image') as File

    // Validate file exists
    if (!file) {
      return NextResponse.json(
        { error: "No file provided" },
        { status: 400 }
      )
    }

    // Validate file type
    if (!ALLOWED_TYPES.includes(file.type)) {
      return NextResponse.json(
        { error: `Invalid file type. Allowed: ${ALLOWED_TYPES.join(', ')}` },
        { status: 400 }
      )
    }

    // Validate file size
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { error: `File too large. Maximum size: ${MAX_FILE_SIZE / 1024 / 1024}MB` },
        { status: 400 }
      )
    }

    // Convert File to Buffer
    const buffer = Buffer.from(await file.arrayBuffer())

    // Validate image and get metadata
    let imageMetadata
    try {
      imageMetadata = await sharp(buffer).metadata()
    } catch (error) {
      return NextResponse.json(
        { error: "Invalid image file" },
        { status: 400 }
      )
    }

    // Additional validation
    if (!imageMetadata.width || !imageMetadata.height) {
      return NextResponse.json(
        { error: "Unable to read image dimensions" },
        { status: 400 }
      )
    }

    // Process image: resize and convert to WebP
    const processedBuffer = await sharp(buffer)
      .resize(OUTPUT_WIDTH, OUTPUT_HEIGHT, {
        fit: 'cover',
        position: 'center'
      })
      .webp({ quality: OUTPUT_QUALITY })
      .toBuffer()

    // Generate unique filename
    const timestamp = Date.now()
    const filename = `avatar_${timestamp}.webp`
    const key = `users/${session.user.id}/profile/${filename}`

    // Connect to database
    await dbConnect()

    // Get current user to check for existing profile image
    const currentUser = await User.findById(session.user.id)
    if (!currentUser) {
      return NextResponse.json(
        { error: "User not found" },
        { status: 404 }
      )
    }

    // Delete old profile image from MinIO if it exists
    if (currentUser.profileImage?.key) {
      try {
        await deleteFromMinio(currentUser.profileImage.key)
      } catch (error) {
        console.warn("Failed to delete old profile image:", error)
        // Continue with upload even if deletion fails
      }
    }

    // Upload to MinIO
    const minioUrl = await uploadToMinio(key, processedBuffer, 'image/webp')

    // Update user with new profile image
    const updatedUser = await User.findByIdAndUpdate(
      session.user.id,
      {
        profileImage: {
          url: minioUrl,
          key: key,
          uploadedAt: new Date()
        }
      },
      { new: true }
    )

    // Return success response
    return NextResponse.json({
      message: "Profile image uploaded successfully",
      profileImage: {
        url: minioUrl,
        uploadedAt: new Date()
      }
    }, { status: 200 })

  } catch (error) {
    console.error("Profile image upload error:", error)
    
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Check authentication
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401 }
      )
    }

    await dbConnect()

    // Get current user
    const currentUser = await User.findById(session.user.id)
    if (!currentUser) {
      return NextResponse.json(
        { error: "User not found" },
        { status: 404 }
      )
    }

    // Check if user has profile image
    if (!currentUser.profileImage?.key) {
      return NextResponse.json(
        { error: "No profile image to delete" },
        { status: 400 }
      )
    }

    // Delete from MinIO
    await deleteFromMinio(currentUser.profileImage.key)

    // Remove profile image from user document
    await User.findByIdAndUpdate(
      session.user.id,
      { $unset: { profileImage: 1 } }
    )

    return NextResponse.json({
      message: "Profile image deleted successfully"
    }, { status: 200 })

  } catch (error) {
    console.error("Profile image deletion error:", error)
    
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    )
  }
}