Это конфигурация приложения на Python в файле app.py:
Код: Выделить всё
app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/agentie_imobiliara'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
app.config['SESSION_COOKIE_SECURE'] = False
app.config['SESSION_TYPE'] = 'filesystem'
app.permanent_session_lifetime = timedelta(days=7)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = "None"
app.config['SESSION_COOKIE_NAME'] = 'session'
CORS(app, origins='*', supports_credentials=True)
Session(app)
if __name__ == '__main__':
app.run()
Код: Выделить всё
@app.route('/login', methods=['POST'])
def login():
try:
email = request.json['email']
password = request.json['password']
user = User.query.filter_by(email=email).first()
if user and user.password == password:
session['user_id'] = user.id
session['user_email'] = user.email
session['user_role'] = user.role
session.modified = True
session.permanent = True
return jsonify({'message': 'Login successful', 'user_id': user.id,
'user_email': user.email, 'user_role': user.role})
else:
return jsonify({'message': 'Invalid email or password'})
except Exception as e:
print(f"Error: {e}")
return jsonify({'message': 'An error occurred'})
@app.route('/user_role', methods=['GET'])
def get_user_role():
print(f"Session contents: {session}")
if 'user_role' in session:
user_role = session.get('user_role')
return jsonify({'user_role': user_role})
else:
return jsonify({'message': 'User not logged in'})
Код: Выделить всё
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post(
"http://127.0.0.1:5000/login",
{ email: email, password: password },
{
headers: {
"Content-Type": "application/json",
},
}
);
alert(response.data.message);
if (response.status === 200 && response.data.message === "Login successful") {
onLoginSuccess(true);
setIsLoggedIn(true);
history.push('/');
console.log("isLoggedIn:", isLoggedIn);
console.log("onLoginSuccess:", onLoginSuccess);
}
} catch (error) {
alert("Invalid email or password");
}
};
Код: Выделить всё
useEffect(() => {
// Fetch the user's role from the API
fetch('http://127.0.0.1:5000/user_role', { credentials: 'include' })
.then(response => response.json())
.then(data => setRole(data.role))
.catch(error => console.error(error));
}, []);
Подробнее здесь: https://stackoverflow.com/questions/760 ... n-sessions