github.com/minio/console@v1.4.1/web-app/src/common/SecureComponent/SecureComponent.tsx (about)

     1  // This file is part of MinIO Console Server
     2  // Copyright (c) 2021 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, { cloneElement } from "react";
    18  import hasPermission from "./accessControl";
    19  
    20  interface ISecureComponentProps {
    21    errorProps?: any;
    22    RenderError?: any;
    23    matchAll?: boolean;
    24    children: any;
    25    scopes: string[];
    26    resource: string | string[];
    27    containsResource?: boolean;
    28  }
    29  
    30  const SecureComponent = ({
    31    children,
    32    RenderError = () => <></>,
    33    errorProps = null,
    34    matchAll = false,
    35    scopes = [],
    36    resource,
    37    containsResource = false,
    38  }: ISecureComponentProps) => {
    39    const permissionGranted = hasPermission(
    40      resource,
    41      scopes,
    42      matchAll,
    43      containsResource,
    44    );
    45    if (!permissionGranted && !errorProps) return <RenderError />;
    46    if (!permissionGranted && errorProps) {
    47      return Array.isArray(children) ? (
    48        <>{children.map((child) => cloneElement(child, { ...errorProps }))}</>
    49      ) : (
    50        cloneElement(children, { ...errorProps })
    51      );
    52    }
    53    return <>{children}</>;
    54  };
    55  
    56  export default SecureComponent;