organizationMemberDetail.tsx 13 KB

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