Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ImportError: cannot import name 'DecodeError' from 'jwt' (/usr/local/lib/python3.10/dist-packages/jwt/__init__.py) #536

Closed
miraqulass opened this issue Dec 6, 2023 · 1 comment

Comments

@miraqulass
Copy link

The following is my code and below it is the error related to the importation of DecodeError even though I imported JWTDecodeError:

import os
from datetime import timedelta
from flask import Flask, request, jsonify
import mysql.connector
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from jwt.exceptions import JWTDecodeError

app = Flask(name)

app.config['JWT_SECRET_KEY'] = '########'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(seconds=86400)

jwt = JWTManager(app)

class User(object):
def init(self, id, phone_number):
self.id = id
self.phone_number = phone_number

@jwt.user_identity_loader
def user_identity_lookup(user):
return user.id

@jwt.user_loader_callback_loader
def user_loader_callback(identity):
# Add your logic to retrieve the user based on the identity
cursor.execute("SELECT phone_number FROM accounts_userprofile WHERE user_id=%s", (identity,))
result = cursor.fetchone()
if result:
return User(identity, result[0])

conn = mysql.connector.connect(
host='##########',
user='######',
database='#######',
password='########'
)
cursor = conn.cursor()

def is_authenticated(phone_number):
cursor.execute("SELECT authenticated FROM accounts_userprofile WHERE phone_number=%s", (phone_number,))
result = cursor.fetchone()
if result:
return result[0]
else:
return False

def get_user_id(phone_number):
cursor.execute("SELECT user_id FROM accounts_userprofile WHERE phone_number-%s", (phone_number,))
result = cursor.fetchone()
if result:
return result[0]
else:
return None

def generate_access_token(phone_number):
user_id = get_user_id(phone_number)
if user_id:
access_token = create_access_token(identity=user_id)
return access_token
else:
return None

@app.route('/api/login', methods=['POST'])
def login():
data = request.get_json()
phone_number = data.get('phone_number')
password = data.get('password')

if not is_authenticated(phone_number):
    return jsonify({'error': 'User not authenticated'}), 401

user_id = get_user_id(phone_number)
if user_id is None:
    return jsonify({'error': 'User not found'}), 404

access_token = create_access_token(identity=user_id)
current_usr = User(user_id, phone_number)
return jsonify(access_token=access_token, user=current_usr.to_dict())

@app.route('/api/vehicles', methods=['GET'])
@jwt_required()
def get_user_vehicles():
try:
current_user = User(get_jwt_identity(), None)
except JWTDecodeError as e:
print(f'Decoding error: {e}')
return jsonify({'error': f'Decoding error: {e}'}), 401

user_id = current_user.id

cursor.execute("SELECT * FROM vehicle_vehicle WHERE user_id=%s", (user_id,))
vehicle_vehicle = cursor.fetchall()

if not vehicle_vehicle:
    return jsonify({'error': 'No vehicles found for this user'}), 404

vehicle_data = [{'id': v[0], 'VIN': v[1], 'manufacturer': v[2], 'model': v[3], 'year': v[4], 'vehicle type': v[5],
                 'transmission': v[6], 'eng displacement': v[7], 'vehicle color': v[8], 'vehicle reg no': v[9],
                 'number plate': v[10]} for v in vehicle_vehicle]

return jsonify({'vehicles': vehicle_data})

def save_api_access_token(token):
with open('access_token.txt', 'w') as file:
file.write(token)

def get_api_access_token():
if os.path.exists('access_token.txt'):
with open('access_token.txt', 'r') as file:
return file.read().strip()
else:
return None

if name == 'main':
app.run()

The error:

Traceback (most recent call last):
File "/home/miraqulas/PycharmProjects/PCEE/Chatbot_API/generalAPI/general_api.py", line 5, in
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
File "/home/miraqulas/.local/lib/python3.10/site-packages/flask_jwt_extended/init.py", line 1, in
from .jwt_manager import JWTManager as JWTManager
File "/home/miraqulas/.local/lib/python3.10/site-packages/flask_jwt_extended/jwt_manager.py", line 8, in
from jwt import DecodeError
ImportError: cannot import name 'DecodeError' from 'jwt' (/usr/local/lib/python3.10/dist-packages/jwt/init.py)

@vimalloc
Copy link
Owner

vimalloc commented Dec 6, 2023

Please see this comment, it's very likely the same issue: #456 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants