|
| 1 | +// This file is part of MinIO Console Server |
| 2 | +// Copyright (c) 2020 MinIO, Inc. |
| 3 | +// |
| 4 | +// This program is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU Affero General Public License as published by |
| 6 | +// the Free Software Foundation, either version 3 of the License, or |
| 7 | +// (at your option) any later version. |
| 8 | +// |
| 9 | +// This program is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU Affero General Public License for more details. |
| 13 | +// |
| 14 | +// You should have received a copy of the GNU Affero General Public License |
| 15 | +// along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +import React, { useEffect, useState } from "react"; |
| 18 | +import { Redirect } from "react-router-dom"; |
| 19 | +import { connect } from "react-redux"; |
| 20 | +import { AppState } from "./store"; |
| 21 | +import { userLoggedIn } from "./actions"; |
| 22 | +import api from "./common/api"; |
| 23 | +import { clearSession } from "./common/utils"; |
| 24 | +import { saveSessionResponse } from "./screens/Console/actions"; |
| 25 | + |
| 26 | +const mapState = (state: AppState) => ({ |
| 27 | + loggedIn: state.system.loggedIn, |
| 28 | +}); |
| 29 | + |
| 30 | +const connector = connect(mapState, { |
| 31 | + userLoggedIn, |
| 32 | + saveSessionResponse, |
| 33 | +}); |
| 34 | + |
| 35 | +interface ProtectedRouteProps { |
| 36 | + loggedIn: boolean; |
| 37 | + Component: any; |
| 38 | + userLoggedIn: typeof userLoggedIn; |
| 39 | + saveSessionResponse: typeof saveSessionResponse; |
| 40 | +} |
| 41 | + |
| 42 | +const ProtectedRoute = ({ |
| 43 | + Component, |
| 44 | + loggedIn, |
| 45 | + userLoggedIn, |
| 46 | + saveSessionResponse, |
| 47 | +}: ProtectedRouteProps) => { |
| 48 | + const [sessionLoading, setSessionLoading] = useState<boolean>(true); |
| 49 | + useEffect(() => { |
| 50 | + api |
| 51 | + .invoke("GET", `/api/v1/session`) |
| 52 | + .then((res) => { |
| 53 | + saveSessionResponse(res); |
| 54 | + userLoggedIn(true); |
| 55 | + setSessionLoading(false); |
| 56 | + }) |
| 57 | + .catch(() => setSessionLoading(false)); |
| 58 | + }, [saveSessionResponse]); |
| 59 | + |
| 60 | + // if we still trying to retrieve user session render nothing |
| 61 | + if (sessionLoading) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + // redirect user to the right page based on session status |
| 65 | + return loggedIn ? <Component /> : <Redirect to={{ pathname: "/login" }} />; |
| 66 | +}; |
| 67 | + |
| 68 | +export default connector(ProtectedRoute); |
0 commit comments