organizationMemberDetail.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 TeamSelect from 'sentry/views/settings/components/teamSelect';
  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. member: Member | null;
  51. orgRole: Member['orgRole'];
  52. teamRoles: Member['teamRoles'];
  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. member: null,
  67. orgRole: '',
  68. teamRoles: [],
  69. };
  70. }
  71. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  72. const {organization, params} = this.props;
  73. return [
  74. ['member', `/organizations/${organization.slug}/members/${params.memberId}/`],
  75. ];
  76. }
  77. onRequestSuccess({data, stateKey}: {data: Member; stateKey: string}) {
  78. if (stateKey === 'member') {
  79. const {orgRole, teamRoles} = data;
  80. this.setState({orgRole, teamRoles});
  81. }
  82. }
  83. handleSave = async () => {
  84. const {organization, params} = this.props;
  85. const {orgRole, teamRoles} = this.state;
  86. addLoadingMessage(t('Saving...'));
  87. this.setState({busy: true});
  88. try {
  89. const updatedMember = await updateMember(this.api, {
  90. orgId: organization.slug,
  91. memberId: params.memberId,
  92. data: {orgRole, teamRoles} as any,
  93. });
  94. this.setState({member: updatedMember, busy: false});
  95. addSuccessMessage(t('Saved'));
  96. } catch (resp) {
  97. const errorMessage =
  98. (resp && resp.responseJSON && resp.responseJSON.detail) || t('Could not save...');
  99. this.setState({busy: false});
  100. addErrorMessage(errorMessage);
  101. }
  102. };
  103. handleInvite = async (regenerate: boolean) => {
  104. const {organization, params} = this.props;
  105. addLoadingMessage(t('Sending invite...'));
  106. this.setState({busy: true});
  107. try {
  108. const data = await resendMemberInvite(this.api, {
  109. orgId: organization.slug,
  110. memberId: params.memberId,
  111. regenerate,
  112. });
  113. addSuccessMessage(t('Sent invite!'));
  114. if (regenerate) {
  115. this.setState(state => ({member: {...state.member, ...data}}));
  116. }
  117. } catch (_err) {
  118. addErrorMessage(t('Could not send invite'));
  119. }
  120. this.setState({busy: false});
  121. };
  122. handle2faReset = async () => {
  123. const {organization, router} = this.props;
  124. const {user} = this.state.member!;
  125. const requests = user.authenticators.map(auth =>
  126. removeAuthenticator(this.api, user.id, auth.id)
  127. );
  128. try {
  129. await Promise.all(requests);
  130. router.push(normalizeUrl(`/settings/${organization.slug}/members/`));
  131. addSuccessMessage(t('All authenticators have been removed'));
  132. } catch (err) {
  133. addErrorMessage(t('Error removing authenticators'));
  134. Sentry.captureException(err);
  135. }
  136. };
  137. onAddTeam = (teamSlug: string) => {
  138. const teamRoles = [...this.state.teamRoles];
  139. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  140. if (i !== -1) {
  141. return;
  142. }
  143. teamRoles.push({teamSlug, role: null});
  144. this.setState({teamRoles});
  145. };
  146. onRemoveTeam = (teamSlug: string) => {
  147. const teamRoles = this.state.teamRoles.filter(r => r.teamSlug !== teamSlug);
  148. this.setState({teamRoles});
  149. };
  150. onChangeOrgRole = orgRole => this.setState({orgRole});
  151. onChangeTeamRole = (teamSlug: string, role: string) => {
  152. if (!this.hasTeamRoles) {
  153. return;
  154. }
  155. const teamRoles = [...this.state.teamRoles];
  156. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  157. if (i === -1) {
  158. return;
  159. }
  160. teamRoles[i] = {...teamRoles[i], role};
  161. this.setState({teamRoles});
  162. };
  163. showResetButton = () => {
  164. const {organization} = this.props;
  165. const {member} = this.state;
  166. const {user} = member!;
  167. if (!user || !user.authenticators || organization.require2FA) {
  168. return false;
  169. }
  170. const hasAuth = user.authenticators.length >= 1;
  171. return hasAuth && user.canReset2fa;
  172. };
  173. getTooltip = (): string => {
  174. const {organization} = this.props;
  175. const {member} = this.state;
  176. const {user} = member!;
  177. if (!user) {
  178. return '';
  179. }
  180. if (!user.authenticators) {
  181. return NO_PERMISSION;
  182. }
  183. if (!user.authenticators.length) {
  184. return NOT_ENROLLED;
  185. }
  186. if (!user.canReset2fa) {
  187. return MULTIPLE_ORGS;
  188. }
  189. if (organization.require2FA) {
  190. return TWO_FACTOR_REQUIRED;
  191. }
  192. return '';
  193. };
  194. get memberDeactivated() {
  195. return isMemberDisabledFromLimit(this.state.member);
  196. }
  197. get hasFormChanged() {
  198. const {member, orgRole, teamRoles} = this.state;
  199. if (!member) {
  200. return false;
  201. }
  202. if (orgRole !== member.orgRole || !isEqual(teamRoles, member?.teamRoles)) {
  203. return true;
  204. }
  205. return false;
  206. }
  207. renderMemberStatus(member: Member) {
  208. if (this.memberDeactivated) {
  209. return (
  210. <em>
  211. <DisabledMemberTooltip>{t('Deactivated')}</DisabledMemberTooltip>
  212. </em>
  213. );
  214. }
  215. if (member.expired) {
  216. return <em>{t('Invitation Expired')}</em>;
  217. }
  218. if (member.pending) {
  219. return <em>{t('Invitation Pending')}</em>;
  220. }
  221. return t('Active');
  222. }
  223. renderBody() {
  224. const {organization} = this.props;
  225. const {member, orgRole, teamRoles} = this.state;
  226. if (!member) {
  227. return <NotFound />;
  228. }
  229. const {access, features, orgRoleList} = organization;
  230. const canEdit = access.includes('org:write') && !this.memberDeactivated;
  231. const hasTeamRoles = features.includes('team-roles');
  232. const {email, expired, pending, invite_link: inviteLink} = member;
  233. const canResend = !expired;
  234. const showAuth = !pending;
  235. const currentUser = configStore.get('user');
  236. const isCurrentUser = currentUser.email === email;
  237. return (
  238. <Fragment>
  239. <SettingsPageHeader
  240. title={
  241. <Fragment>
  242. <div>{member.name}</div>
  243. <ExtraHeaderText>{t('Member Settings')}</ExtraHeaderText>
  244. </Fragment>
  245. }
  246. />
  247. <Panel>
  248. <PanelHeader>{t('Basics')}</PanelHeader>
  249. <PanelBody>
  250. <PanelItem>
  251. <Details>
  252. <div>
  253. <DetailLabel>{t('Email')}</DetailLabel>
  254. <div>
  255. <ExternalLink href={`mailto:${email}`}>{email}</ExternalLink>
  256. </div>
  257. </div>
  258. <div>
  259. <DetailLabel>{t('Status')}</DetailLabel>
  260. <div data-test-id="member-status">
  261. {this.renderMemberStatus(member)}
  262. </div>
  263. </div>
  264. <div>
  265. <DetailLabel>{t('Added')}</DetailLabel>
  266. <div>
  267. <DateTime dateOnly date={member.dateCreated} />
  268. </div>
  269. </div>
  270. </Details>
  271. </PanelItem>
  272. <PanelItem>
  273. {inviteLink && (
  274. <InviteSection>
  275. <InviteField>
  276. <DetailLabel>{t('Invite Link')}</DetailLabel>
  277. <TextCopyInput>{inviteLink}</TextCopyInput>
  278. <p className="help-block">
  279. {t(
  280. 'This invite link can be used by anyone who knows it. Keep it secure!'
  281. )}
  282. </p>
  283. </InviteField>
  284. <ButtonBar gap={1}>
  285. {canResend && (
  286. <Button
  287. data-test-id="resend-invite"
  288. onClick={() => this.handleInvite(false)}
  289. >
  290. {t('Resend Invite')}
  291. </Button>
  292. )}
  293. <Button
  294. onClick={() => this.handleInvite(true)}
  295. title={t(
  296. 'Generate New Invite. This will invalidate the previous invite link!'
  297. )}
  298. priority="danger"
  299. aria-label={t('Generate New Invite')}
  300. icon={<IconRefresh size="sm" />}
  301. />
  302. </ButtonBar>
  303. </InviteSection>
  304. )}
  305. </PanelItem>
  306. </PanelBody>
  307. </Panel>
  308. {showAuth && (
  309. <Panel>
  310. <PanelHeader>{t('Authentication')}</PanelHeader>
  311. <PanelBody>
  312. <FieldGroup
  313. alignRight
  314. flexibleControlStateSize
  315. label={t('Reset two-factor authentication')}
  316. help={t(
  317. 'Resetting two-factor authentication will remove all two-factor authentication methods for this member.'
  318. )}
  319. >
  320. <Tooltip disabled={this.showResetButton()} title={this.getTooltip()}>
  321. <Confirm
  322. disabled={!this.showResetButton()}
  323. message={tct(
  324. 'Are you sure you want to disable all two-factor authentication methods for [name]?',
  325. {name: member.name ? member.name : 'this member'}
  326. )}
  327. onConfirm={this.handle2faReset}
  328. >
  329. <Button priority="danger">
  330. {t('Reset two-factor authentication')}
  331. </Button>
  332. </Confirm>
  333. </Tooltip>
  334. </FieldGroup>
  335. </PanelBody>
  336. </Panel>
  337. )}
  338. <OrganizationRoleSelect
  339. enforceAllowed={false}
  340. enforceIdpRoleRestricted={member.flags['idp:role-restricted']}
  341. enforceRetired={hasTeamRoles}
  342. isCurrentUser={isCurrentUser}
  343. disabled={!canEdit}
  344. roleList={orgRoleList}
  345. roleSelected={orgRole}
  346. setSelected={this.onChangeOrgRole}
  347. />
  348. <Teams slugs={member.teams}>
  349. {({initiallyLoaded}) => (
  350. <TeamSelect
  351. enforceIdpProvisioned
  352. disabled={!canEdit}
  353. organization={organization}
  354. selectedOrgRole={orgRole}
  355. selectedTeamRoles={teamRoles}
  356. onChangeTeamRole={this.onChangeTeamRole}
  357. onAddTeam={this.onAddTeam}
  358. onRemoveTeam={this.onRemoveTeam}
  359. loadingTeams={!initiallyLoaded}
  360. />
  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 InviteField = styled('div')`
  400. flex-grow: 1;
  401. `;
  402. const InviteSection = styled('div')`
  403. flex-grow: 1;
  404. display: flex;
  405. gap: ${space(1)};
  406. `;
  407. const Footer = styled('div')`
  408. display: flex;
  409. justify-content: flex-end;
  410. `;