Я создаю систему аутентификации, и я хочу отправить запрос сброса с помощью API Miledersend, код не имеет ошибок. Точка входа для приложения находится в файле app.py. Структура данных также верна. Папка Project включает в себя login.html и login.js, который содержит как страницы, так и страницы забытых паролей. Точка входа для приложения находится на app.py < /p>
Код даже не выходит из консоли с print (), используемой для < /p>
authentication.py
import secrets
import bcrypt
import sqlite3
import datetime
from flask import Blueprint, jsonify, request,session
from mailersend import MailerSendClient, EmailBuilder
import secrets
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
# creatin mail sender client
mailer = MailerSendClient(api_key='mlsn.cc7po0a13bghjgjg061960a92b85e0676e762384ba8097993cc02ac8783052849baba75d')
def get_db_connection():
# Get database connection to the cyber-shield-linkguard database
conn = sqlite3.connect('cyber-shield-linkguard.db')
# return dictionary data structure from the columns of the database
# e.g instead of column id data[2] use data['password']
conn.row_factory = sqlite3.Row
return conn
@auth_bp.route('/forgot-password', methods=['POST'])
def forgot_password():
try:
data = request.get_json()
email = data.get('email', '').strip().lower()
if not email:
print('No email provided')
return jsonify({'error': 'Email is required'}), 400
try:
conn = get_db_connection()
cursor = conn.cursor()
# Check if user exists
cursor.execute('SELECT id FROM users WHERE email = ?', (email,))
user = cursor.fetchone()
print(f'Entries found: {user}')
if not user:
conn.close()
print('Email not found in database')
return jsonify({'error': 'Email not found'}), 404
#generate token
token = secrets.token_urlsafe(32)
print(f'Generated token: {token}')
cursor.execute('''INSERT INTO password_reset_tokens (email, token, is_used) VALUES (?, ?, 0)''', (email, token))
conn.commit()
conn.close()
reset_link = f'http://localhost:5000/reset-password?token={token}'
print(f'Reset link: {reset_link}')
mail_msg = EmailBuilder().from_email("test@test-ywj2lpnwmmqg7oqz.mlsender.net","theArchive").to_many([{"email":email}]).subject("Password Reset Request").html(f"
Click here to reset your password.
").text(f"Use the following link to reset your password: {reset_link}").build()
try:
response = mailer.emails.send(mail_msg)
print(f'Email sent successsfully: {response.json()}')
print(f'Password reset link sent to {email}: {reset_link}')
return jsonify({'message': 'Password reset link sent'}), 200
except Exception as e:
print(f'Error sending email: {e}')
return jsonify({'error': str(e)}), 500
except sqlite3.Error as e:
print(f"Database error: {e}")
return jsonify({'error': 'Database error occurred'}), 500
except Exception as e:
print(f"Forgot password error: {e}")
return jsonify({'error': 'Failed to process request'}), 500
Подробнее здесь: https://stackoverflow.com/questions/797 ... ot-working
Приложение Flask: Забыть пароль маршрут не работает ⇐ Javascript
Форум по Javascript
-
Anonymous
1757611034
Anonymous
Я создаю систему аутентификации, и я хочу отправить запрос сброса с помощью API Miledersend, код не имеет ошибок. Точка входа для приложения находится в файле app.py. Структура данных также верна. Папка Project включает в себя login.html и login.js, который содержит как страницы, так и страницы забытых паролей. Точка входа для приложения находится на app.py < /p>
Код даже не выходит из консоли с print (), используемой для < /p>
authentication.py
import secrets
import bcrypt
import sqlite3
import datetime
from flask import Blueprint, jsonify, request,session
from mailersend import MailerSendClient, EmailBuilder
import secrets
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
# creatin mail sender client
mailer = MailerSendClient(api_key='mlsn.cc7po0a13bghjgjg061960a92b85e0676e762384ba8097993cc02ac8783052849baba75d')
def get_db_connection():
# Get database connection to the cyber-shield-linkguard database
conn = sqlite3.connect('cyber-shield-linkguard.db')
# return dictionary data structure from the columns of the database
# e.g instead of column id data[2] use data['password']
conn.row_factory = sqlite3.Row
return conn
@auth_bp.route('/forgot-password', methods=['POST'])
def forgot_password():
try:
data = request.get_json()
email = data.get('email', '').strip().lower()
if not email:
print('No email provided')
return jsonify({'error': 'Email is required'}), 400
try:
conn = get_db_connection()
cursor = conn.cursor()
# Check if user exists
cursor.execute('SELECT id FROM users WHERE email = ?', (email,))
user = cursor.fetchone()
print(f'Entries found: {user}')
if not user:
conn.close()
print('Email not found in database')
return jsonify({'error': 'Email not found'}), 404
#generate token
token = secrets.token_urlsafe(32)
print(f'Generated token: {token}')
cursor.execute('''INSERT INTO password_reset_tokens (email, token, is_used) VALUES (?, ?, 0)''', (email, token))
conn.commit()
conn.close()
reset_link = f'http://localhost:5000/reset-password?token={token}'
print(f'Reset link: {reset_link}')
mail_msg = EmailBuilder().from_email("test@test-ywj2lpnwmmqg7oqz.mlsender.net","theArchive").to_many([{"email":email}]).subject("Password Reset Request").html(f"
Click [url={reset_link}]here[/url] to reset your password.
").text(f"Use the following link to reset your password: {reset_link}").build()
try:
response = mailer.emails.send(mail_msg)
print(f'Email sent successsfully: {response.json()}')
print(f'Password reset link sent to {email}: {reset_link}')
return jsonify({'message': 'Password reset link sent'}), 200
except Exception as e:
print(f'Error sending email: {e}')
return jsonify({'error': str(e)}), 500
except sqlite3.Error as e:
print(f"Database error: {e}")
return jsonify({'error': 'Database error occurred'}), 500
except Exception as e:
print(f"Forgot password error: {e}")
return jsonify({'error': 'Failed to process request'}), 500
Подробнее здесь: [url]https://stackoverflow.com/questions/79762225/flask-application-forgot-password-route-is-not-working[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия