organizationMemberDetail.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 configStore from 'sentry/stores/configStore';
  27. import {space} from 'sentry/styles/space';
  28. import {Member, Organization} from 'sentry/types';
  29. import isMemberDisabledFromLimit from 'sentry/utils/isMemberDisabledFromLimit';
  30. import Teams from 'sentry/utils/teams';
  31. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  32. import withOrganization from 'sentry/utils/withOrganization';
  33. import AsyncView from 'sentry/views/asyncView';
  34. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  35. import TeamSelectForMember from 'sentry/views/settings/components/teamSelect/teamSelectForMember';
  36. import OrganizationRoleSelect from './inviteMember/orgRoleSelect';
  37. const MULTIPLE_ORGS = t('Cannot be reset since user is in more than one organization');
  38. const NOT_ENROLLED = t('Not enrolled in two-factor authentication');
  39. const NO_PERMISSION = t('You do not have permission to perform this action');
  40. const TWO_FACTOR_REQUIRED = t(
  41. 'Cannot be reset since two-factor is required for this organization'
  42. );
  43. type RouteParams = {
  44. memberId: string;
  45. };
  46. type Props = {
  47. organization: Organization;
  48. } & RouteComponentProps<RouteParams, {}>;
  49. type State = {
  50. groupOrgRoles: Member['groupOrgRoles']; // Form state
  51. member: Member | null;
  52. orgRole: Member['orgRole']; // Form state
  53. teamRoles: Member['teamRoles']; // Form state
  54. } & AsyncView['state'];
  55. const DisabledMemberTooltip = HookOrDefault({
  56. hookName: 'component:disabled-member-tooltip',
  57. defaultComponent: ({children}) => <Fragment>{children}</Fragment>,
  58. });
  59. class OrganizationMemberDetail extends AsyncView<Props, State> {
  60. get hasTeamRoles() {
  61. const {organization} = this.props;
  62. return organization.features.includes('team-roles');
  63. }
  64. getDefaultState(): State {
  65. return {
  66. ...super.getDefaultState(),
  67. groupOrgRoles: [],
  68. member: null,
  69. orgRole: '',
  70. teamRoles: [],
  71. };
  72. }
  73. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  74. const {organization, params} = this.props;
  75. return [
  76. ['member', `/organizations/${organization.slug}/members/${params.memberId}/`],
  77. ];
  78. }
  79. onRequestSuccess({data, stateKey}: {data: Member; stateKey: string}) {
  80. if (stateKey === 'member') {
  81. const {orgRole, teamRoles, groupOrgRoles} = data;
  82. this.setState({
  83. orgRole,
  84. teamRoles,
  85. groupOrgRoles,
  86. });
  87. }
  88. }
  89. handleSave = async () => {
  90. const {organization, params} = this.props;
  91. const {orgRole, teamRoles} = this.state;
  92. addLoadingMessage(t('Saving...'));
  93. this.setState({busy: true});
  94. try {
  95. const updatedMember = await updateMember(this.api, {
  96. orgId: organization.slug,
  97. memberId: params.memberId,
  98. data: {orgRole, teamRoles} as any,
  99. });
  100. this.setState({
  101. member: updatedMember,
  102. orgRole: updatedMember.orgRole,
  103. teamRoles: updatedMember.teamRoles,
  104. busy: false,
  105. });
  106. addSuccessMessage(t('Saved'));
  107. } catch (resp) {
  108. const errorMessage =
  109. (resp && resp.responseJSON && resp.responseJSON.detail) || t('Could not save...');
  110. this.setState({busy: false});
  111. addErrorMessage(errorMessage);
  112. }
  113. };
  114. handleInvite = async (regenerate: boolean) => {
  115. const {organization, params} = this.props;
  116. addLoadingMessage(t('Sending invite...'));
  117. this.setState({busy: true});
  118. try {
  119. const data = await resendMemberInvite(this.api, {
  120. orgId: organization.slug,
  121. memberId: params.memberId,
  122. regenerate,
  123. });
  124. addSuccessMessage(t('Sent invite!'));
  125. if (regenerate) {
  126. this.setState(state => ({member: {...state.member, ...data}}));
  127. }
  128. } catch (_err) {
  129. addErrorMessage(t('Could not send invite'));
  130. }
  131. this.setState({busy: false});
  132. };
  133. handle2faReset = async () => {
  134. const {organization, router} = this.props;
  135. const {user} = this.state.member!;
  136. const requests =
  137. user?.authenticators.map(auth => removeAuthenticator(this.api, user.id, auth.id)) ??
  138. [];
  139. try {
  140. await Promise.all(requests);
  141. router.push(normalizeUrl(`/settings/${organization.slug}/members/`));
  142. addSuccessMessage(t('All authenticators have been removed'));
  143. } catch (err) {
  144. addErrorMessage(t('Error removing authenticators'));
  145. Sentry.captureException(err);
  146. }
  147. };
  148. onAddTeam = (teamSlug: string) => {
  149. const teamRoles = [...this.state.teamRoles];
  150. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  151. if (i !== -1) {
  152. return;
  153. }
  154. teamRoles.push({teamSlug, role: null});
  155. this.setState({teamRoles});
  156. };
  157. onRemoveTeam = (teamSlug: string) => {
  158. const teamRoles = this.state.teamRoles.filter(r => r.teamSlug !== teamSlug);
  159. this.setState({teamRoles});
  160. };
  161. onChangeOrgRole = orgRole => this.setState({orgRole});
  162. onChangeTeamRole = (teamSlug: string, role: string) => {
  163. if (!this.hasTeamRoles) {
  164. return;
  165. }
  166. const teamRoles = [...this.state.teamRoles];
  167. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  168. if (i === -1) {
  169. return;
  170. }
  171. teamRoles[i] = {...teamRoles[i], role};
  172. this.setState({teamRoles});
  173. };
  174. showResetButton = () => {
  175. const {organization} = this.props;
  176. const {member} = this.state;
  177. const {user} = member!;
  178. if (!user || !user.authenticators || organization.require2FA) {
  179. return false;
  180. }
  181. const hasAuth = user.authenticators.length >= 1;
  182. return hasAuth && user.canReset2fa;
  183. };
  184. getTooltip = (): string => {
  185. const {organization} = this.props;
  186. const {member} = this.state;
  187. const {user} = member!;
  188. if (!user) {
  189. return '';
  190. }
  191. if (!user.authenticators) {
  192. return NO_PERMISSION;
  193. }
  194. if (!user.authenticators.length) {
  195. return NOT_ENROLLED;
  196. }
  197. if (!user.canReset2fa) {
  198. return MULTIPLE_ORGS;
  199. }
  200. if (organization.require2FA) {
  201. return TWO_FACTOR_REQUIRED;
  202. }
  203. return '';
  204. };
  205. get memberDeactivated() {
  206. return isMemberDisabledFromLimit(this.state.member);
  207. }
  208. get hasFormChanged() {
  209. const {member, orgRole, teamRoles} = this.state;
  210. if (!member) {
  211. return false;
  212. }
  213. if (orgRole !== member.orgRole || !isEqual(teamRoles, member.teamRoles)) {
  214. return true;
  215. }
  216. return false;
  217. }
  218. renderMemberStatus(member: Member) {
  219. if (this.memberDeactivated) {
  220. return (
  221. <em>
  222. <DisabledMemberTooltip>{t('Deactivated')}</DisabledMemberTooltip>
  223. </em>
  224. );
  225. }
  226. if (member.expired) {
  227. return <em>{t('Invitation Expired')}</em>;
  228. }
  229. if (member.pending) {
  230. return <em>{t('Invitation Pending')}</em>;
  231. }
  232. return t('Active');
  233. }
  234. renderBody() {
  235. const {organization} = this.props;
  236. const {member, orgRole, teamRoles} = this.state;
  237. if (!member) {
  238. return <NotFound />;
  239. }
  240. const {access, features, orgRoleList} = organization;
  241. const canEdit = access.includes('org:write') && !this.memberDeactivated;
  242. const hasTeamRoles = features.includes('team-roles');
  243. const {email, expired, pending, invite_link: inviteLink} = member;
  244. const canResend = !expired;
  245. const showAuth = !pending;
  246. const currentUser = configStore.get('user');
  247. const isCurrentUser = currentUser.email === email;
  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. enforceIdpRoleRestricted={member.flags['idp:role-restricted']}
  352. enforceRetired={hasTeamRoles}
  353. isCurrentUser={isCurrentUser}
  354. disabled={!canEdit}
  355. roleList={orgRoleList}
  356. roleSelected={orgRole}
  357. setSelected={this.onChangeOrgRole}
  358. />
  359. <Teams slugs={member.teams}>
  360. {({initiallyLoaded}) => (
  361. <Fragment>
  362. <TeamSelectForMember
  363. disabled={!canEdit}
  364. organization={organization}
  365. member={member}
  366. selectedOrgRole={orgRole}
  367. selectedTeamRoles={teamRoles}
  368. onChangeTeamRole={this.onChangeTeamRole}
  369. onAddTeam={this.onAddTeam}
  370. onRemoveTeam={this.onRemoveTeam}
  371. loadingTeams={!initiallyLoaded}
  372. />
  373. </Fragment>
  374. )}
  375. </Teams>
  376. <Footer>
  377. <Button
  378. priority="primary"
  379. busy={this.state.busy}
  380. onClick={this.handleSave}
  381. disabled={!canEdit || !this.hasFormChanged}
  382. >
  383. {t('Save Member')}
  384. </Button>
  385. </Footer>
  386. </Fragment>
  387. );
  388. }
  389. }
  390. export default withOrganization(OrganizationMemberDetail);
  391. const ExtraHeaderText = styled('div')`
  392. color: ${p => p.theme.gray300};
  393. font-weight: normal;
  394. font-size: ${p => p.theme.fontSizeLarge};
  395. `;
  396. const Details = styled('div')`
  397. display: grid;
  398. grid-auto-flow: column;
  399. grid-template-columns: 2fr 1fr 1fr;
  400. gap: ${space(2)};
  401. width: 100%;
  402. @media (max-width: ${p => p.theme.breakpoints.small}) {
  403. grid-auto-flow: row;
  404. grid-template-columns: auto;
  405. }
  406. `;
  407. const DetailLabel = styled('div')`
  408. font-weight: bold;
  409. margin-bottom: ${space(0.5)};
  410. color: ${p => p.theme.textColor};
  411. `;
  412. const InviteField = styled('div')`
  413. flex-grow: 1;
  414. `;
  415. const InviteSection = styled('div')`
  416. flex-grow: 1;
  417. display: flex;
  418. gap: ${space(1)};
  419. `;
  420. const Footer = styled('div')`
  421. display: flex;
  422. justify-content: flex-end;
  423. `;