-
-
Notifications
You must be signed in to change notification settings - Fork 86
Open
Description
i'm using scylla for database for my gradution project got a problems
from django.contrib.auth.backends import BaseBackend
from .models import User
from cassandra.cluster import Cluster
from cassandra.query import SimpleStatement
class CassandraAuthBackend(BaseBackend):
def init(self):
# Initialize Cassandra connection
cluster = Cluster(['127.0.0.1']) # Update with your Cassandra cluster node(s)
self.session = cluster.connect('galileo') # Replace with your keyspace
def authenticate(self, request, username=None, password=None, **kwargs):
if not username or not password:
return None # Return None if credentials are incomplete
try:
# Query the Cassandra database for the user
query = SimpleStatement(
"SELECT * FROM user WHERE username=%s ALLOW FILTERING", fetch_size=1
)
rows = self.session.execute(query, (username,))
user_data = next(iter(rows), None) # Get the first result, or None if no results
if user_data:
# Create a `User` instance manually
user = User(
user_id=user_data.user_id,
username=user_data.username,
email=user_data.email,
password_hash=user_data.password_hash,
first_name=user_data.first_name,
last_name=user_data.last_name,
)
# Check the password
if user.check_password(password):
return user
else:
print("Password mismatch")
else:
print("No user found for username")
except Exception as e:
print(f"Authentication error: {e}")
return None # Explicitly return None if authentication fails
def get_user(self, user_id):
try:
# Query Cassandra to get a user by user_id
query = SimpleStatement(
"SELECT * FROM user WHERE user_id=%s ALLOW FILTERING", fetch_size=1
)
rows = self.session.execute(query, (user_id,))
user_data = next(iter(rows), None)
if user_data:
# Create and return a `User` object
return User(
user_id=user_data.user_id,
username=user_data.username,
email=user_data.email,
password_hash=user_data.password_hash,
first_name=user_data.first_name,
last_name=user_data.last_name,
)
except Exception as e:
print(f"Error fetching user by user_id: {e}")
return None # Explicitly return None if no user is found
Metadata
Metadata
Assignees
Labels
No labels