Home > Software design >  I have problem with sessions(redis) in my React Flask application
I have problem with sessions(redis) in my React Flask application

Time:04-22

I have app: backend flask(api) and frontend react. Program worked well on localhost, but after deployment on server(with apache) something went wrong.

P.S. react working on :80 port, flask on :81 port.

React

When page is loading - useEffect checking for current session.

import React, {useEffect, useState} from 'react'
import { useNavigate } from 'react-router-dom';

export const Login = () => {
    const [user, setUser] = useState(null)

    useEffect(() => {
        fetch('http://myip:81/api/@me').then(
            res => res.json()
        ).then(
            user => {
                setUser(user)
            }
        )
    }, [])
    return(...)
}

Login:

import React, {useEffect, useState} from 'react'
import httpClient from "../components/httpClient"


export const LoginPage = () => {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [userID, setUserID] = useState(null)
    const [error, setError] = useState(false)

    const logInUser = async () => {
        try {
            const res = await httpClient.post("http://myip:81/api/login", {
                content: {
                    email,
                    password
                }
            })
            setEmail('')
            setPassword('')
            window.location.href = `/profile`
        } catch (e) {
            if (e.response.status !== 200) {
                setError(true)
                setEmail('')
                setPassword('')
            }
        }
    }

    return(...)
}

Flask API

Checking current user:

@app.route("/api/@me")
def get_current_user():
    user_id = session.get("user_id")

    if not user_id:
        return {"error": "Unauthorized"}, 401

    user = User.query.filter_by(id=user_id).first()
    return {'id': user.id, 'email': user.email}

Login:

@app.route('/api/login', methods=['POST'])
def login():
    request_data = json.loads(request.data)["content"]
    email = request_data["email"]
    password = request_data["password"]

    user = User.query.filter_by(email=email).first()
    if user is None:
        return {'error': 'User does not exist'}, 401

    if not bcrypt.check_password_hash(user.password, password):
        return {'error': 'Wrong password'}, 401

    session["user_id"] = user.id
    session["email"] = user.email
    return {'id': user.id, 'email': user.email}, 200

Redis check

root@nik:~# redis-cli
127.0.0.1:6379> ping
PONG

When user logging in, the session is created correctly:

127.0.0.1:6379> keys *
1) "session:8e3f1576-8505-40c0-b8ba-bdb1a733133b"
2) "session:ce4f6024-c965-46c0-b0f6-cfafb87640df"

If i'm typing myip:81/api/@me in browser - json returning correctly(like session is working well), but if i'm trying to do it from my react page - json returning "Unauthorized".

What i did wrong? Any ideas?

CodePudding user response:

After 5 days of surfing the internet, I found a solution!

I noticed such a thing:

Browser ---(cookie)---> Flask working well on backend

Browser ---(cookie)---> React ---(no cookie)---> Flask not working because there was no cookie in request from react to flask

So i needed change my code like this:

import React, {useEffect, useState} from 'react'
import { useNavigate } from 'react-router-dom';

export const Login = () => {
    const [user, setUser] = useState(null)

    useEffect(() => {
        fetch('http://myip:81/api/@me', {credentials: 'include'}).then(
            res => res.json()
        ).then(
            user => {
                setUser(user)
            }
        )
    }, [])
    return(...)
}
  • Related