-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2983 lines (2532 loc) · 113 KB
/
Copy pathapp.py
File metadata and controls
2983 lines (2532 loc) · 113 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import eventlet
eventlet.monkey_patch()
import sqlite3
import uuid
import logging
from flask import Flask, render_template, request, redirect, url_for, session, flash, g, make_response, jsonify, send_from_directory
from flask_socketio import SocketIO, send, emit, join_room, leave_room
from datetime import datetime, timedelta
import os
import json
from functools import wraps
import hashlib
import re
from werkzeug.utils import secure_filename
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
import shutil
import time
from flask_bcrypt import Bcrypt
from flask_wtf.csrf import CSRFProtect
# 이미지 파일 확장자 설정
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'jfif', 'webp'}
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key' # 실제 운영 환경에서는 안전한 키로 변경해야 합니다
app.config['SESSION_COOKIE_NAME'] = 'market_session'
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SECURE'] = True # HTTPS 환경에서만 쿠키 전송 (프로덕션에서는 True로 설정)
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF 보호를 위한 SameSite 설정
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2) # 세션 만료 시간 설정
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 최대 업로드 크기 50MB
app.config['SESSION_TYPE'] = 'filesystem' # 세션 저장소 설정
app.config['MAX_LOGIN_ATTEMPTS'] = 5 # 로그인 실패 횟수 제한
app.config['LOGIN_TIMEOUT'] = 300 # 로그인 제한 시간(초)
app.config['WTF_CSRF_ENABLED'] = True # CSRF 보호 활성화
# CSRF 토큰을 헤더에서도 가져올 수 있도록 설정
app.config['WTF_CSRF_CHECK_DEFAULT'] = False
app.config['WTF_CSRF_HEADERS'] = ['X-CSRF-TOKEN']
# 데이터베이스 파일 경로 설정
DATABASE = 'market.db'
# bcrypt 및 CSRF 설정
bcrypt = Bcrypt(app)
csrf = CSRFProtect(app)
# 특정 경로에 대해 CSRF 보호 제외
csrf.exempt('/payment/create')
csrf.exempt('/payment/handle')
csrf.exempt('/notifications/mark-all-read')
csrf.exempt('/notifications/mark-read/<int:notification_id>')
# 로깅 설정 추가
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='app.log'
)
logger = logging.getLogger(__name__)
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# 통화 형식 필터 추가
def format_currency(value):
"""통화 형식으로 숫자를 포맷팅하는 필터"""
if value is None:
return '0'
try:
return "{:,}".format(float(value))
except (ValueError, TypeError):
return str(value)
# 날짜 형식 필터 추가
def datetime_format(value, format='%Y-%m-%d %H:%M:%S'):
"""날짜 형식을 포맷팅하는 필터"""
if value is None:
return ''
if isinstance(value, str):
try:
value = datetime.fromisoformat(value.replace('Z', '+00:00'))
except (ValueError, AttributeError):
try:
value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except (ValueError, AttributeError):
return value
try:
return value.strftime(format)
except (ValueError, AttributeError):
return str(value)
# Jinja 환경에 필터 등록
app.jinja_env.filters['format_currency'] = format_currency
app.jinja_env.filters['datetime'] = datetime_format
class User(UserMixin):
def __init__(self, id, username, password=None, is_admin=False, is_suspended=False):
self.id = id
self.username = username
self.password = password
self.is_admin = is_admin
self.is_suspended = is_suspended
def get_id(self):
return str(self.id)
@login_manager.user_loader
def load_user(user_id):
"""사용자 정보를 데이터베이스에서 로드하는 함수"""
db = get_db()
cursor = db.cursor()
try:
cursor.execute('SELECT * FROM user WHERE id = ?', (user_id,))
user = cursor.fetchone()
if user:
user_data = {
'id': user['id'] if 'id' in user else None,
'username': user['username'] if 'username' in user else None,
'email': user['email'] if 'email' in user else None,
'password': user['password'] if 'password' in user else None,
'created_at': user['created_at'] if 'created_at' in user else None,
'is_admin': user['is_admin'] if 'is_admin' in user else False,
'is_suspended': user['is_suspended'] if 'is_suspended' in user else False
}
return user_data
return None
except Exception as e:
print(f"사용자 로드 중 오류 발생: {str(e)}")
return None
# 로그인 필요 데코레이터
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash('로그인이 필요합니다.')
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def get_db():
"""데이터베이스 연결을 가져오거나 새로 생성합니다."""
if 'db' not in g:
g.db = sqlite3.connect(
DATABASE,
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
# SQLite 타입 어댑터 등록
def adapt_datetime(dt):
return dt.isoformat()
def convert_datetime(s):
try:
return datetime.fromisoformat(s.decode())
except:
return None
sqlite3.register_adapter(datetime, adapt_datetime)
sqlite3.register_converter("timestamp", convert_datetime)
return g.db
@app.teardown_appcontext
def close_connection(exception):
"""애플리케이션 컨텍스트가 종료될 때 데이터베이스 연결을 닫습니다."""
db = g.pop('db', None)
if db is not None:
try:
db.close()
except Exception as e:
print(f"데이터베이스 연결 종료 중 오류 발생: {e}")
def init_db():
"""데이터베이스를 초기화합니다."""
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
# 기본 라우트
@app.route('/')
def index():
return render_template('index.html')
# 비밀번호 해싱 유틸리티 함수
def hash_password(password):
"""비밀번호를 해싱하는 함수 (bcrypt 사용)"""
return bcrypt.generate_password_hash(password).decode('utf-8')
# 비밀번호 검증 유틸리티 함수
def verify_password(password, hashed_password):
"""비밀번호가 해시와 일치하는지 확인하는 함수 (bcrypt 사용)"""
# 기존 SHA-256 방식 (이전 계정 호환성 지원)
if len(hashed_password) == 64: # SHA-256 해시 길이
salt = app.config.get('SECRET_KEY', 'default-salt')
return hashlib.sha256((password + salt).encode()).hexdigest() == hashed_password
# bcrypt 방식
return bcrypt.check_password_hash(hashed_password, password)
# 로그인 시도 제한 함수 추가
def check_login_attempts(username):
"""로그인 시도 횟수 확인 및 제한 함수"""
current_time = datetime.now()
if username in login_attempts:
attempts, last_attempt_time = login_attempts[username]
# 제한 시간이 지났으면 초기화
if (current_time - last_attempt_time).total_seconds() > app.config['LOGIN_TIMEOUT']:
login_attempts[username] = (1, current_time)
return True
# 최대 시도 횟수를 초과하면 제한
if attempts >= app.config['MAX_LOGIN_ATTEMPTS']:
return False
# 시도 횟수 증가
login_attempts[username] = (attempts + 1, current_time)
return True
else:
login_attempts[username] = (1, current_time)
return True
# 세션 갱신 미들웨어 추가
@app.before_request
def session_management():
session.permanent = True
# 마지막 활동 시간 갱신
if 'user_id' in session:
session['last_activity'] = datetime.now().isoformat()
# 세션 만료 확인
if 'last_activity' in session:
last_activity = datetime.fromisoformat(session['last_activity'])
if (datetime.now() - last_activity) > timedelta(hours=2):
session.clear()
flash('세션이 만료되었습니다. 다시 로그인해주세요.')
return redirect(url_for('login'))
# 로그인
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username', '').strip()
password = request.form.get('password', '').strip()
if not username or not password:
flash('사용자명과 비밀번호를 모두 입력해주세요.')
return redirect(url_for('login'))
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT * FROM user WHERE username = ?", (username,))
user = cursor.fetchone()
if user is None:
flash('사용자를 찾을 수 없습니다.')
return redirect(url_for('login'))
user_id = user['id']
hashed_password = user['password']
if verify_password(password, hashed_password):
session.clear()
session['user_id'] = user_id
session['username'] = username
session['last_activity'] = datetime.now().isoformat()
# is_admin 값을 명시적으로 가져와 불리언으로 변환하여 세션에 저장
session['is_admin'] = bool(user['is_admin'])
session['is_suspended'] = bool(user['is_suspended']) if 'is_suspended' in user else False
print(f"로그인 성공: {username}, 관리자 권한: {session['is_admin']}")
return redirect(url_for('dashboard'))
else:
flash('비밀번호가 일치하지 않습니다.')
return redirect(url_for('login'))
return render_template('login.html')
# 로그아웃
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
# 세션 확인 미들웨어
@app.before_request
def check_session():
# 로그인, 회원가입, 정적 파일 요청은 세션 확인 제외
if request.endpoint in ['login', 'register', 'static', 'index'] or request.path.startswith('/static/'):
return
if 'user_id' not in session:
return redirect(url_for('login'))
# 사용자 정보를 g 객체에 저장
g.user_id = session['user_id']
g.username = session['username']
g.is_admin = session['is_admin']
g.is_suspended = session['is_suspended']
# 계정 정지 여부 확인
if g.is_suspended:
session.clear()
flash('계정이 정지되었습니다. 관리자에게 문의하세요.')
return redirect(url_for('login'))
# 대시보드: 사용자 정보와 전체 상품 리스트 표시
@app.route('/dashboard')
@login_required
def dashboard():
"""대시보드 페이지"""
# 세션 디버깅 정보 출력
print(f"현재 세션 정보: user_id={session.get('user_id')}, username={session.get('username')}, is_admin={session.get('is_admin')}")
db = None
try:
db = get_db()
cursor = db.cursor()
# 사용자 정보 조회
cursor.execute('''
SELECT id, username, email, created_at, is_admin
FROM user
WHERE id = ?
''', (session['user_id'],))
user = cursor.fetchone()
# 세션에 관리자 권한 정보 업데이트
if user and 'is_admin' in user:
session['is_admin'] = bool(user['is_admin'])
print(f"데이터베이스에서 불러온 is_admin 값: {user['is_admin']}, 세션에 저장된 값: {session['is_admin']}")
# 상품 목록 조회
cursor.execute('''
SELECT p.*, u.username as seller_name
FROM product p
JOIN user u ON p.seller_id = u.id
WHERE p.is_deleted = 0
ORDER BY p.created_at DESC
LIMIT 10
''')
products = cursor.fetchall()
# 전체 채팅 메시지 조회
cursor.execute('''
SELECT m.*, u.username as sender_name
FROM chat_message m
JOIN user u ON m.sender_id = u.id
WHERE m.room_id = 'global_chat'
ORDER BY m.created_at DESC
LIMIT 50
''')
global_messages = cursor.fetchall()
# 메시지의 시간 형식 처리
formatted_messages = []
for message in global_messages:
message_dict = dict(message)
if 'created_at' in message_dict and message_dict['created_at']:
# datetime이 문자열이 아닌 경우 형식화
if not isinstance(message_dict['created_at'], str):
try:
message_dict['created_at'] = message_dict['created_at'].strftime('%Y-%m-%d %H:%M:%S')
except (AttributeError, ValueError):
# 문자열로 변환한 후 마이크로초 제거
message_dict['created_at'] = str(message_dict['created_at']).split('.')[0]
formatted_messages.append(message_dict)
return render_template('dashboard.html',
user=user,
products=products,
global_messages=formatted_messages)
except Exception as e:
print(f"대시보드 로드 중 오류 발생: {str(e)}")
flash('대시보드를 불러오는 중 오류가 발생했습니다.')
return redirect(url_for('index'))
# 프로필 페이지: bio 업데이트 가능
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
db = get_db()
cursor = db.cursor()
if request.method == 'POST':
bio = request.form.get('bio', '')
current_password = request.form.get('current_password', '')
new_password = request.form.get('new_password', '')
confirm_password = request.form.get('confirm_password', '')
update_fields = []
update_values = []
# 바이오 업데이트
if bio:
update_fields.append("bio = ?")
update_values.append(bio)
# 비밀번호 변경
if current_password and new_password:
if len(new_password) < 7:
flash('새 비밀번호는 7자 이상이어야 합니다.')
return redirect(url_for('profile'))
if not re.match(r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{7,}$', new_password):
flash('새 비밀번호는 영문, 숫자, 특수문자를 포함해야 합니다.')
return redirect(url_for('profile'))
if new_password != confirm_password:
flash('새 비밀번호와 확인이 일치하지 않습니다.')
return redirect(url_for('profile'))
# 현재 비밀번호 확인
cursor.execute("SELECT password FROM user WHERE id = ?", (session['user_id'],))
user_password = cursor.fetchone()['password']
if not verify_password(current_password, user_password):
flash('현재 비밀번호가 올바르지 않습니다.')
return redirect(url_for('profile'))
# 새 비밀번호 해싱
hashed_password = hash_password(new_password)
update_fields.append("password = ?")
update_values.append(hashed_password)
flash('비밀번호가 성공적으로 변경되었습니다.')
elif current_password or new_password or confirm_password:
flash('비밀번호를 변경하려면 현재 비밀번호와 새 비밀번호를 모두 입력해야 합니다.')
return redirect(url_for('profile'))
if update_fields:
update_fields.append("updated_at = datetime('now')")
update_sql = f"UPDATE user SET {', '.join(update_fields)} WHERE id = ?"
update_values.append(session['user_id'])
cursor.execute(update_sql, update_values)
db.commit()
flash('프로필이 업데이트되었습니다.')
return redirect(url_for('profile'))
# 사용자 정보 조회
cursor.execute("SELECT * FROM user WHERE id = ?", (session['user_id'],))
user = cursor.fetchone()
# 사용자의 상품 목록 가져오기
cursor.execute('''
SELECT p.id, p.title, p.price, p.created_at, u.username as seller_name
FROM product p
JOIN user u ON p.seller_id = u.id
WHERE p.seller_id = ? AND p.is_deleted = 0 AND p.id IS NOT NULL
ORDER BY p.created_at DESC
''', (session['user_id'],))
products = [dict(row) for row in cursor.fetchall()]
# 디버깅을 위한 로그 추가
app.logger.debug(f"조회된 상품 목록: {products}")
app.logger.debug(f"상품 개수: {len(products)}")
if products:
app.logger.debug(f"첫 번째 상품의 ID: {products[0]['id']}")
# 송금 내역
cursor.execute("""
SELECT p.*,
u1.username as sender_name,
u2.username as receiver_name
FROM payment p
JOIN user u1 ON p.sender_id = u1.id
JOIN user u2 ON p.receiver_id = u2.id
WHERE p.sender_id = ? OR p.receiver_id = ?
ORDER BY p.created_at DESC
""", (session['user_id'], session['user_id']))
payments = cursor.fetchall()
# 신고 내역
cursor.execute("""
SELECT r.*,
CASE
WHEN r.target_type = 'user' THEN u.username
WHEN r.target_type = 'product' THEN p.title
END as target_name,
r.target_type
FROM report r
LEFT JOIN user u ON r.target_id = u.id AND r.target_type = 'user'
LEFT JOIN product p ON r.target_id = p.id AND r.target_type = 'product'
WHERE r.reporter_id = ?
ORDER BY r.created_at DESC
""", (session['user_id'],))
reports = cursor.fetchall()
return render_template('profile.html',
user=user,
products=products,
payments=payments,
reports=reports)
# 이미지 파일 확장자 체크 함수
def allowed_file(filename):
if not filename:
return False
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def optimize_image(image_path, max_size=(800, 800), quality=85):
from PIL import Image, ExifTags
import os
try:
img = Image.open(image_path)
# EXIF 정보에서 방향 정보 추출 및 이미지 회전 처리
try:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif = dict(img._getexif().items())
if orientation in exif:
if exif[orientation] == 2:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif exif[orientation] == 3:
img = img.transpose(Image.ROTATE_180)
elif exif[orientation] == 4:
img = img.transpose(Image.FLIP_TOP_BOTTOM)
elif exif[orientation] == 5:
img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_90)
elif exif[orientation] == 6:
img = img.transpose(Image.ROTATE_270)
elif exif[orientation] == 7:
img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_270)
elif exif[orientation] == 8:
img = img.transpose(Image.ROTATE_90)
except (AttributeError, KeyError, IndexError):
# EXIF 정보가 없는 경우 무시
pass
try:
# 최신 PIL 버전용
img.thumbnail(max_size, Image.Resampling.LANCZOS)
except AttributeError:
# 이전 PIL 버전용
img.thumbnail(max_size, Image.LANCZOS if hasattr(Image, 'LANCZOS') else Image.ANTIALIAS)
# 이미지 최적화
if img.mode in ('RGBA', 'LA'):
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1])
img = background
# 이미지 저장
img.save(image_path, 'JPEG', quality=quality, optimize=True)
return True
except Exception as e:
print(f"이미지 최적화 중 오류 발생: {e}")
return False
def validate_image_file(file):
"""이미지 파일 검증 함수"""
if not file or not file.filename:
return False, '이미지 파일을 선택해주세요.'
if not allowed_file(file.filename):
return False, '이미지는 JPG, JPEG, PNG, GIF 형식만 가능합니다.'
# 파일 크기 검증 - 10MB로 제한
if file.content_length > 10 * 1024 * 1024:
return False, '이미지 크기는 10MB를 초과할 수 없습니다.'
try:
from PIL import Image
# 파일 포인터를 처음으로 되돌림
file.seek(0)
img = Image.open(file)
# 이미지가 실제로 로드 가능한지 확인
img.verify()
# 파일 포인터를 다시 처음으로 되돌림
file.seek(0)
return True, None
except Exception as e:
print(f"이미지 검증 오류: {e}")
return False, f'이미지 파일이 손상되었거나 올바르지 않습니다: {str(e)}'
def save_image(file):
"""이미지 파일 저장 함수"""
try:
# 파일 포인터를 처음으로 되돌림
file.seek(0)
file_ext = os.path.splitext(file.filename)[1].lower()
unique_filename = f"{uuid.uuid4()}{file_ext}"
image_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
# 업로드 폴더가 없으면 생성
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# 이미지 저장
file.save(image_path)
# 이미지 최적화
if optimize_image(image_path):
return unique_filename
else:
# 최적화 실패 시 원본 파일 삭제
os.remove(image_path)
return None
except Exception as e:
print(f"이미지 저장 오류: {e}")
return None
# 상품 등록
@app.route('/add_product', methods=['GET', 'POST'])
@login_required
def add_product():
if request.method == 'POST':
title = sanitize_input(request.form.get('title', '').strip())
price = request.form.get('price', '').strip()
description = sanitize_input(request.form.get('description', '').strip())
# 필수 필드 검증
if not title or not price or not description:
flash('모든 필드를 입력해주세요.')
return redirect(url_for('add_product'))
# 제목 길이 제한
if len(title) > 100:
flash('제목은 100자 이내로 입력해주세요.')
return redirect(url_for('add_product'))
try:
price = float(price)
if price <= 0:
flash('가격은 0보다 커야 합니다.')
return redirect(url_for('add_product'))
if price > 1000000000: # 10억원 제한
flash('가격이 너무 높습니다.')
return redirect(url_for('add_product'))
except ValueError:
flash('유효한 가격을 입력해주세요.')
return redirect(url_for('add_product'))
# 이미지 업로드 처리
image_urls = []
# request.files 디버깅
print(f"요청에 포함된 파일들: {list(request.files.keys())}")
# 'images' 키로 파일 목록 가져오기
uploaded_files = request.files.getlist('images')
print(f"업로드된 파일 수: {len(uploaded_files)}")
for file in uploaded_files:
if file and file.filename:
print(f"업로드 시도: {file.filename}") # 디버깅
try:
# 파일 확장자 확인
if not allowed_file(file.filename):
print(f"허용되지 않는 파일 형식: {file.filename}")
flash(f'허용되지 않는 파일 형식입니다: {file.filename}')
continue
# 이미지 처리 함수 호출
filename, error = process_image_upload(file)
if filename:
image_urls.append(filename)
elif error:
flash(error)
except Exception as e:
print(f"예외 발생: {str(e)}") # 디버깅
flash(f'이미지 처리 중 오류가 발생했습니다: {str(e)}')
if len(image_urls) == 0:
print("업로드된 이미지가 없습니다")
flash('최소한 한 개의 이미지를 업로드해야 합니다.')
return redirect(url_for('add_product'))
try:
db = get_db()
cursor = db.cursor()
# UUID를 사용하여 product_id 생성
product_id = str(uuid.uuid4())
# 이미지가 있는 경우 첫 번째 이미지를 메인 이미지로 설정
main_image = image_urls[0] if image_urls else None
cursor.execute('''
INSERT INTO product (id, title, price, description, seller_id, image_url)
VALUES (?, ?, ?, ?, ?, ?)
''', (product_id, title, price, description, session['user_id'], main_image))
# 추가 이미지가 있는 경우 저장
for image_url in image_urls[1:]:
cursor.execute('''
INSERT INTO product_images (product_id, image_url)
VALUES (?, ?)
''', (product_id, image_url))
db.commit()
flash('상품이 등록되었습니다.')
return redirect(url_for('view_product', product_id=product_id))
except Exception as e:
db.rollback()
flash('상품 등록 중 오류가 발생했습니다.')
print(f"상품 등록 오류: {str(e)}")
return redirect(url_for('add_product'))
return render_template('add_product.html')
# 상품 상세보기
@app.route('/view_product/<string:product_id>')
def view_product(product_id):
try:
db = get_db()
cursor = db.cursor()
# 상품 정보 조회
cursor.execute('''
SELECT p.*, u.username as seller_name, u.report_count as seller_report_count
FROM product p
JOIN user u ON p.seller_id = u.id
WHERE p.id = ? AND p.is_deleted = 0
''', (product_id,))
product = cursor.fetchone()
if not product:
flash('존재하지 않는 상품입니다.')
return redirect(url_for('dashboard'))
# 상품에 대한 신고 횟수 조회
cursor.execute('''
SELECT COUNT(*) as report_count
FROM report
WHERE target_type = 'product' AND target_id = ?
''', (product_id,))
product_report = cursor.fetchone()
product_report_count = product_report['report_count'] if product_report else 0
# 추가 이미지 조회
cursor.execute('''
SELECT image_url FROM product_images
WHERE product_id = ?
ORDER BY created_at
''', (product_id,))
images = [row['image_url'] for row in cursor.fetchall()]
return render_template('view_product.html',
product=product,
images=images,
product_report_count=product_report_count)
except Exception as e:
print(f"상품 조회 중 오류 발생: {str(e)}")
flash('상품을 불러오는 중 오류가 발생했습니다.')
return redirect(url_for('dashboard'))
# 상품 수정
@app.route('/edit_product/<string:product_id>', methods=['GET', 'POST'])
@login_required
def edit_product(product_id):
db = get_db()
cursor = db.cursor()
# 제품 정보 조회
cursor.execute("""
SELECT p.*, GROUP_CONCAT(pi.image_url) as image_urls
FROM product p
LEFT JOIN product_images pi ON p.id = pi.product_id
WHERE p.id = ?
GROUP BY p.id
""", (product_id,))
product = cursor.fetchone()
if not product:
flash('존재하지 않는 제품입니다.')
return redirect(url_for('dashboard'))
# 현재 사용자가 판매자인지 확인
if product['seller_id'] != session['user_id']:
flash('자신의 제품만 수정할 수 있습니다.')
return redirect(url_for('dashboard'))
if request.method == 'POST':
title = request.form['title']
price = request.form['price']
description = request.form['description']
# 필수 필드 검증
if not title or not price or not description:
flash('모든 필드를 입력해주세요.')
return redirect(url_for('edit_product', product_id=product_id))
try:
price = float(price)
if price <= 0:
flash('가격은 0보다 커야 합니다.')
return redirect(url_for('edit_product', product_id=product_id))
except ValueError:
flash('유효한 가격을 입력해주세요.')
return redirect(url_for('edit_product', product_id=product_id))
try:
# 제품 정보 업데이트
cursor.execute("""
UPDATE product
SET title = ?, price = ?, description = ?, updated_at = datetime('now')
WHERE id = ?
""", (title, price, description, product_id))
# 새로운 이미지 업로드 처리
new_images = request.files.getlist('images')
for file in new_images:
if file and file.filename:
filename, error = process_image_upload(file)
if filename:
cursor.execute("""
INSERT INTO product_images (product_id, image_url)
VALUES (?, ?)
""", (product_id, filename))
elif error:
flash(error)
# 삭제할 이미지 처리
delete_images = request.form.getlist('delete_images')
if delete_images:
for image_url in delete_images:
# 파일 시스템에서 이미지 삭제
image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_url)
if os.path.exists(image_path):
os.remove(image_path)
# 데이터베이스에서 이미지 레코드 삭제
cursor.execute("DELETE FROM product_images WHERE product_id = ? AND image_url = ?",
(product_id, image_url))
db.commit()
flash('제품이 성공적으로 수정되었습니다.')
return redirect(url_for('view_product', product_id=product_id))
except Exception as e:
db.rollback()
flash('제품 수정 중 오류가 발생했습니다.')
print(f"Error updating product: {e}")
return redirect(url_for('edit_product', product_id=product_id))
# GET 요청 처리
images = []
if product['image_urls']:
images = product['image_urls'].split(',')
return render_template('edit_product.html', product=product, images=images)
# 상품 삭제
@app.route('/delete_product/<string:product_id>', methods=['POST'])
@login_required
def delete_product(product_id):
db = get_db()
cursor = db.cursor()
# 제품 정보 조회
cursor.execute("SELECT seller_id FROM product WHERE id = ?", (product_id,))
product = cursor.fetchone()
if not product:
flash('존재하지 않는 제품입니다.')
return redirect(url_for('dashboard'))
# 현재 사용자가 판매자인지 확인
if product['seller_id'] != session['user_id']:
flash('자신의 제품만 삭제할 수 있습니다.')
return redirect(url_for('dashboard'))
try:
# 제품 이미지 삭제
cursor.execute("SELECT image_url FROM product_images WHERE product_id = ?", (product_id,))
images = cursor.fetchall()
for image in images:
image_path = os.path.join(app.config['UPLOAD_FOLDER'], image['image_url'])
if os.path.exists(image_path):
os.remove(image_path)
# 제품 이미지 레코드 삭제
cursor.execute("DELETE FROM product_images WHERE product_id = ?", (product_id,))
# 제품 삭제
cursor.execute("DELETE FROM product WHERE id = ?", (product_id,))
db.commit()
flash('제품이 삭제되었습니다.')
except Exception as e:
db.rollback()
flash('제품 삭제 중 오류가 발생했습니다.')
print(f"Error deleting product: {e}")
return redirect(url_for('dashboard'))
# 채팅방 생성 또는 찾기 함수
def get_or_create_chat_room(user1_id, user2_id, product_id=None):
"""
두 사용자 간의 채팅방을 가져오거나 생성합니다.
product_id가 제공되면 해당 상품에 대한 채팅방을 생성합니다.
"""
db = get_db()
cursor = db.cursor()
try:
# product_id가 있는 경우 해당 상품에 대한 채팅방 조회
if product_id:
cursor.execute('''
SELECT cr.id FROM chat_room cr
JOIN chat_participant cp1 ON cr.id = cp1.room_id
JOIN chat_participant cp2 ON cr.id = cp2.room_id
WHERE cp1.user_id = ? AND cp2.user_id = ? AND cr.product_id = ?
AND cp1.user_id != cp2.user_id
''', (user1_id, user2_id, product_id))
else:
# 기존 방식대로 사용자 간 채팅방 조회 (product_id가 NULL인 경우)
cursor.execute('''
SELECT cr.id FROM chat_room cr
JOIN chat_participant cp1 ON cr.id = cp1.room_id
JOIN chat_participant cp2 ON cr.id = cp2.room_id
WHERE cp1.user_id = ? AND cp2.user_id = ? AND cr.product_id IS NULL
AND cp1.user_id != cp2.user_id
''', (user1_id, user2_id))
chat_room = cursor.fetchone()
if chat_room:
return chat_room['id']
# 채팅방이 없는 경우 새로 생성
room_id = str(uuid.uuid4())
cursor.execute('''
INSERT INTO chat_room (id, created_at, product_id)
VALUES (?, datetime('now'), ?)
''', (room_id, product_id))
# 참여자 추가
cursor.execute('''
INSERT INTO chat_participant (room_id, user_id, joined_at)
VALUES (?, ?, datetime('now'))
''', (room_id, user1_id))
cursor.execute('''
INSERT INTO chat_participant (room_id, user_id, joined_at)
VALUES (?, ?, datetime('now'))
''', (room_id, user2_id))
db.commit()
return room_id
except Exception as e:
print(f"채팅방 생성 중 오류 발생: {str(e)}")
db.rollback()
return None
# 상품 검색
@app.route('/search')
@login_required
def search():
keyword = request.args.get('keyword', '')
db = get_db()
cursor = db.cursor()
# 키워드로 상품 검색
cursor.execute("""
SELECT p.*, u.username as seller_name
FROM product p
JOIN user u ON p.seller_id = u.id
WHERE (p.title LIKE ? OR p.description LIKE ?) AND p.is_deleted = 0
""", (f'%{keyword}%', f'%{keyword}%'))
products = cursor.fetchall()
return render_template('search_results.html', products=products, keyword=keyword)
# 이미지 유효성 검사 및 저장 함수
def process_image_upload(file, max_size=10*1024*1024):
"""이미지 파일 검증 및 저장 통합 함수"""
if not file or not file.filename:
return None, '이미지 파일을 선택해주세요.'
# 파일 확장자 검증
if not allowed_file(file.filename):
return None, '이미지는 JPG, JPEG, PNG, GIF 형식만 가능합니다.'
try:
# 파일 크기 검증 - 명시적으로 10MB 제한
file.seek(0, os.SEEK_END)
file_size = file.tell()
file.seek(0)
if file_size > max_size: # 10MB
return None, '이미지 크기는 10MB를 초과할 수 없습니다.'