quamble / login.py
raj-tomar001's picture
Update login.py
74ece7a verified
raw
history blame
2.93 kB
from flask import request, jsonify
from models import get_user_by_email, bcrypt
import logging
from flask_jwt_extended import create_access_token
from datetime import timedelta
import os
import traceback
logging.basicConfig(
filename=os.path.join('/tmp', 'app.log'),
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def login_route():
try:
if request.method == 'POST':
if request.is_json:
data = request.get_json()
email = data.get('email')
password = data.get('password')
else:
email = request.form.get('email')
password = request.form.get('password')
logging.info("Attempted login with Email: %s", email)
if not email or not password:
logging.warning("Missing email or password for login attempt.")
return jsonify({'message': 'Please enter both email and password.', 'status': 'danger'}), 400
try:
user = get_user_by_email(email)
logging.info("User found: %s", user)
if not user:
logging.warning("No account found with this email: %s", email)
return jsonify({'message': 'No account found with this email', 'status': 'danger'}), 400
if not bcrypt.check_password_hash(user['password'], password):
logging.warning("Incorrect password attempt for email: %s", email)
return jsonify({'message': 'Incorrect password. Please try again.', 'status': 'danger'}), 400
except Exception as db_error:
logging.error("Error retrieving user from database: %s", traceback.format_exc())
return jsonify({'message': 'Internal server error while processing login.', 'status': 'danger'}), 500
try:
expires = timedelta(minutes=600)
access_token = create_access_token(identity=user['id'],expires_delta=expires)
except Exception as token_error:
logging.error("Error creating access token: %s", traceback.format_exc())
return jsonify({'message': 'Internal server error while generating token.', 'status': 'danger'}), 500
logging.info("Login successful for user: %s", user['username'])
return jsonify({'token': access_token, 'message': f'Welcome, {user["username"]}!', 'status': 'success'}), 200
logging.error("Method not allowed: %s", request.method)
return jsonify({'message': 'Method not allowed', 'status': 'danger'}), 405
except Exception as e:
logging.error("Unexpected error in login: %s", traceback.format_exc())
return jsonify({'message': 'Internal server error', 'status': 'danger'}), 500