organizationMemberDetail.tsx 13 KB

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