-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
461 lines (396 loc) · 16.6 KB
/
main.py
File metadata and controls
461 lines (396 loc) · 16.6 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
import pymysql
pymysql.install_as_MySQLdb()
from flask import Flask, render_template, request, redirect, url_for, flash,session
import mysql.connector
from flask_socketio import SocketIO, emit
import subprocess
from datetime import datetime, timedelta
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
import threading
import os
project_dir = '/Volumes/Data/Laptrinh/App/blogweb'
app = Flask(__name__,template_folder=os.path.join(project_dir, 'templates'), static_folder=None)
app.secret_key = 'your_secret_key'
socketio = SocketIO(app,async_mode='gevent')
# Cấu hình cơ sở dữ liệu
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@127.0.0.1:3306/blog_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Cấu hình Flask-Session sử dụng SQLAlchemy
app.config['SESSION_TYPE'] = 'sqlalchemy'
app.config['SESSION_SQLALCHEMY'] = SQLAlchemy(app) # Liên kết với SQLAlchemy
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_KEY_PREFIX'] = 'your_prefix:'
# Khởi tạo SQLAlchemy và Flask-Session
Session(app)
config = {
'user': 'root',
'password': '',
'host': '127.0.0.1',
'port': 3306,
'database': 'blog_db',
'raise_on_warnings': True,
'auth_plugin': 'mysql_native_password'
}
def get_db_connection():
return mysql.connector.connect(**config)
def tao_bang():
# Tạo bảng nếu chưa tồn tại
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('admin', 'user') DEFAULT 'user',
locked_until DATETIME DEFAULT NULL, ALGORITHM=INPLACE, LOCK=NONE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
edited_content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INT,
approved BOOLEAN DEFAULT FALSE,
FOREIGN KEY (user_id) REFERENCES users(id), ALGORITHM=INPLACE, LOCK=NONE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id), ALGORITHM=INPLACE, LOCK=NONE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS post_history (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT,
edited_by VARCHAR(50),
edited_content TEXT,
edited_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id), ALGORITHM=INPLACE, LOCK=NONE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(255) NOT NULL UNIQUE,
data LONGBLOB NOT NULL, -- Dùng LONGBLOB để lưu trữ dữ liệu nhị phân
expiry DATETIME NOT NULL, ALGORITHM=INPLACE, LOCK=NONE
);
''')
cursor.execute('''
ALTER TABLE users DROP INDEX username, ALGORITHM=INPLACE, LOCK=NONE;
ALTER TABLE users MODIFY username VARCHAR(255) NOT NULL UNIQUE, ALGORITHM=INPLACE, LOCK=NONE;
''')
connection.commit()
except mysql.connector.Error as err:
app.logger.error(f"Error creating tables: {err}")
finally:
cursor.close()
connection.close()
# Danh sách từ bậy
BAD_WORDS = ['xạo', 'dởm', 'bẩn', 'hư', 'ngu', 'đểu']
@app.errorhandler(404)
def page_not_found(s):
# Render trang HTML tùy chỉnh hoặc trả JSON
return render_template('404.html'), 404
@app.before_request
def before_request():
# Nếu yêu cầu không phải là HTTPS (request.is_secure)
if not request.is_secure:
return redirect(request.url.replace("http://", "https://"), code=301)
@app.route('/')
def index():
if 'username' in session:
username = session['username']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT locked_until FROM users WHERE username = %s', (username,))
user = cursor.fetchone()
cursor.close()
connection.close()
if user and user['locked_until'] == 'LOCKED':
return "Tài khoản của bạn đã bị khóa. Vui lòng thử lại sau."
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM posts ORDER BY created_at DESC')
posts = cursor.fetchall()
cursor.close()
connection.close()
return render_template('index.html', posts=posts)
@app.route('/add_post', methods=['GET', 'POST'])
def add_post():
if 'username' not in session:
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
username = session['username']
if any(word in title.lower() for word in BAD_WORDS) or any(word in content.lower() for word in BAD_WORDS):
flash("Bài viết chứa từ không phù hợp. Vui lòng sửa lại.")
return redirect(url_for('add_post'))
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
'INSERT INTO posts (title, content, user_id) VALUES (%s, %s, (SELECT id FROM users WHERE username = %s))',
(title, content, username)
)
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('index'))
return render_template('add_post.html')
@app.route('/post_detail/<int:post_id>', methods=['GET', 'POST'])
def post_detail(post_id):
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('''
SELECT posts.*, users.username
FROM posts
JOIN users ON posts.user_id = users.id
WHERE posts.id = %s, ALGORITHM=INPLACE, LOCK=NONE
''', (post_id,))
post = cursor.fetchone()
if not post:
return "Bài viết không tồn tại", 404
if request.method == 'POST':
if 'username' not in session:
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
content = request.form.get('content', '')
cursor.execute(
'INSERT INTO comments (post_id, username, content) VALUES (%s, %s, %s), ALGORITHM=INPLACE, LOCK=NONE',
(post_id, session['username'], content)
)
connection.commit()
cursor.execute('SELECT * FROM comments WHERE post_id = %s ORDER BY created_at, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
comments = cursor.fetchall()
cursor.execute('SELECT * FROM post_history WHERE post_id = %s ORDER BY edited_at DESC, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
history = cursor.fetchall()
cursor.close()
connection.close()
return render_template('post_detail.html', post=post, comments=comments, history=history)
# Route cho trang terminal
@app.route('/terminal')
def terminal():
if 'username' not in session or session['username'] != 'admin':
return render_template('404.html')
return render_template('terminal.html')
@app.route('/delete_post/<int:post_id>', methods=['POST'])
def delete_post(post_id):
if 'username' not in session:
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
connection = get_db_connection()
cursor = connection.cursor()
# Xóa các bình luận liên quan đến bài viết trước khi xóa bài viết
cursor.execute('DELETE FROM comments WHERE post_id = %s, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
# Xóa lịch sử bài viết
cursor.execute('DELETE FROM post_history WHERE post_id = %s, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
# Xóa bài viết
cursor.execute('DELETE FROM posts WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
user = cursor.fetchone()
cursor.close()
connection.close()
# So sánh mật khẩu trực tiếp (không mã hóa)
if user and user['password'] == password:
session['username'] = username
session['role'] = user['role']
return redirect(url_for('index'))
else:
flash("Tên đăng nhập hoặc mật khẩu không đúng")
return render_template('login.html')
@app.route('/logout')
def logout():
# Xóa session trong ứng dụng
session.pop('username', None)
session.pop('role', None)
response = redirect(url_for('index'))
return response
@app.route('/shop')
def shop():
return render_template('shop.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
role = request.form.get('role', 'user')
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('INSERT INTO users (username, password, role) VALUES (%s, %s, %s), ALGORITHM=INPLACE, LOCK=NONE', (username, password, role))
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/manage_users', methods=['GET', 'POST'])
def manage_users():
# Kiểm tra quyền truy cập của người dùng
if 'username' not in session or session['username'] != 'admin':
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
if request.method == 'POST':
if 'delete_user' in request.form:
user_id_to_delete = request.form['delete_user']
cursor.execute('DELETE FROM users WHERE id = %s,, ALGORITHM=INPLACE, LOCK=NONE', (user_id_to_delete,))
connection.commit()
flash("Người dùng đã được xóa.")
if 'change_role' in request.form:
user_id = request.form['user_id']
new_role = request.form['new_role']
cursor.execute('UPDATE users SET role = %s WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE', (new_role, user_id))
connection.commit()
flash("Vai trò người dùng đã được cập nhật.")
if 'lock_user' in request.form:
user_id_to_lock = request.form['lock_user']
# Khóa tài khoản bằng cách đặt giá trị 'LOCKED'
cursor.execute('UPDATE users SET locked_until = %s WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE', ('LOCKED', user_id_to_lock))
connection.commit()
flash("Tài khoản đã bị khóa.")
if 'unlock_user' in request.form:
user_id_to_unlock = request.form['unlock_user']
cursor.execute('UPDATE users SET locked_until = NULL WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE', (user_id_to_unlock,))
connection.commit()
flash("Tài khoản đã được bỏ khóa.")
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
cursor.close()
connection.close()
return render_template('manage_users.html', users=users)
def get_post_by_id(post_id):
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('''
SELECT posts.*, users.username
FROM posts
JOIN users ON posts.user_id = users.id
WHERE posts.id = %s, ALGORITHM=INPLACE, LOCK=NONE
''', (post_id,))
post = cursor.fetchone()
cursor.close()
connection.close()
return post
def approve_post(post_id):
connection = get_db_connection()
cursor = connection.cursor()
try:
# Cập nhật nội dung chính thức từ nội dung chỉnh sửa
cursor.execute(
'UPDATE posts SET content = edited_content, edited_content = NULL, approved = TRUE WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE',
(post_id,)
)
connection.commit()
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
connection.close()
@app.route('/approve_edit/<int:post_id>', methods=['POST'])
def approve_edit(post_id):
post = get_post_by_id(post_id) # Lấy bài viết từ cơ sở dữ liệu
if post:
post_username = post.get('username')
session_username = session.get('username')
session_role = session.get('role')
if session_role == 'admin' or post_username == session_username:
approve_post(post_id)
flash('Bài viết đã được phê duyệt!')
else:
flash('Bạn không có quyền để phê duyệt bài viết này.')
else:
flash('Bài viết không tồn tại.')
return redirect(url_for('post_detail', post_id=post_id))
@app.route('/delete_comment/<int:comment_id>', methods=['POST'])
def delete_comment(comment_id):
if 'username' not in session:
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('DELETE FROM comments WHERE id = %s AND username = %s, ALGORITHM=INPLACE, LOCK=NONE', (comment_id, session['username']))
connection.commit()
cursor.close()
connection.close()
return redirect(request.referrer) # Quay lại trang trước đó
@app.route('/edit_post/<int:post_id>', methods=['GET', 'POST'])
def edit_post(post_id):
if 'username' not in session:
flash("Bạn không có quyền thực hiện hành động này")
return redirect(url_for('index'))
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
if request.method == 'GET':
cursor.execute('SELECT * FROM posts WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE', (post_id,))
post = cursor.fetchone()
if not post:
cursor.close()
connection.close()
return "Bài viết không tồn tại", 404
post_content = post['content']
cursor.close()
connection.close()
return render_template('edit_post.html', post=post, post_content=post_content)
if request.method == 'POST':
content = request.form.get('content', '')
cursor.execute(
'INSERT INTO post_history (post_id, edited_by, edited_content) VALUES (%s, %s, %s), ALGORITHM=INPLACE, LOCK=NONE',
(post_id, session['username'], content)
)
cursor.execute(
'UPDATE posts SET edited_content = %s, approved = FALSE WHERE id = %s, ALGORITHM=INPLACE, LOCK=NONE',
(content, post_id)
)
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('post_detail', post_id=post_id))
def run_command(command):
"""Thực thi lệnh và gửi output từng dòng về client."""
process = subprocess.Popen(
command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True
)
for line in iter(process.stdout.readline, ''):
socketio.emit('command_response', {'result': line})
process.stdout.close()
process.wait()
@socketio.on('execute_command')
def handle_execute_command(data):
command = data.get('command')
if not command:
emit('command_response', {'error': 'No command received\n'})
return
thread = threading.Thread(target=run_command, args=(command,))
thread.start()
if __name__ == '__main__':
#tao_bang() bỏ # nếu ko có bảng
socketio.run(app,host='0.0.0.0',certfile="localhost.crt", keyfile="localhost.key")