organizationMemberDetail.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import {Fragment} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {removeAuthenticator} from 'sentry/actionCreators/account';
  6. import {
  7. addErrorMessage,
  8. addLoadingMessage,
  9. addSuccessMessage,
  10. } from 'sentry/actionCreators/indicator';
  11. import {resendMemberInvite, updateMember} from 'sentry/actionCreators/members';
  12. import Button from 'sentry/components/button';
  13. import Confirm from 'sentry/components/confirm';
  14. import DateTime from 'sentry/components/dateTime';
  15. import NotFound from 'sentry/components/errors/notFound';
  16. import Field from 'sentry/components/forms/field';
  17. import HookOrDefault from 'sentry/components/hookOrDefault';
  18. import ExternalLink from 'sentry/components/links/externalLink';
  19. import {Panel, PanelBody, PanelHeader, PanelItem} from 'sentry/components/panels';
  20. import TextCopyInput from 'sentry/components/textCopyInput';
  21. import Tooltip from 'sentry/components/tooltip';
  22. import {t, tct} from 'sentry/locale';
  23. import space from 'sentry/styles/space';
  24. import {Member, Organization, Team} from 'sentry/types';
  25. import isMemberDisabledFromLimit from 'sentry/utils/isMemberDisabledFromLimit';
  26. import recreateRoute from 'sentry/utils/recreateRoute';
  27. import Teams from 'sentry/utils/teams';
  28. import withOrganization from 'sentry/utils/withOrganization';
  29. import AsyncView from 'sentry/views/asyncView';
  30. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  31. import TeamSelect from 'sentry/views/settings/components/teamSelect';
  32. import OrganizationRoleSelect from './inviteMember/orgRoleSelect';
  33. const MULTIPLE_ORGS = t('Cannot be reset since user is in more than one organization');
  34. const NOT_ENROLLED = t('Not enrolled in two-factor authentication');
  35. const NO_PERMISSION = t('You do not have permission to perform this action');
  36. const TWO_FACTOR_REQUIRED = t(
  37. 'Cannot be reset since two-factor is required for this organization'
  38. );
  39. type RouteParams = {
  40. memberId: string;
  41. orgId: string;
  42. };
  43. type Props = {
  44. organization: Organization;
  45. } & RouteComponentProps<RouteParams, {}>;
  46. type State = {
  47. member: Member | null;
  48. roleList: Member['roles'];
  49. selectedRole: Member['role'];
  50. } & AsyncView['state'];
  51. const DisabledMemberTooltip = HookOrDefault({
  52. hookName: 'component:disabled-member-tooltip',
  53. defaultComponent: ({children}) => <Fragment>{children}</Fragment>,
  54. });
  55. class OrganizationMemberDetail extends AsyncView<Props, State> {
  56. getDefaultState(): State {
  57. return {
  58. ...super.getDefaultState(),
  59. roleList: [],
  60. selectedRole: '',
  61. member: null,
  62. };
  63. }
  64. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  65. const {organization, params} = this.props;
  66. return [
  67. ['member', `/organizations/${organization.slug}/members/${params.memberId}/`],
  68. ];
  69. }
  70. redirectToMemberPage() {
  71. const {location, params, routes} = this.props;
  72. const members = recreateRoute('members/', {
  73. location,
  74. routes,
  75. params,
  76. stepBack: -2,
  77. });
  78. browserHistory.push(members);
  79. }
  80. handleSave = async () => {
  81. const {organization, params} = this.props;
  82. addLoadingMessage(t('Saving...'));
  83. this.setState({busy: true});
  84. try {
  85. await updateMember(this.api, {
  86. orgId: organization.slug,
  87. memberId: params.memberId,
  88. data: this.state.member,
  89. });
  90. addSuccessMessage(t('Saved'));
  91. this.redirectToMemberPage();
  92. } catch (resp) {
  93. const errorMessage =
  94. (resp && resp.responseJSON && resp.responseJSON.detail) || t('Could not save...');
  95. addErrorMessage(errorMessage);
  96. }
  97. this.setState({busy: false});
  98. };
  99. handleInvite = async (regenerate: boolean) => {
  100. const {organization, params} = this.props;
  101. addLoadingMessage(t('Sending invite...'));
  102. this.setState({busy: true});
  103. try {
  104. const data = await resendMemberInvite(this.api, {
  105. orgId: organization.slug,
  106. memberId: params.memberId,
  107. regenerate,
  108. });
  109. addSuccessMessage(t('Sent invite!'));
  110. if (regenerate) {
  111. this.setState(state => ({member: {...state.member, ...data}}));
  112. }
  113. } catch (_err) {
  114. addErrorMessage(t('Could not send invite'));
  115. }
  116. this.setState({busy: false});
  117. };
  118. handleAddTeam = (team: Team) => {
  119. const {member} = this.state;
  120. if (!member!.teams.includes(team.slug)) {
  121. member!.teams.push(team.slug);
  122. }
  123. this.setState({member});
  124. };
  125. handleRemoveTeam = (removedTeam: string) => {
  126. const {member} = this.state;
  127. this.setState({
  128. member: {
  129. ...member!,
  130. teams: member!.teams.filter(slug => slug !== removedTeam),
  131. },
  132. });
  133. };
  134. handle2faReset = async () => {
  135. const {organization, router} = this.props;
  136. const {user} = this.state.member!;
  137. const requests = user.authenticators.map(auth =>
  138. removeAuthenticator(this.api, user.id, auth.id)
  139. );
  140. try {
  141. await Promise.all(requests);
  142. router.push(`/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. showResetButton = () => {
  150. const {organization} = this.props;
  151. const {member} = this.state;
  152. const {user} = member!;
  153. if (!user || !user.authenticators || organization.require2FA) {
  154. return false;
  155. }
  156. const hasAuth = user.authenticators.length >= 1;
  157. return hasAuth && user.canReset2fa;
  158. };
  159. getTooltip = (): string => {
  160. const {organization} = this.props;
  161. const {member} = this.state;
  162. const {user} = member!;
  163. if (!user) {
  164. return '';
  165. }
  166. if (!user.authenticators) {
  167. return NO_PERMISSION;
  168. }
  169. if (!user.authenticators.length) {
  170. return NOT_ENROLLED;
  171. }
  172. if (!user.canReset2fa) {
  173. return MULTIPLE_ORGS;
  174. }
  175. if (organization.require2FA) {
  176. return TWO_FACTOR_REQUIRED;
  177. }
  178. return '';
  179. };
  180. get memberDeactivated() {
  181. return isMemberDisabledFromLimit(this.state.member);
  182. }
  183. renderMemberStatus(member: Member) {
  184. if (this.memberDeactivated) {
  185. return (
  186. <em>
  187. <DisabledMemberTooltip>{t('Deactivated')}</DisabledMemberTooltip>
  188. </em>
  189. );
  190. }
  191. if (member.expired) {
  192. return <em>{t('Invitation Expired')}</em>;
  193. }
  194. if (member.pending) {
  195. return <em>{t('Invitation Pending')}</em>;
  196. }
  197. return t('Active');
  198. }
  199. renderBody() {
  200. const {organization} = this.props;
  201. const {member} = this.state;
  202. if (!member) {
  203. return <NotFound />;
  204. }
  205. const {access, features} = organization;
  206. const inviteLink = member.invite_link;
  207. const canEdit = access.includes('org:write') && !this.memberDeactivated;
  208. const hasTeamRoles = features.includes('team-roles');
  209. const {email, expired, pending} = member;
  210. const canResend = !expired;
  211. const showAuth = !pending;
  212. return (
  213. <Fragment>
  214. <SettingsPageHeader
  215. title={
  216. <Fragment>
  217. <div>{member.name}</div>
  218. <ExtraHeaderText>{t('Member Settings')}</ExtraHeaderText>
  219. </Fragment>
  220. }
  221. />
  222. <Panel>
  223. <PanelHeader>{t('Basics')}</PanelHeader>
  224. <PanelBody>
  225. <PanelItem>
  226. <OverflowWrapper>
  227. <Details>
  228. <div>
  229. <DetailLabel>{t('Email')}</DetailLabel>
  230. <div>
  231. <ExternalLink href={`mailto:${email}`}>{email}</ExternalLink>
  232. </div>
  233. </div>
  234. <div>
  235. <DetailLabel>{t('Status')}</DetailLabel>
  236. <div data-test-id="member-status">
  237. {this.renderMemberStatus(member)}
  238. </div>
  239. </div>
  240. <div>
  241. <DetailLabel>{t('Added')}</DetailLabel>
  242. <div>
  243. <DateTime dateOnly date={member.dateCreated} />
  244. </div>
  245. </div>
  246. </Details>
  247. {inviteLink && (
  248. <InviteSection>
  249. <div>
  250. <DetailLabel>{t('Invite Link')}</DetailLabel>
  251. <TextCopyInput>{inviteLink}</TextCopyInput>
  252. <p className="help-block">
  253. {t('This unique invite link may only be used by this member.')}
  254. </p>
  255. </div>
  256. <InviteActions>
  257. <Button onClick={() => this.handleInvite(true)}>
  258. {t('Generate New Invite')}
  259. </Button>
  260. {canResend && (
  261. <Button
  262. data-test-id="resend-invite"
  263. onClick={() => this.handleInvite(false)}
  264. >
  265. {t('Resend Invite')}
  266. </Button>
  267. )}
  268. </InviteActions>
  269. </InviteSection>
  270. )}
  271. </OverflowWrapper>
  272. </PanelItem>
  273. </PanelBody>
  274. </Panel>
  275. {showAuth && (
  276. <Panel>
  277. <PanelHeader>{t('Authentication')}</PanelHeader>
  278. <PanelBody>
  279. <Field
  280. alignRight
  281. flexibleControlStateSize
  282. label={t('Reset two-factor authentication')}
  283. help={t(
  284. 'Resetting two-factor authentication will remove all two-factor authentication methods for this member.'
  285. )}
  286. >
  287. <Tooltip
  288. data-test-id="reset-2fa-tooltip"
  289. disabled={this.showResetButton()}
  290. title={this.getTooltip()}
  291. >
  292. <Confirm
  293. disabled={!this.showResetButton()}
  294. message={tct(
  295. 'Are you sure you want to disable all two-factor authentication methods for [name]?',
  296. {name: member.name ? member.name : 'this member'}
  297. )}
  298. onConfirm={this.handle2faReset}
  299. data-test-id="reset-2fa-confirm"
  300. >
  301. <Button data-test-id="reset-2fa" priority="danger">
  302. {t('Reset two-factor authentication')}
  303. </Button>
  304. </Confirm>
  305. </Tooltip>
  306. </Field>
  307. </PanelBody>
  308. </Panel>
  309. )}
  310. <OrganizationRoleSelect
  311. enforceAllowed={false}
  312. enforceRetired={hasTeamRoles}
  313. disabled={!canEdit}
  314. roleList={member.roles}
  315. roleSelected={member.role}
  316. setSelected={slug => this.setState({member: {...member, role: slug}})}
  317. />
  318. <Teams slugs={member.teams}>
  319. {({teams, initiallyLoaded}) => (
  320. <TeamSelect
  321. organization={organization}
  322. selectedTeams={teams}
  323. disabled={!canEdit}
  324. onAddTeam={this.handleAddTeam}
  325. onRemoveTeam={this.handleRemoveTeam}
  326. loadingTeams={!initiallyLoaded}
  327. />
  328. )}
  329. </Teams>
  330. <Footer>
  331. <Button
  332. priority="primary"
  333. busy={this.state.busy}
  334. onClick={this.handleSave}
  335. disabled={!canEdit}
  336. >
  337. {t('Save Member')}
  338. </Button>
  339. </Footer>
  340. </Fragment>
  341. );
  342. }
  343. }
  344. export default withOrganization(OrganizationMemberDetail);
  345. const ExtraHeaderText = styled('div')`
  346. color: ${p => p.theme.gray300};
  347. font-weight: normal;
  348. font-size: ${p => p.theme.fontSizeLarge};
  349. `;
  350. const Details = styled('div')`
  351. display: grid;
  352. grid-auto-flow: column;
  353. grid-template-columns: 2fr 1fr 1fr;
  354. gap: ${space(2)};
  355. width: 100%;
  356. @media (max-width: ${p => p.theme.breakpoints.small}) {
  357. grid-auto-flow: row;
  358. grid-template-columns: auto;
  359. }
  360. `;
  361. const DetailLabel = styled('div')`
  362. font-weight: bold;
  363. margin-bottom: ${space(0.5)};
  364. color: ${p => p.theme.textColor};
  365. `;
  366. const OverflowWrapper = styled('div')`
  367. overflow: hidden;
  368. flex: 1;
  369. `;
  370. const InviteSection = styled('div')`
  371. border-top: 1px solid ${p => p.theme.border};
  372. margin-top: ${space(2)};
  373. padding-top: ${space(2)};
  374. `;
  375. const InviteActions = styled('div')`
  376. display: grid;
  377. gap: ${space(1)};
  378. grid-auto-flow: column;
  379. justify-content: flex-end;
  380. margin-top: ${space(2)};
  381. `;
  382. const Footer = styled('div')`
  383. display: flex;
  384. justify-content: flex-end;
  385. `;