organizationMemberDetail.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 {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 DeprecatedAsyncView, {AsyncViewState} from 'sentry/views/deprecatedAsyncView';
  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. interface Props extends RouteComponentProps<RouteParams, {}> {
  47. organization: Organization;
  48. }
  49. interface State extends AsyncViewState {
  50. groupOrgRoles: Member['groupOrgRoles']; // Form state
  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. groupOrgRoles: [],
  68. member: null,
  69. orgRole: '',
  70. teamRoles: [],
  71. };
  72. }
  73. getEndpoints(): ReturnType<DeprecatedAsyncView['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 =>
  138. removeAuthenticator(this.api, user.id, auth.id)
  139. ) ?? [];
  140. try {
  141. await Promise.all(requests);
  142. router.push(normalizeUrl(`/settings/${organization.slug}/members/`));
  143. addSuccessMessage(t('All authenticators have been removed'));
  144. } catch (err) {
  145. addErrorMessage(t('Error removing authenticators'));
  146. Sentry.captureException(err);
  147. }
  148. };
  149. onAddTeam = (teamSlug: string) => {
  150. const teamRoles = [...this.state.teamRoles];
  151. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  152. if (i !== -1) {
  153. return;
  154. }
  155. teamRoles.push({teamSlug, role: null});
  156. this.setState({teamRoles});
  157. };
  158. onRemoveTeam = (teamSlug: string) => {
  159. const teamRoles = this.state.teamRoles.filter(r => r.teamSlug !== teamSlug);
  160. this.setState({teamRoles});
  161. };
  162. onChangeOrgRole = orgRole => this.setState({orgRole});
  163. onChangeTeamRole = (teamSlug: string, role: string) => {
  164. if (!this.hasTeamRoles) {
  165. return;
  166. }
  167. const teamRoles = [...this.state.teamRoles];
  168. const i = teamRoles.findIndex(r => r.teamSlug === teamSlug);
  169. if (i === -1) {
  170. return;
  171. }
  172. teamRoles[i] = {...teamRoles[i], role};
  173. this.setState({teamRoles});
  174. };
  175. showResetButton = () => {
  176. const {organization} = this.props;
  177. const {member} = this.state;
  178. const {user} = member!;
  179. if (!user || !user.authenticators || organization.require2FA) {
  180. return false;
  181. }
  182. const hasAuth = user.authenticators.length >= 1;
  183. return hasAuth && user.canReset2fa;
  184. };
  185. getTooltip = (): string => {
  186. const {organization} = this.props;
  187. const {member} = this.state;
  188. const {user} = member!;
  189. if (!user) {
  190. return '';
  191. }
  192. if (!user.authenticators) {
  193. return NO_PERMISSION;
  194. }
  195. if (!user.authenticators.length) {
  196. return NOT_ENROLLED;
  197. }
  198. if (!user.canReset2fa) {
  199. return MULTIPLE_ORGS;
  200. }
  201. if (organization.require2FA) {
  202. return TWO_FACTOR_REQUIRED;
  203. }
  204. return '';
  205. };
  206. get memberDeactivated() {
  207. return isMemberDisabledFromLimit(this.state.member);
  208. }
  209. get hasFormChanged() {
  210. const {member, orgRole, teamRoles} = this.state;
  211. if (!member) {
  212. return false;
  213. }
  214. if (orgRole !== member.orgRole || !isEqual(teamRoles, member.teamRoles)) {
  215. return true;
  216. }
  217. return false;
  218. }
  219. renderMemberStatus(member: Member) {
  220. if (this.memberDeactivated) {
  221. return (
  222. <em>
  223. <DisabledMemberTooltip>{t('Deactivated')}</DisabledMemberTooltip>
  224. </em>
  225. );
  226. }
  227. if (member.expired) {
  228. return <em>{t('Invitation Expired')}</em>;
  229. }
  230. if (member.pending) {
  231. return <em>{t('Invitation Pending')}</em>;
  232. }
  233. return t('Active');
  234. }
  235. renderBody() {
  236. const {organization} = this.props;
  237. const {member, orgRole, teamRoles} = this.state;
  238. if (!member) {
  239. return <NotFound />;
  240. }
  241. const {access, orgRoleList} = organization;
  242. const canEdit = access.includes('org:write') && !this.memberDeactivated;
  243. const isPartnershipUser = member.flags['partnership:restricted'] === true;
  244. const {email, expired, pending} = member;
  245. const canResend = !expired;
  246. const showAuth = !pending;
  247. const showResendButton = (member.pending || member.expired) && canResend;
  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 hasButtons={showResendButton}>
  260. {t('Basics')}
  261. {showResendButton && (
  262. <Button
  263. data-test-id="resend-invite"
  264. size="xs"
  265. priority="primary"
  266. icon={<IconRefresh />}
  267. title={t('Generate a new invite link and send a new email.')}
  268. onClick={() => this.handleInvite(true)}
  269. >
  270. {t('Resend Invite')}
  271. </Button>
  272. )}
  273. </PanelHeader>
  274. <PanelBody>
  275. <PanelItem>
  276. <Details>
  277. <div>
  278. <DetailLabel>{t('Email')}</DetailLabel>
  279. <div>
  280. <ExternalLink href={`mailto:${email}`}>{email}</ExternalLink>
  281. </div>
  282. </div>
  283. <div>
  284. <DetailLabel>{t('Status')}</DetailLabel>
  285. <div data-test-id="member-status">
  286. {this.renderMemberStatus(member)}
  287. </div>
  288. </div>
  289. <div>
  290. <DetailLabel>{t('Added')}</DetailLabel>
  291. <div>
  292. <DateTime dateOnly date={member.dateCreated} />
  293. </div>
  294. </div>
  295. </Details>
  296. </PanelItem>
  297. </PanelBody>
  298. </Panel>
  299. {showAuth && (
  300. <Panel>
  301. <PanelHeader>{t('Authentication')}</PanelHeader>
  302. <PanelBody>
  303. <FieldGroup
  304. alignRight
  305. flexibleControlStateSize
  306. label={t('Reset two-factor authentication')}
  307. help={t(
  308. 'Resetting two-factor authentication will remove all two-factor authentication methods for this member.'
  309. )}
  310. >
  311. <Tooltip disabled={this.showResetButton()} title={this.getTooltip()}>
  312. <Confirm
  313. disabled={!this.showResetButton()}
  314. message={tct(
  315. 'Are you sure you want to disable all two-factor authentication methods for [name]?',
  316. {name: member.name ? member.name : 'this member'}
  317. )}
  318. onConfirm={this.handle2faReset}
  319. >
  320. <Button priority="danger">
  321. {t('Reset two-factor authentication')}
  322. </Button>
  323. </Confirm>
  324. </Tooltip>
  325. </FieldGroup>
  326. </PanelBody>
  327. </Panel>
  328. )}
  329. <OrganizationRoleSelect
  330. enforceAllowed={false}
  331. enforceRetired={this.hasTeamRoles}
  332. disabled={!canEdit || isPartnershipUser}
  333. roleList={orgRoleList}
  334. roleSelected={orgRole}
  335. setSelected={this.onChangeOrgRole}
  336. helpText={
  337. isPartnershipUser
  338. ? t('You cannot make changes to this partner-provisioned user.')
  339. : undefined
  340. }
  341. />
  342. <Teams slugs={member.teams}>
  343. {({initiallyLoaded}) => (
  344. <Fragment>
  345. <TeamSelectForMember
  346. disabled={!canEdit}
  347. organization={organization}
  348. member={member}
  349. selectedOrgRole={orgRole}
  350. selectedTeamRoles={teamRoles}
  351. onChangeTeamRole={this.onChangeTeamRole}
  352. onAddTeam={this.onAddTeam}
  353. onRemoveTeam={this.onRemoveTeam}
  354. loadingTeams={!initiallyLoaded}
  355. />
  356. </Fragment>
  357. )}
  358. </Teams>
  359. <Footer>
  360. <Button
  361. priority="primary"
  362. busy={this.state.busy}
  363. onClick={this.handleSave}
  364. disabled={!canEdit || !this.hasFormChanged}
  365. >
  366. {t('Save Member')}
  367. </Button>
  368. </Footer>
  369. </Fragment>
  370. );
  371. }
  372. }
  373. export default withOrganization(OrganizationMemberDetail);
  374. const ExtraHeaderText = styled('div')`
  375. color: ${p => p.theme.gray300};
  376. font-weight: normal;
  377. font-size: ${p => p.theme.fontSizeLarge};
  378. `;
  379. const Details = styled('div')`
  380. display: grid;
  381. grid-auto-flow: column;
  382. grid-template-columns: 2fr 1fr 1fr;
  383. gap: ${space(2)};
  384. width: 100%;
  385. @media (max-width: ${p => p.theme.breakpoints.small}) {
  386. grid-auto-flow: row;
  387. grid-template-columns: auto;
  388. }
  389. `;
  390. const DetailLabel = styled('div')`
  391. font-weight: bold;
  392. margin-bottom: ${space(0.5)};
  393. color: ${p => p.theme.textColor};
  394. `;
  395. const Footer = styled('div')`
  396. display: flex;
  397. justify-content: flex-end;
  398. `;