-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp1.py
More file actions
531 lines (446 loc) · 16.2 KB
/
app1.py
File metadata and controls
531 lines (446 loc) · 16.2 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
# app.py
import os
from flask import Flask, render_template, request, jsonify, Blueprint, session
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import secrets
import re
# Initialize Flask app
app = Flask(__name__,
template_folder=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates'),
static_folder=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static')
)
# Configuration
app.config['SECRET_KEY'] = secrets.token_hex(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///advanced_blog.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Security headers middleware
@app.after_request
def set_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
return response
# Initialize database
db = SQLAlchemy(app)
# ===== ENHANCED MODELS =====
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
display_name = db.Column(db.String(100))
mobile_number = db.Column(db.String(20))
location = db.Column(db.String(100))
profile_picture = db.Column(db.String(200), default='/static/images/default-avatar.png')
bio = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
posts = db.relationship('Post', backref='author', lazy=True, cascade='all, delete-orphan')
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def to_dict(self):
return {
'id': self.id,
'username': self.username,
'email': self.email,
'display_name': self.display_name,
'mobile_number': self.mobile_number,
'location': self.location,
'profile_picture': self.profile_picture,
'bio': self.bio,
'created_at': self.created_at.isoformat() if self.created_at else None
}
def __repr__(self):
return f'<User {self.username}>'
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'content': self.content,
'created_at': self.created_at.isoformat(),
'updated_at': self.updated_at.isoformat(),
'author_id': self.user_id,
'author_username': self.author.username,
'author_display_name': self.author.display_name or self.author.username,
'author_profile_picture': self.author.profile_picture
}
def __repr__(self):
return f'<Post {self.title}>'
# ===== BLUEPRINTS =====
# Auth API Blueprint
auth_api = Blueprint('auth_api', __name__, url_prefix='/api/auth')
@auth_api.route('/register', methods=['POST'])
def register_user():
try:
data = request.get_json()
required_fields = ['username', 'password', 'email', 'display_name', 'mobile_number', 'location']
if not data or not all(data.get(field) for field in required_fields):
return jsonify({
'success': False,
'message': 'All fields are required'
}), 400
username = data['username']
email = data['email']
password = data['password']
display_name = data['display_name']
mobile_number = data['mobile_number']
location = data['location']
bio = data.get('bio', '')
# Validation
if len(username) < 3:
return jsonify({
'success': False,
'message': 'Username must be at least 3 characters long'
}), 400
if len(password) < 6:
return jsonify({
'success': False,
'message': 'Password must be at least 6 characters long'
}), 400
if User.query.filter_by(username=username).first():
return jsonify({
'success': False,
'message': 'Username already exists'
}), 409
if User.query.filter_by(email=email).first():
return jsonify({
'success': False,
'message': 'Email already exists'
}), 409
new_user = User(
username=username,
email=email,
display_name=display_name,
mobile_number=mobile_number,
location=location,
bio=bio
)
new_user.set_password(password)
db.session.add(new_user)
db.session.commit()
session['user_id'] = new_user.id
session['username'] = new_user.username
return jsonify({
'success': True,
'message': 'User registered successfully',
'user': new_user.to_dict()
}), 201
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Error registering user'
}), 500
@auth_api.route('/login', methods=['POST'])
def login_user():
try:
data = request.get_json()
if not data or not data.get('username') or not data.get('password'):
return jsonify({
'success': False,
'message': 'Username and password are required'
}), 400
username = data['username']
password = data['password']
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
session['user_id'] = user.id
session['username'] = user.username
return jsonify({
'success': True,
'message': 'Login successful',
'user': user.to_dict()
}), 200
else:
return jsonify({
'success': False,
'message': 'Invalid username or password'
}), 401
except Exception as e:
return jsonify({
'success': False,
'message': 'Error during login'
}), 500
@auth_api.route('/logout', methods=['POST'])
def logout_user():
session.pop('user_id', None)
session.pop('username', None)
return jsonify({
'success': True,
'message': 'Logout successful'
}), 200
@auth_api.route('/user', methods=['GET'])
def get_current_user():
if 'user_id' in session:
user = User.query.get(session['user_id'])
if user:
return jsonify({
'success': True,
'user': user.to_dict()
}), 200
return jsonify({
'success': False,
'message': 'Not logged in'
}), 401
@auth_api.route('/profile/update', methods=['PUT'])
def update_profile():
try:
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Please login'}), 401
user = User.query.get(session['user_id'])
if not user:
return jsonify({'success': False, 'message': 'User not found'}), 404
data = request.get_json()
if 'display_name' in data:
user.display_name = data['display_name']
if 'mobile_number' in data:
user.mobile_number = data['mobile_number']
if 'location' in data:
user.location = data['location']
if 'bio' in data:
user.bio = data['bio']
if 'profile_picture' in data:
user.profile_picture = data['profile_picture']
db.session.commit()
return jsonify({
'success': True,
'message': 'Profile updated successfully',
'user': user.to_dict()
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Error updating profile'
}), 500
# Blog API Blueprint
blog_api = Blueprint('blog_api', __name__, url_prefix='/api/posts')
@blog_api.route('/', methods=['GET'])
def get_all_posts():
try:
posts = Post.query.order_by(Post.created_at.desc()).all()
return jsonify({
'success': True,
'posts': [post.to_dict() for post in posts]
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': 'Error fetching posts'
}), 500
@blog_api.route('/my', methods=['GET'])
def get_my_posts():
try:
if 'user_id' not in session:
return jsonify({
'success': False,
'message': 'Please login to view your posts'
}), 401
user_posts = Post.query.filter_by(user_id=session['user_id']).order_by(Post.created_at.desc()).all()
return jsonify({
'success': True,
'posts': [post.to_dict() for post in user_posts]
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': 'Error fetching your posts'
}), 500
@blog_api.route('/<int:post_id>', methods=['GET'])
def get_post(post_id):
try:
post = Post.query.get_or_404(post_id)
return jsonify({
'success': True,
'post': post.to_dict()
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': 'Post not found'
}), 404
@blog_api.route('/', methods=['POST'])
def create_post():
try:
if 'user_id' not in session:
return jsonify({
'success': False,
'message': 'Please login to create a post'
}), 401
data = request.get_json()
if not data or not data.get('title') or not data.get('content'):
return jsonify({
'success': False,
'message': 'Title and content are required'
}), 400
user = User.query.get(session['user_id'])
if not user:
return jsonify({
'success': False,
'message': 'User not found'
}), 404
new_post = Post(
title=data['title'],
content=data['content'],
author=user
)
db.session.add(new_post)
db.session.commit()
return jsonify({
'success': True,
'message': 'Post created successfully',
'post': new_post.to_dict()
}), 201
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Error creating post'
}), 500
@blog_api.route('/<int:post_id>', methods=['PUT'])
def update_post(post_id):
try:
if 'user_id' not in session:
return jsonify({
'success': False,
'message': 'Please login to update a post'
}), 401
post = Post.query.get_or_404(post_id)
if post.user_id != session['user_id']:
return jsonify({
'success': False,
'message': 'You can only edit your own posts'
}), 403
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'No data provided'
}), 400
if 'title' in data:
post.title = data['title']
if 'content' in data:
post.content = data['content']
db.session.commit()
return jsonify({
'success': True,
'message': 'Post updated successfully',
'post': post.to_dict()
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Error updating post'
}), 500
@blog_api.route('/<int:post_id>', methods=['DELETE'])
def delete_post(post_id):
try:
if 'user_id' not in session:
return jsonify({
'success': False,
'message': 'Please login to delete a post'
}), 401
post = Post.query.get_or_404(post_id)
if post.user_id != session['user_id']:
return jsonify({
'success': False,
'message': 'You can only delete your own posts'
}), 403
db.session.delete(post)
db.session.commit()
return jsonify({
'success': True,
'message': 'Post deleted successfully'
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Error deleting post'
}), 500
# ===== REGISTER BLUEPRINTS =====
app.register_blueprint(auth_api)
app.register_blueprint(blog_api)
# ===== FRONTEND ROUTES =====
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login')
def login_view():
return render_template('login.html')
@app.route('/register')
def register_view():
return render_template('register.html')
@app.route('/dashboard')
def dashboard_view():
return render_template('dashboard.html')
@app.route('/create-post')
def create_post_view():
return render_template('create_post.html')
@app.route('/my-posts')
def my_posts_view():
return render_template('my_posts.html')
@app.route('/post/<int:post_id>')
def view_post(post_id):
return render_template('view_post.html', post_id=post_id)
@app.route('/edit/<int:post_id>')
def edit_post_view(post_id):
return render_template('edit_post.html', post_id=post_id)
# ADD THIS MISSING ROUTE:
@app.route('/profile')
def profile_view():
return render_template('profile.html')
# ===== CONTEXT PROCESSOR =====
@app.context_processor
def inject_user():
if 'user_id' in session:
user = User.query.get(session['user_id'])
if user:
return {'current_user': user}
return {'current_user': None}
# ===== DATABASE INITIALIZATION =====
def init_db():
with app.app_context():
db.create_all()
# Create default admin user if not exists
if not User.query.filter_by(username='admin').first():
admin = User(
username='admin',
email='admin@blog.com',
display_name='Administrator',
mobile_number='+1234567890',
location='Internet',
bio='I am the administrator of this awesome blog!'
)
admin.set_password('admin123')
db.session.add(admin)
db.session.commit()
print("✅ Default admin user created: admin/admin123")
else:
print("✅ Database already initialized")
# ===== ERROR HANDLER =====
@app.errorhandler(404)
def not_found(error):
return jsonify({
'success': False,
'message': 'Endpoint not found'
}), 404
# ===== MAIN APPLICATION =====
if __name__ == '__main__':
init_db()
print("🚀 Starting Advanced Blog Application...")
print("📍 Access: http://localhost:5000")
print("🔐 Default admin: admin / admin123")
print("👤 Profile: http://localhost:5000/profile")
app.run(debug=True, host='0.0.0.0', port=5000)