organizationMemberDetail.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import isEqual from 'lodash/isEqual';
  6. import {removeAuthenticator} from 'sentry/actionCreators/account';
  7. import {
  8. addErrorMessage,
  9. addLoadingMessage,
  10. addSuccessMessage,
  11. } from 'sentry/actionCreators/indicator';
  12. import {resendMemberInvite, updateMember} from 'sentry/actionCreators/members';
  13. import {Button} from 'sentry/components/button';
  14. import ButtonBar from 'sentry/components/buttonBar';
  15. import Confirm from 'sentry/components/confirm';
  16. import DateTime from 'sentry/components/dateTime';
  17. import NotFound from 'sentry/components/errors/notFound';
  18. import FieldGroup from 'sentry/components/forms/fieldGroup';
  19. import HookOrDefault from 'sentry/components/hookOrDefault';
  20. import ExternalLink from 'sentry/components/links/externalLink';
  21. import Panel from 'sentry/components/panels/panel';
  22. import PanelBody from 'sentry/components/panels/panelBody';
  23. import PanelHeader from 'sentry/components/panels/panelHeader';
  24. import PanelItem from 'sentry/components/panels/panelItem';
  25. import {Tooltip} from 'sentry/components/tooltip';
  26. import {IconRefresh} from 'sentry/icons';
  27. import {t, tct} from 'sentry/locale';
  28. import {space} from 'sentry/styles/space';
  29. import {Member, Organization} from 'sentry/types';
  30. import isMemberDisabledFromLimit from 'sentry/utils/isMemberDisabledFromLimit';
  31. import Teams from 'sentry/utils/teams';
  32. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  33. import withOrganization from 'sentry/utils/withOrganization';
  34. import DeprecatedAsyncView, {AsyncViewState} from 'sentry/views/deprecatedAsyncView';
  35. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  36. import TeamSelectForMember from 'sentry/views/settings/components/teamSelect/teamSelectForMember';
  37. import OrganizationRoleSelect from './inviteMember/orgRoleSelect';
  38. const MULTIPLE_ORGS = t('Cannot be reset since user is in more than one organization');
  39. const NOT_ENROLLED = t('Not enrolled in two-factor authentication');
  40. const NO_PERMISSION = t('You do not have permission to perform this action');
  41. const TWO_FACTOR_REQUIRED = t(
  42. 'Cannot be reset since two-factor is required for this organization'
  43. );
  44. type RouteParams = {
  45. memberId: string;
  46. };
  47. interface Props extends RouteComponentProps<RouteParams, {}> {
  48. organization: Organization;
  49. }
  50. interface State extends AsyncViewState {
  51. groupOrgRoles: Member['groupOrgRoles']; // Form state
  52. member: Member | null;
  53. orgRole: Member['orgRole']; // Form state
  54. teamRoles: Member['teamRoles']; // Form state
  55. }
  56. const DisabledMemberTooltip = HookOrDefault({
  57. hookName: 'component:disabled-member-tooltip',
  58. defaultComponent: ({children}) => <Fragment>{children}</Fragment>,
  59. });
  60. class OrganizationMemberDetail extends DeprecatedAsyncView<Props, State> {
  61. get hasTeamRoles() {
  62. const {organization} = this.props;
  63. return organization.features.includes('team-roles');
  64. }
  65. getDefaultState(): State {
  66. return {
  67. ...super.getDefaultState(),
  68. groupOrgRoles: [],
  69. member: null,
  70. orgRole: '',
  71. teamRoles: [],
  72. };
  73. }
  74. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  75. const {organization, params} = this.props;
  76. return [
  77. ['member', `/organizations/${organization.slug}/members/${params.memberId}/`],
  78. ];
  79. }
  80. onRequestSuccess({data, stateKey}: {data: Member; stateKey: string}) {
  81. if (stateKey === 'member') {
  82. const {orgRole, teamRoles, groupOrgRoles} = data;
  83. this.setState({
  84. orgRole,
  85. teamRoles,
  86. groupOrgRoles,
  87. });
  88. }
  89. }
  90. handleSave = async () => {
  91. const {organization, params} = this.props;
  92. const {orgRole, teamRoles} = this.state;
  93. addLoadingMessage(t('Saving...'));
  94. this.setState({busy: true});
  95. try {
  96. const updatedMember = await updateMember(this.api, {
  97. orgId: organization.slug,
  98. memberId: params.memberId,
  99. data: {orgRole, teamRoles} as any,
  100. });
  101. this.setState({
  102. member: updatedMember,
  103. orgRole: updatedMember.orgRole,
  104. teamRoles: updatedMember.teamRoles,
  105. busy: false,
  106. });
  107. addSuccessMessage(t('Saved'));
  108. } catch (resp) {
  109. const errorMessage =
  110. (resp && resp.responseJSON && resp.responseJSON.detail) || t('Could not save...');
  111. this.setState({busy: false});
  112. addErrorMessage(errorMessage);
  113. }
  114. };
  115. handleInvite = async (regenerate: boolean) => {
  116. const {organization, params} = this.props;
  117. addLoadingMessage(t('Sending invite...'));
  118. this.setState({busy: true});
  119. try {
  120. const data = await resendMemberInvite(this.api, {
  121. orgId: organization.slug,
  122. memberId: params.memberId,
  123. regenerate,
  124. });
  125. addSuccessMessage(t('Sent invite!'));
  126. if (regenerate) {
  127. this.setState(state => ({member: {...state.member, ...data}}));
  128. }
  129. } catch (_err) {
  130. addErrorMessage(t('Could not send invite'));
  131. }
  132. this.setState({busy: false});
  133. };
  134. handle2faReset = async () => {
  135. const {organization, router} = this.props;
  136. const {user} = this.state.member!;
  137. const requests =
  138. user?.authenticators?.map(auth =>
  139. removeAuthenticator(this.api, user.id, auth.id)
  140. ) ?? [];
  141. try {
  142. await Promise.all(requests);
  143. router.push(normalizeUrl(`/settings/${organization.slug}/members/`));
  144. addSuccessMessage(t('All authenticators have been removed'));
  145. } catch (err) {
  146. addErrorMessage(t('Error removing authenticators'));
  147. Sentry.captureException(err);
  148. }
  149. };
  150. onAddTeam = (teamSlug: string) => {
  151. const teamRoles = [...this.state.teamRoles];
  152. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  153. if (i !== -1) {
  154. return;
  155. }
  156. teamRoles.push({teamSlug, role: null});
  157. this.setState({teamRoles});
  158. };
  159. onRemoveTeam = (teamSlug: string) => {
  160. const teamRoles = this.state.teamRoles.filter(r => r.teamSlug !== teamSlug);
  161. this.setState({teamRoles});
  162. };
  163. onChangeOrgRole = orgRole => this.setState({orgRole});
  164. onChangeTeamRole = (teamSlug: string, role: string) => {
  165. if (!this.hasTeamRoles) {
  166. return;
  167. }
  168. const teamRoles = [...this.state.teamRoles];
  169. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  170. if (i === -1) {
  171. return;
  172. }
  173. teamRoles[i] = {...teamRoles[i], role};
  174. this.setState({teamRoles});
  175. };
  176. showResetButton = () => {
  177. const {organization} = this.props;
  178. const {member} = this.state;
  179. const {user} = member!;
  180. if (!user || !user.authenticators || organization.require2FA) {
  181. return false;
  182. }
  183. const hasAuth = user.authenticators.length >= 1;
  184. return hasAuth && user.canReset2fa;
  185. };
  186. getTooltip = (): string => {
  187. const {organization} = this.props;
  188. const {member} = this.state;
  189. const {user} = member!;
  190. if (!user) {
  191. return '';
  192. }
  193. if (!user.authenticators) {
  194. return NO_PERMISSION;
  195. }
  196. if (!user.authenticators.length) {
  197. return NOT_ENROLLED;
  198. }
  199. if (!user.canReset2fa) {
  200. return MULTIPLE_ORGS;
  201. }
  202. if (organization.require2FA) {
  203. return TWO_FACTOR_REQUIRED;
  204. }
  205. return '';
  206. };
  207. get memberDeactivated() {
  208. return isMemberDisabledFromLimit(this.state.member);
  209. }
  210. get hasFormChanged() {
  211. const {member, orgRole, teamRoles} = this.state;
  212. if (!member) {
  213. return false;
  214. }
  215. if (orgRole !== member.orgRole || !isEqual(teamRoles, member.teamRoles)) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. renderMemberStatus(member: Member) {
  221. if (this.memberDeactivated) {
  222. return (
  223. <em>
  224. <DisabledMemberTooltip>{t('Deactivated')}</DisabledMemberTooltip>
  225. </em>
  226. );
  227. }
  228. if (member.expired) {
  229. return <em>{t('Invitation Expired')}</em>;
  230. }
  231. if (member.pending) {
  232. return <em>{t('Invitation Pending')}</em>;
  233. }
  234. return t('Active');
  235. }
  236. renderBody() {
  237. const {organization} = this.props;
  238. const {member, orgRole, teamRoles} = this.state;
  239. if (!member) {
  240. return <NotFound />;
  241. }
  242. const {access, orgRoleList} = organization;
  243. const canEdit = access.includes('org:write') && !this.memberDeactivated;
  244. const isPartnershipUser = member.flags['partnership:restricted'] === true;
  245. const {email, expired, pending} = member;
  246. const canResend = !expired;
  247. const showAuth = !pending;
  248. return (
  249. <Fragment>
  250. <SettingsPageHeader
  251. title={
  252. <Fragment>
  253. <div>{member.name}</div>
  254. <ExtraHeaderText>{t('Member Settings')}</ExtraHeaderText>
  255. </Fragment>
  256. }
  257. />
  258. <Panel>
  259. <PanelHeader>{t('Basics')}</PanelHeader>
  260. <PanelBody>
  261. <PanelItem>
  262. <Details>
  263. <div>
  264. <DetailLabel>{t('Email')}</DetailLabel>
  265. <div>
  266. <ExternalLink href={`mailto:${email}`}>{email}</ExternalLink>
  267. </div>
  268. </div>
  269. <div>
  270. <DetailLabel>{t('Status')}</DetailLabel>
  271. <div data-test-id="member-status">
  272. {this.renderMemberStatus(member)}
  273. </div>
  274. </div>
  275. <div>
  276. <DetailLabel>{t('Added')}</DetailLabel>
  277. <div>
  278. <DateTime dateOnly date={member.dateCreated} />
  279. </div>
  280. </div>
  281. </Details>
  282. </PanelItem>
  283. <PanelItem>
  284. {(member.pending || member.expired) && (
  285. <InviteSection>
  286. <ButtonBar gap={1}>
  287. {canResend && (
  288. <Button
  289. data-test-id="resend-invite"
  290. icon={<IconRefresh size="sm" />}
  291. title={t('Generate a new invite link and send a new email.')}
  292. onClick={() => this.handleInvite(true)}
  293. >
  294. {t('Resend Invite')}
  295. </Button>
  296. )}
  297. </ButtonBar>
  298. </InviteSection>
  299. )}
  300. </PanelItem>
  301. </PanelBody>
  302. </Panel>
  303. {showAuth && (
  304. <Panel>
  305. <PanelHeader>{t('Authentication')}</PanelHeader>
  306. <PanelBody>
  307. <FieldGroup
  308. alignRight
  309. flexibleControlStateSize
  310. label={t('Reset two-factor authentication')}
  311. help={t(
  312. 'Resetting two-factor authentication will remove all two-factor authentication methods for this member.'
  313. )}
  314. >
  315. <Tooltip disabled={this.showResetButton()} title={this.getTooltip()}>
  316. <Confirm
  317. disabled={!this.showResetButton()}
  318. message={tct(
  319. 'Are you sure you want to disable all two-factor authentication methods for [name]?',
  320. {name: member.name ? member.name : 'this member'}
  321. )}
  322. onConfirm={this.handle2faReset}
  323. >
  324. <Button priority="danger">
  325. {t('Reset two-factor authentication')}
  326. </Button>
  327. </Confirm>
  328. </Tooltip>
  329. </FieldGroup>
  330. </PanelBody>
  331. </Panel>
  332. )}
  333. <OrganizationRoleSelect
  334. enforceAllowed={false}
  335. enforceRetired={this.hasTeamRoles}
  336. disabled={!canEdit || isPartnershipUser}
  337. roleList={orgRoleList}
  338. roleSelected={orgRole}
  339. setSelected={this.onChangeOrgRole}
  340. helpText={
  341. isPartnershipUser
  342. ? t('You cannot make changes to this partner-provisioned user.')
  343. : undefined
  344. }
  345. />
  346. <Teams slugs={member.teams}>
  347. {({initiallyLoaded}) => (
  348. <Fragment>
  349. <TeamSelectForMember
  350. disabled={!canEdit}
  351. organization={organization}
  352. member={member}
  353. selectedOrgRole={orgRole}
  354. selectedTeamRoles={teamRoles}
  355. onChangeTeamRole={this.onChangeTeamRole}
  356. onAddTeam={this.onAddTeam}
  357. onRemoveTeam={this.onRemoveTeam}
  358. loadingTeams={!initiallyLoaded}
  359. />
  360. </Fragment>
  361. )}
  362. </Teams>
  363. <Footer>
  364. <Button
  365. priority="primary"
  366. busy={this.state.busy}
  367. onClick={this.handleSave}
  368. disabled={!canEdit || !this.hasFormChanged}
  369. >
  370. {t('Save Member')}
  371. </Button>
  372. </Footer>
  373. </Fragment>
  374. );
  375. }
  376. }
  377. export default withOrganization(OrganizationMemberDetail);
  378. const ExtraHeaderText = styled('div')`
  379. color: ${p => p.theme.gray300};
  380. font-weight: normal;
  381. font-size: ${p => p.theme.fontSizeLarge};
  382. `;
  383. const Details = styled('div')`
  384. display: grid;
  385. grid-auto-flow: column;
  386. grid-template-columns: 2fr 1fr 1fr;
  387. gap: ${space(2)};
  388. width: 100%;
  389. @media (max-width: ${p => p.theme.breakpoints.small}) {
  390. grid-auto-flow: row;
  391. grid-template-columns: auto;
  392. }
  393. `;
  394. const DetailLabel = styled('div')`
  395. font-weight: bold;
  396. margin-bottom: ${space(0.5)};
  397. color: ${p => p.theme.textColor};
  398. `;
  399. const InviteSection = styled('div')`
  400. flex-grow: 1;
  401. display: flex;
  402. gap: ${space(1)};
  403. `;
  404. const Footer = styled('div')`
  405. display: flex;
  406. justify-content: flex-end;
  407. `;