organizationMemberDetail.tsx 13 KB

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