Search code examples
pythonflaskflask-loginflask-socketio

Python Flask Login Current_User Not Always Available


any ideas on the following?

This is my User Class:

class UserType(db.Document):
firstName = db.StringField()
lastName = db.StringField()
email = db.StringField()
passwordHash = db.StringField()
created = db.DateTimeField()
lastEdit = db.DateTimeField()
lastSignIn = db.DateTimeField()
hostOrTest = db.StringField()

def to_json(self):
    return jsonify({
        '_id': str(self.pk),
        'First Name': self.firstName,
        'Last Name': self.lastName,
        'Email': self.email,
        'Creation Date': self.created,
        'Edit Date': self.lastEdit,
        'Last Sign In': self.lastSignIn,
        'hostOrTest': self.hostOrTest
    })

def is_authenticated(self):
    return True

def is_active(self):
    return True

def is_anonymous(self):
    return False

def get_id(self):
    return str(self.pk)

@property
def host(self):
    if self.hostOrTest == "host":
        return True
    else:
        return False

@property
def test(self):
    if self.hostOrTest == 'test':
        return True
    else:
        return False

and this is my login endpoint:

@app.route("/api/Login", methods=["POST"])
def login():
request_data = request.get_json()
email = request_data["email"]
if 'passwordHash' in request_data:
    passwordHash = request_data["passwordHash"]
else:
    passwordHash = request_data["email"]
userObj = UserType.objects(email=email, passwordHash=passwordHash).first()
if userObj:
    login_user(userObj, remember=True, fresh=False)
    userObj.update(lastSignIn=datetime.datetime.now())
    return(jsonify('success'), 200)
else:
    return(jsonify("Username or password error"), 401)

This is all works as expected and when I question the server to see if the user is logged in with the endpoint:

@app.route("/api/isUserLoggedIn", methods=["GET"])
def apiIsUserLoggedIn():
if current_user.is_authenticated:
    print(f"User ID is {current_user.get_id()}")
    return('True')
elif not current_user.is_authenticated:
    return('False')

It works as expected and printed to the console is the Users ID.

However when I run this function:

@app.route('/socketIO/API/createRoom', methods=["POST"])
@socketio.event
#@login_required
def createRoom():
quizId = ''.join(random.choice(string.ascii_lowercase)
                 for i in range(6))

questions = []
timeLimit = 5
quizStarted = 'False'
print(f"User ID is {current_user.get_id()}")
activeRooms = ActiveRooms(
    roomId=quizId,
    connectedUserId=[current_user.get_id()],
    allConnectedUsers=[current_user.get_id()],
    dateTime=datetime.datetime.now(),
    questions=questions,
    timeLimit=timeLimit,
    quizStarted=quizStarted,
    currentQuestion="null"
)
activeRooms.save()
print(f'room created with quiz ID: {quizId}')
# CHANGEBACK emit(f'ID {quizId}')

return(f'ID {quizId}')

these are all apart of the same file as well, in the createRoom function I get User ID is None printed everytime, even though in my IsUserLoggedIn function it works fine.

Any ideas?

PS This is my first post on StackOverflow so I hope I didn't mess anything up! :)

Thanks!


Solution

  • You are using self.pk, but I don't see this defined anywhere. Is this supposed to get the primary key? Because then you might want to set primary_key=True for an attribute (e.g. email = db.StringField(primary_key=True))