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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
|
"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "@/hooks/use-toast"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { findUserById } from "@/lib/admin-users/service"
import { useSession } from "next-auth/react";
import { updateUserProfileImage } from "@/lib/users/service"
const accountFormSchema = z.object({
name: z
.string()
.min(2, {
message: "Name must be at least 2 characters.",
})
.max(30, {
message: "Name must not be longer than 30 characters.",
}),
email: z.string().email(),
imageFile: z.any().optional(),
})
type AccountFormValues = z.infer<typeof accountFormSchema>
export function AccountForm() {
const { data: session } = useSession();
const userId = session?.user.id || ""
const [currentImageUrl, setCurrentImageUrl] = React.useState<string | null>(null)
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null)
const [imageError, setImageError] = React.useState<boolean>(false)
const form = useForm<AccountFormValues>({
resolver: zodResolver(accountFormSchema),
defaultValues: {
name: "",
email: "",
imageFile: null,
},
})
// 안전한 이미지 URL 검증 함수
const isValidImageUrl = (url: string): boolean => {
try {
// 1. 빈 문자열 체크
if (!url || typeof url !== 'string') return false
// 2. 위험한 프로토콜 차단
const dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:', 'ftp:']
const lowerUrl = url.toLowerCase()
if (dangerousProtocols.some(protocol => lowerUrl.startsWith(protocol))) {
return false
}
// 3. 상대 경로 공격 방지
if (url.includes('../') || url.includes('..\\')) {
return false
}
// 4. 허용된 경로만 통과 (프로젝트 구조에 맞게 조정)
const allowedPaths = ['/profiles/', '/uploads/', '/images/']
const hasAllowedPath = allowedPaths.some(path => url.startsWith(path))
// 5. 또는 허용된 도메인만 통과 (필요한 경우)
// const allowedDomains = ['yourdomain.com', 'cdn.yourdomain.com']
// if (url.startsWith('http')) {
// const urlObj = new URL(url)
// return allowedDomains.includes(urlObj.hostname)
// }
return hasAllowedPath
} catch (error) {
console.error('URL validation error:', error)
return false
}
}
// 안전한 이미지 URL 생성 함수
const getSafeImageUrl = (imagePath: string | null): string | null => {
if (!imagePath) return null
// 이미 전체 경로인 경우
if (imagePath.startsWith('/profiles/') || imagePath.startsWith('/uploads/')) {
return isValidImageUrl(imagePath) ? imagePath : null
}
// 파일명만 있는 경우 안전한 경로로 조합
const safePath = `/profiles/${encodeURIComponent(imagePath)}`
return isValidImageUrl(safePath) ? safePath : null
}
React.useEffect(() => {
async function fetchUser() {
try {
const data = await findUserById(Number(userId))
if (data) {
form.reset({
name: data.user_name || "",
email: data.user_email || "",
imageFile: null,
})
// 안전한 이미지 URL 설정
const safeImageUrl = getSafeImageUrl(data.user_image)
setCurrentImageUrl(safeImageUrl)
setImageError(false)
setPreviewUrl(null)
}
} catch (error) {
console.error("Failed to fetch user data:", error)
}
}
if (userId) {
fetchUser()
}
}, [userId, form])
async function onSubmit(data: AccountFormValues) {
const { dirtyFields } = form.formState
if (Object.keys(dirtyFields).length === 0) {
toast({
title: "No changes",
description: "Nothing to update",
})
return
}
let imageFile: File | null = null
if (dirtyFields.imageFile && data.imageFile && data.imageFile.length > 0) {
const file = data.imageFile[0]
// 클라이언트 측 파일 검증
if (!isValidImageFile(file)) {
toast({
title: "Invalid file",
description: "Please select a valid image file (PNG, JPG, JPEG, WebP, max 5MB)",
variant: "destructive",
})
return
}
imageFile = file
}
const formData = new FormData()
formData.append("userId", userId)
formData.append("name", data.name)
formData.append("email", data.email)
if (imageFile) {
formData.append("file", imageFile)
}
try {
await updateUserProfileImage(formData)
toast({
title: "Account updated",
description: "User updated successfully!",
})
} catch (error: any) {
toast({
title: "Error",
description: `Error: ${error.message ?? error}`,
variant: "destructive",
})
}
}
// 파일 유효성 검증 함수
const isValidImageFile = (file: File): boolean => {
// 1. 파일 크기 검증 (5MB 제한)
const maxSize = 5 * 1024 * 1024 // 5MB
if (file.size > maxSize) {
return false
}
// 2. MIME 타입 검증
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
if (!allowedTypes.includes(file.type)) {
return false
}
// 3. 파일 확장자 검증 (추가 보안)
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.webp']
const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
if (!allowedExtensions.includes(fileExtension)) {
return false
}
return true
}
// 이미지 로드 에러 처리
const handleImageError = () => {
setImageError(true)
setCurrentImageUrl(null)
}
// 안전한 이미지 표시 함수
const getDisplayImage = () => {
if (previewUrl) {
return (
<img
src={previewUrl}
alt="Preview"
width={200}
className="rounded-lg object-cover"
onError={() => setPreviewUrl(null)}
/>
)
}
if (currentImageUrl && !imageError) {
return (
<img
src={currentImageUrl}
alt="Current profile"
width={200}
className="rounded-lg object-cover"
onError={handleImageError}
// 추가 보안: referrer policy 설정
referrerPolicy="no-referrer"
/>
)
}
return (
<div className="w-[200px] h-[200px] bg-gray-200 rounded-lg flex items-center justify-center">
<span className="text-gray-500">
{imageError ? "Image load failed" : "No image"}
</span>
</div>
)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is the name that will be displayed on your profile and in
emails.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="Your Email" {...field} />
</FormControl>
<FormDescription>
This is the email that will be used on login. If you want change it, please be careful.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="imageFile"
render={({ field }) => (
<FormItem>
<FormLabel>Profile Image</FormLabel>
<FormControl>
<div className="space-y-4">
<Input
type="file"
accept="image/jpeg,image/jpg,image/png,image/webp"
onChange={(e) => {
const files = e.target.files
field.onChange(files)
if (files && files.length > 0) {
const file = files[0]
// 파일 유효성 검증
if (!isValidImageFile(file)) {
toast({
title: "Invalid file",
description: "Please select a valid image file (PNG, JPG, JPEG, WebP, max 5MB)",
variant: "destructive",
})
// 파일 입력 초기화
e.target.value = ''
field.onChange(null)
return
}
if (previewUrl) {
URL.revokeObjectURL(previewUrl)
}
const url = URL.createObjectURL(file)
setPreviewUrl(url)
setImageError(false)
} else {
if (previewUrl) {
URL.revokeObjectURL(previewUrl)
}
setPreviewUrl(null)
}
}}
/>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
{getDisplayImage()}
</div>
{previewUrl && (
<p className="text-sm text-blue-600">새 이미지 미리보기</p>
)}
{!previewUrl && currentImageUrl && !imageError && (
<p className="text-sm text-gray-600">현재 프로필 이미지</p>
)}
{imageError && (
<p className="text-sm text-red-600">이미지를 불러올 수 없습니다</p>
)}
</div>
</FormControl>
<FormDescription>
Upload your profile image (PNG, JPG, JPEG, WebP, max 5MB).
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Update account</Button>
</form>
</Form>
)
}
|