41 lines
1.5 KiB
Python
41 lines
1.5 KiB
Python
from flask import abort
|
|
from flask_jwt_extended import get_jwt_identity
|
|
from models import User, db
|
|
import os
|
|
from werkzeug.security import generate_password_hash
|
|
|
|
|
|
def admin_required(user_id, message='Access denied.'):
|
|
user = db.session.get(User, user_id)
|
|
if user is None or user.role != "Administrator":
|
|
abort(403, message)
|
|
|
|
|
|
def validate_access(owner_id, message='Access denied.'):
|
|
# Check if user try to access or edit resource that does not belong to them
|
|
logged_user_id = int(get_jwt_identity())
|
|
logged_user_role = db.session.get(User, logged_user_id).role
|
|
if logged_user_role != "Administrator" and logged_user_id != owner_id:
|
|
abort(403, message)
|
|
|
|
|
|
def get_user_or_404(user_id):
|
|
"Get user from database or abort 404"
|
|
user = db.session.get(User, user_id)
|
|
if user is None:
|
|
abort(404, "User not found")
|
|
return user
|
|
|
|
|
|
def init_db():
|
|
"""Create default admin account if database is empty"""
|
|
with db.session.begin():
|
|
if not User.query.first(): # Check if user table is empty
|
|
admin_username = os.getenv("ADMIN_USERNAME", "admin")
|
|
admin_email = os.getenv("ADMIN_EMAIL", "admin@example.pl")
|
|
admin_password = os.getenv("ADMIN_PASSWORD", "admin")
|
|
hashed_password = generate_password_hash(admin_password)
|
|
admin = User(username=admin_username, email=admin_email, password=hashed_password, role='Administrator')
|
|
db.session.add(admin)
|
|
db.session.commit()
|