fixed some issues with profile and events

This commit is contained in:
2025-05-29 22:40:59 +02:00
parent 8f24e21d5d
commit 37fcc5f34c
7 changed files with 79 additions and 18 deletions

2
app.py
View File

@@ -35,7 +35,7 @@ def create_app():
@app.context_processor @app.context_processor
def inject_csrf_token(): def inject_csrf_token():
return dict(csrf_token=generate_csrf()) return dict(csrf_token=lambda: generate_csrf())
@app.context_processor @app.context_processor
def inject_config(): def inject_config():

View File

@@ -270,8 +270,12 @@ def init_routes(main_bp):
@require_password_change @require_password_change
def profile(): def profile():
if request.method == 'POST': if request.method == 'POST':
logger.debug(f"Profile form submitted with data: {request.form}")
logger.debug(f"Files in request: {request.files}")
# Handle profile picture removal # Handle profile picture removal
if 'remove_picture' in request.form: if 'remove_picture' in request.form:
logger.debug("Removing profile picture")
if current_user.profile_picture: if current_user.profile_picture:
# Delete the old profile picture file # Delete the old profile picture file
old_picture_path = os.path.join(UPLOAD_FOLDER, current_user.profile_picture) old_picture_path = os.path.join(UPLOAD_FOLDER, current_user.profile_picture)
@@ -283,6 +287,7 @@ def init_routes(main_bp):
return redirect(url_for('main.profile')) return redirect(url_for('main.profile'))
new_email = request.form.get('email') new_email = request.form.get('email')
logger.debug(f"New email: {new_email}")
# Check if the new email is already used by another user # Check if the new email is already used by another user
if new_email != current_user.email: if new_email != current_user.email:
existing_user = User.query.filter_by(email=new_email).first() existing_user = User.query.filter_by(email=new_email).first()
@@ -292,6 +297,7 @@ def init_routes(main_bp):
# Handle profile picture upload # Handle profile picture upload
file = request.files.get('profile_picture') file = request.files.get('profile_picture')
if file and file.filename: if file and file.filename:
logger.debug(f"Uploading new profile picture: {file.filename}")
filename = secure_filename(file.filename) filename = secure_filename(file.filename)
file_path = os.path.join(UPLOAD_FOLDER, filename) file_path = os.path.join(UPLOAD_FOLDER, filename)
file.save(file_path) file.save(file_path)
@@ -304,22 +310,62 @@ def init_routes(main_bp):
current_user.company = request.form.get('company') current_user.company = request.form.get('company')
current_user.position = request.form.get('position') current_user.position = request.form.get('position')
current_user.notes = request.form.get('notes') current_user.notes = request.form.get('notes')
logger.debug(f"Updated user data: username={current_user.username}, last_name={current_user.last_name}, email={current_user.email}")
# Handle password change if provided # Handle password change if provided
new_password = request.form.get('new_password') new_password = request.form.get('new_password')
confirm_password = request.form.get('confirm_password') confirm_password = request.form.get('confirm_password')
if new_password: if new_password:
if not confirm_password:
flash('Please confirm your new password.', 'error')
return render_template('profile/profile.html')
if new_password != confirm_password: if new_password != confirm_password:
flash('Passwords do not match.', 'error') flash('Passwords do not match.', 'error')
return render_template('profile/profile.html') return render_template('profile/profile.html')
current_user.set_password(new_password) current_user.set_password(new_password)
flash('Password updated successfully.', 'success') flash('Password updated successfully.', 'success')
elif confirm_password:
flash('Please enter a new password.', 'error')
return render_template('profile/profile.html')
try: try:
db.session.commit() db.session.commit()
logger.debug("Profile changes committed to database")
# Log profile update event
event_details = {
'user_id': current_user.id,
'email': current_user.email,
'update_type': 'profile_update',
'updated_fields': {
'username': current_user.username,
'last_name': current_user.last_name,
'email': current_user.email,
'phone': current_user.phone,
'company': current_user.company,
'position': current_user.position,
'notes': current_user.notes,
'profile_picture': bool(current_user.profile_picture)
},
'changes': {
'username': request.form.get('first_name'),
'last_name': request.form.get('last_name'),
'email': request.form.get('email'),
'phone': request.form.get('phone'),
'company': request.form.get('company'),
'position': request.form.get('position'),
'notes': request.form.get('notes'),
'password_changed': bool(new_password)
}
}
logger.debug(f"Creating profile update event with details: {event_details}")
event = log_event('user_update', event_details, current_user.id)
logger.debug(f"Event created successfully with ID: {event.id}")
flash('Profile updated successfully!', 'success') flash('Profile updated successfully!', 'success')
except Exception as e: except Exception as e:
logger.error(f"Error updating profile or logging event: {str(e)}")
db.session.rollback() db.session.rollback()
flash('An error occurred while updating your profile.', 'error') flash('An error occurred while updating your profile.', 'error')
return redirect(url_for('main.profile')) return redirect(url_for('main.dashboard'))
return render_template('profile/profile.html') return render_template('profile/profile.html')
@main_bp.route('/starred') @main_bp.route('/starred')

View File

@@ -6,6 +6,7 @@
<div class="container mx-auto px-4 py-6"> <div class="container mx-auto px-4 py-6">
<div class="max-w-3xl mx-auto"> <div class="max-w-3xl mx-auto">
<form method="POST" enctype="multipart/form-data" class="bg-white rounded-lg shadow overflow-hidden"> <form method="POST" enctype="multipart/form-data" class="bg-white rounded-lg shadow overflow-hidden">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<!-- Profile Picture Section --> <!-- Profile Picture Section -->
<div class="p-4 border-b border-gray-200"> <div class="p-4 border-b border-gray-200">
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
@@ -93,8 +94,8 @@
<button type="submit" <button type="submit"
class="text-white px-6 py-2 rounded-lg transition duration-200" class="text-white px-6 py-2 rounded-lg transition duration-200"
style="background-color: var(--primary-color); border: 1px solid var(--primary-color);" style="background-color: var(--primary-color); border: 1px solid var(--primary-color);"
onmouseover="this.style.backgroundColor='#1a8a90'" onmouseover="this.style.backgroundColor='var(--primary-light)'"
onmouseout="this.style.backgroundColor='#16767b'"> onmouseout="this.style.backgroundColor='var(--primary-color)'">
Save Changes Save Changes
</button> </button>
</div> </div>

View File

@@ -42,7 +42,7 @@
<select id="userFilter" class="form-select form-select-sm"> <select id="userFilter" class="form-select form-select-sm">
<option value="">All Users</option> <option value="">All Users</option>
{% for user in users %} {% for user in users %}
<option value="{{ user.id }}">{{ user.username }}</option> <option value="{{ user.id }}">{{ user.username }} {{ user.last_name }}</option>
{% endfor %} {% endfor %}
</select> </select>
<button id="applyFilters" class="btn btn-primary btn-sm">Apply Filters</button> <button id="applyFilters" class="btn btn-primary btn-sm">Apply Filters</button>
@@ -122,7 +122,7 @@
<span class="badge bg-secondary">{{ event.event_type }}</span> <span class="badge bg-secondary">{{ event.event_type }}</span>
{% endif %} {% endif %}
</td> </td>
<td>{{ event.user.username if event.user else 'Unknown' }}</td> <td>{{ event.user.username }} {{ event.user.last_name if event.user else 'Unknown' }}</td>
<td> <td>
<button class="btn btn-sm btn-outline-secondary" <button class="btn btn-sm btn-outline-secondary"
data-bs-toggle="modal" data-bs-toggle="modal"

View File

@@ -4,6 +4,9 @@ from typing import Optional, Dict, Any, List
from datetime import datetime from datetime import datetime
from flask_login import current_user from flask_login import current_user
from sqlalchemy import desc from sqlalchemy import desc
import logging
logger = logging.getLogger(__name__)
def log_event(event_type: str, details: Optional[Dict[str, Any]] = None, user_id: Optional[int] = None) -> Event: def log_event(event_type: str, details: Optional[Dict[str, Any]] = None, user_id: Optional[int] = None) -> Event:
""" """
@@ -17,9 +20,14 @@ def log_event(event_type: str, details: Optional[Dict[str, Any]] = None, user_id
Returns: Returns:
The created Event object The created Event object
""" """
logger.debug(f"Creating event of type: {event_type}")
logger.debug(f"Event details: {details}")
if user_id is None and current_user.is_authenticated: if user_id is None and current_user.is_authenticated:
user_id = current_user.id user_id = current_user.id
logger.debug(f"Using current user ID: {user_id}")
try:
event = Event( event = Event(
event_type=event_type, event_type=event_type,
user_id=user_id, user_id=user_id,
@@ -29,9 +37,15 @@ def log_event(event_type: str, details: Optional[Dict[str, Any]] = None, user_id
user_agent=request.user_agent.string if request and request.user_agent else None user_agent=request.user_agent.string if request and request.user_agent else None
) )
logger.debug(f"Created event object: {event}")
db.session.add(event) db.session.add(event)
db.session.commit() db.session.commit()
logger.debug(f"Event saved to database with ID: {event.id}")
return event return event
except Exception as e:
logger.error(f"Error creating event: {str(e)}")
db.session.rollback()
raise
def get_user_events(user_id: int, limit: int = 50) -> List[Event]: def get_user_events(user_id: int, limit: int = 50) -> List[Event]:
"""Get recent events for a specific user""" """Get recent events for a specific user"""