organizationMemberDetail.tsx 14 KB

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