1import React from 'react'; 2 3import { getBackendSrv } from '@grafana/runtime'; 4import { UserOrgDTO } from '@grafana/data'; 5import { Modal, Button, CustomScrollbar } from '@grafana/ui'; 6 7import { contextSrv } from 'app/core/services/context_srv'; 8import config from 'app/core/config'; 9import { css } from '@emotion/css'; 10 11interface Props { 12 onDismiss: () => void; 13} 14 15interface State { 16 orgs: UserOrgDTO[]; 17} 18 19export class OrgSwitcher extends React.PureComponent<Props, State> { 20 state: State = { 21 orgs: [], 22 }; 23 24 componentDidMount() { 25 this.getUserOrgs(); 26 } 27 28 getUserOrgs = async () => { 29 const orgs: UserOrgDTO[] = await getBackendSrv().get('/api/user/orgs'); 30 this.setState({ orgs }); 31 }; 32 33 setCurrentOrg = async (org: UserOrgDTO) => { 34 await getBackendSrv().post(`/api/user/using/${org.orgId}`); 35 this.setWindowLocation(`${config.appSubUrl}${config.appSubUrl.endsWith('/') ? '' : '/'}?orgId=${org.orgId}`); 36 }; 37 38 setWindowLocation(href: string) { 39 window.location.href = href; 40 } 41 42 render() { 43 const { onDismiss } = this.props; 44 const { orgs } = this.state; 45 46 const currentOrgId = contextSrv.user.orgId; 47 const contentClassName = css({ 48 display: 'flex', 49 maxHeight: 'calc(85vh - 42px)', 50 }); 51 52 return ( 53 <Modal 54 title="Switch Organization" 55 icon="arrow-random" 56 onDismiss={onDismiss} 57 isOpen={true} 58 contentClassName={contentClassName} 59 > 60 <CustomScrollbar autoHeightMin="100%"> 61 <table className="filter-table form-inline"> 62 <thead> 63 <tr> 64 <th>Name</th> 65 <th>Role</th> 66 <th /> 67 </tr> 68 </thead> 69 <tbody> 70 {orgs.map((org) => ( 71 <tr key={org.orgId}> 72 <td>{org.name}</td> 73 <td>{org.role}</td> 74 <td className="text-right"> 75 {org.orgId === currentOrgId ? ( 76 <Button size="sm">Current</Button> 77 ) : ( 78 <Button variant="secondary" size="sm" onClick={() => this.setCurrentOrg(org)}> 79 Switch to 80 </Button> 81 )} 82 </td> 83 </tr> 84 ))} 85 </tbody> 86 </table> 87 </CustomScrollbar> 88 </Modal> 89 ); 90 } 91} 92