80 lines
2.9 KiB
Python
80 lines
2.9 KiB
Python
from flask import Blueprint, render_template, redirect, url_for, flash, request, session
|
|
from flask_login import login_user, logout_user, login_required, current_user
|
|
from app import db
|
|
from app.models.user import User
|
|
from app.forms.auth import LoginForm
|
|
from datetime import datetime
|
|
|
|
auth_bp = Blueprint('auth', __name__)
|
|
|
|
@auth_bp.route('/login', methods=['GET', 'POST'])
|
|
def login():
|
|
"""Handle user login"""
|
|
if current_user.is_authenticated:
|
|
return redirect(url_for('main.dashboard'))
|
|
|
|
form = LoginForm()
|
|
if form.validate_on_submit():
|
|
user = User.query.filter_by(email=form.email.data).first()
|
|
|
|
if user and user.check_password(form.password.data):
|
|
if not user.is_active:
|
|
flash('Your account has been deactivated. Please contact administrator.', 'error')
|
|
return render_template('auth/login.html', form=form)
|
|
|
|
login_user(user, remember=form.remember_me.data)
|
|
user.update_last_login()
|
|
|
|
next_page = request.args.get('next')
|
|
if not next_page or not next_page.startswith('/'):
|
|
next_page = url_for('main.dashboard')
|
|
|
|
flash(f'Welcome back, {user.name}!', 'success')
|
|
return redirect(next_page)
|
|
else:
|
|
flash('Invalid email or password.', 'error')
|
|
|
|
return render_template('auth/login.html', form=form)
|
|
|
|
@auth_bp.route('/logout')
|
|
@login_required
|
|
def logout():
|
|
"""Handle user logout"""
|
|
logout_user()
|
|
flash('You have been logged out successfully.', 'info')
|
|
return redirect(url_for('auth.login'))
|
|
|
|
@auth_bp.route('/profile')
|
|
@login_required
|
|
def profile():
|
|
"""User profile page"""
|
|
return render_template('auth/profile.html')
|
|
|
|
@auth_bp.route('/change_password', methods=['GET', 'POST'])
|
|
@login_required
|
|
def change_password():
|
|
"""Change user password"""
|
|
if request.method == 'POST':
|
|
current_password = request.form.get('current_password')
|
|
new_password = request.form.get('new_password')
|
|
confirm_password = request.form.get('confirm_password')
|
|
|
|
if not current_user.check_password(current_password):
|
|
flash('Current password is incorrect.', 'error')
|
|
return redirect(url_for('auth.change_password'))
|
|
|
|
if new_password != confirm_password:
|
|
flash('New passwords do not match.', 'error')
|
|
return redirect(url_for('auth.change_password'))
|
|
|
|
if len(new_password) < 6:
|
|
flash('Password must be at least 6 characters long.', 'error')
|
|
return redirect(url_for('auth.change_password'))
|
|
|
|
current_user.set_password(new_password)
|
|
db.session.commit()
|
|
|
|
flash('Password changed successfully!', 'success')
|
|
return redirect(url_for('auth.profile'))
|
|
|
|
return render_template('auth/change_password.html') |