organizationMemberDetail.tsx 14 KB

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