accountSecurityEnroll.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import {Fragment} from 'react';
  2. import {WithRouterProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {QRCodeCanvas} from 'qrcode.react';
  5. import {
  6. addErrorMessage,
  7. addLoadingMessage,
  8. addSuccessMessage,
  9. } from 'sentry/actionCreators/indicator';
  10. import {openRecoveryOptions} from 'sentry/actionCreators/modal';
  11. import {fetchOrganizationByMember} from 'sentry/actionCreators/organizations';
  12. import {Alert} from 'sentry/components/alert';
  13. import {Button} from 'sentry/components/button';
  14. import ButtonBar from 'sentry/components/buttonBar';
  15. import CircleIndicator from 'sentry/components/circleIndicator';
  16. import FieldGroup from 'sentry/components/forms/fieldGroup';
  17. import Form, {FormProps} from 'sentry/components/forms/form';
  18. import JsonForm from 'sentry/components/forms/jsonForm';
  19. import FormModel from 'sentry/components/forms/model';
  20. import {FieldObject} from 'sentry/components/forms/types';
  21. import {PanelItem} from 'sentry/components/panels';
  22. import TextCopyInput from 'sentry/components/textCopyInput';
  23. import U2fsign from 'sentry/components/u2f/u2fsign';
  24. import {t} from 'sentry/locale';
  25. import {space} from 'sentry/styles/space';
  26. import {Authenticator} from 'sentry/types';
  27. import getPendingInvite from 'sentry/utils/getPendingInvite';
  28. // eslint-disable-next-line no-restricted-imports
  29. import withSentryRouter from 'sentry/utils/withSentryRouter';
  30. import AsyncView from 'sentry/views/asyncView';
  31. import RemoveConfirm from 'sentry/views/settings/account/accountSecurity/components/removeConfirm';
  32. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  33. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  34. type getFieldsOpts = {
  35. authenticator: Authenticator;
  36. /**
  37. * Flag to track if totp has been sent
  38. */
  39. hasSentCode: boolean;
  40. /**
  41. * Callback to reset SMS 2fa enrollment
  42. */
  43. onSmsReset: () => void;
  44. /**
  45. * Callback when u2f device is activated
  46. */
  47. onU2fTap: React.ComponentProps<typeof U2fsign>['onTap'];
  48. /**
  49. * Flag to track if we are currently sending the otp code
  50. */
  51. sendingCode: boolean;
  52. };
  53. /**
  54. * Retrieve additional form fields (or modify ones) based on 2fa method
  55. */
  56. const getFields = ({
  57. authenticator,
  58. hasSentCode,
  59. sendingCode,
  60. onSmsReset,
  61. onU2fTap,
  62. }: getFieldsOpts): null | FieldObject[] => {
  63. const {form} = authenticator;
  64. if (!form) {
  65. return null;
  66. }
  67. if (authenticator.id === 'totp') {
  68. return [
  69. () => (
  70. <CodeContainer key="qrcode">
  71. <StyledQRCode
  72. aria-label={t('Enrollment QR Code')}
  73. value={authenticator.qrcode}
  74. size={228}
  75. />
  76. </CodeContainer>
  77. ),
  78. () => (
  79. <FieldGroup key="secret" label={t('Authenticator secret')}>
  80. <TextCopyInput>{authenticator.secret ?? ''}</TextCopyInput>
  81. </FieldGroup>
  82. ),
  83. ...form,
  84. () => (
  85. <Actions key="confirm">
  86. <Button priority="primary" type="submit">
  87. {t('Confirm')}
  88. </Button>
  89. </Actions>
  90. ),
  91. ];
  92. }
  93. // Sms Form needs a start over button + confirm button
  94. // Also inputs being disabled vary based on hasSentCode
  95. if (authenticator.id === 'sms') {
  96. // Ideally we would have greater flexibility when rendering footer
  97. return [
  98. {...form[0], disabled: sendingCode || hasSentCode},
  99. ...(hasSentCode ? [{...form[1], required: true}] : []),
  100. () => (
  101. <Actions key="sms-footer">
  102. <ButtonBar gap={1}>
  103. {hasSentCode && <Button onClick={onSmsReset}>{t('Start Over')}</Button>}
  104. <Button priority="primary" type="submit">
  105. {hasSentCode ? t('Confirm') : t('Send Code')}
  106. </Button>
  107. </ButtonBar>
  108. </Actions>
  109. ),
  110. ];
  111. }
  112. // Need to render device name field + U2f component
  113. if (authenticator.id === 'u2f') {
  114. const deviceNameField = form.find(({name}) => name === 'deviceName')!;
  115. return [
  116. deviceNameField,
  117. () => (
  118. <U2fsign
  119. key="u2f-enroll"
  120. style={{marginBottom: 0}}
  121. challengeData={authenticator.challenge}
  122. displayMode="enroll"
  123. onTap={onU2fTap}
  124. />
  125. ),
  126. ];
  127. }
  128. return null;
  129. };
  130. type Props = AsyncView['props'] & WithRouterProps<{authId: string}, {}> & {};
  131. type State = AsyncView['state'] & {
  132. authenticator: Authenticator | null;
  133. hasSentCode: boolean;
  134. sendingCode: boolean;
  135. };
  136. type PendingInvite = ReturnType<typeof getPendingInvite>;
  137. /**
  138. * Renders necessary forms in order to enroll user in 2fa
  139. */
  140. class AccountSecurityEnroll extends AsyncView<Props, State> {
  141. formModel = new FormModel();
  142. getTitle() {
  143. return t('Security');
  144. }
  145. getDefaultState() {
  146. return {...super.getDefaultState(), hasSentCode: false};
  147. }
  148. get authenticatorEndpoint() {
  149. return `/users/me/authenticators/${this.props.params.authId}/`;
  150. }
  151. get enrollEndpoint() {
  152. return `${this.authenticatorEndpoint}enroll/`;
  153. }
  154. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  155. const errorHandler = (err: any) => {
  156. const alreadyEnrolled =
  157. err &&
  158. err.status === 400 &&
  159. err.responseJSON &&
  160. err.responseJSON.details === 'Already enrolled';
  161. if (alreadyEnrolled) {
  162. this.props.router.push('/settings/account/security/');
  163. addErrorMessage(t('Already enrolled'));
  164. }
  165. // Allow the endpoint to fail if the user is already enrolled
  166. return alreadyEnrolled;
  167. };
  168. return [['authenticator', this.enrollEndpoint, {}, {allowError: errorHandler}]];
  169. }
  170. componentDidMount() {
  171. this.pendingInvitation = getPendingInvite();
  172. }
  173. pendingInvitation: PendingInvite = null;
  174. get authenticatorName() {
  175. return this.state.authenticator?.name ?? 'Authenticator';
  176. }
  177. // This resets state so that user can re-enter their phone number again
  178. handleSmsReset = () => this.setState({hasSentCode: false}, this.remountComponent);
  179. // Handles SMS authenticators
  180. handleSmsSubmit = async (dataModel: any) => {
  181. const {authenticator, hasSentCode} = this.state;
  182. const {phone, otp} = dataModel;
  183. // Don't submit if empty
  184. if (!phone || !authenticator) {
  185. return;
  186. }
  187. const data = {
  188. phone,
  189. // Make sure `otp` is undefined if we are submitting OTP verification
  190. // Otherwise API will think that we are on verification step (e.g. after submitting phone)
  191. otp: hasSentCode ? otp : undefined,
  192. secret: authenticator.secret,
  193. };
  194. // Only show loading when submitting OTP
  195. this.setState({sendingCode: !hasSentCode});
  196. if (!hasSentCode) {
  197. addLoadingMessage(t('Sending code to %s...', data.phone));
  198. } else {
  199. addLoadingMessage(t('Verifying OTP...'));
  200. }
  201. try {
  202. await this.api.requestPromise(this.enrollEndpoint, {data});
  203. } catch (error) {
  204. this.formModel.resetForm();
  205. addErrorMessage(
  206. this.state.hasSentCode ? t('Incorrect OTP') : t('Error sending SMS')
  207. );
  208. this.setState({
  209. hasSentCode: false,
  210. sendingCode: false,
  211. });
  212. // Re-mount because we want to fetch a fresh secret
  213. this.remountComponent();
  214. return;
  215. }
  216. if (!hasSentCode) {
  217. // Just successfully finished sending OTP to user
  218. this.setState({hasSentCode: true, sendingCode: false});
  219. addSuccessMessage(t('Sent code to %s', data.phone));
  220. } else {
  221. // OTP was accepted and SMS was added as a 2fa method
  222. this.handleEnrollSuccess();
  223. }
  224. };
  225. // Handle u2f device tap
  226. handleU2fTap = async (tapData: any) => {
  227. const data = {deviceName: this.formModel.getValue('deviceName'), ...tapData};
  228. this.setState({loading: true});
  229. try {
  230. await this.api.requestPromise(this.enrollEndpoint, {data});
  231. } catch (err) {
  232. this.handleEnrollError();
  233. return;
  234. }
  235. this.handleEnrollSuccess();
  236. };
  237. // Currently only TOTP uses this
  238. handleTotpSubmit = async (dataModel: any) => {
  239. if (!this.state.authenticator) {
  240. return;
  241. }
  242. const data = {
  243. ...(dataModel ?? {}),
  244. secret: this.state.authenticator.secret,
  245. };
  246. this.setState({loading: true});
  247. try {
  248. await this.api.requestPromise(this.enrollEndpoint, {method: 'POST', data});
  249. } catch (err) {
  250. this.handleEnrollError();
  251. return;
  252. }
  253. this.handleEnrollSuccess();
  254. };
  255. handleSubmit: FormProps['onSubmit'] = data => {
  256. const id = this.state.authenticator?.id;
  257. if (id === 'totp') {
  258. this.handleTotpSubmit(data);
  259. return;
  260. }
  261. if (id === 'sms') {
  262. this.handleSmsSubmit(data);
  263. return;
  264. }
  265. };
  266. // Handler when we successfully add a 2fa device
  267. async handleEnrollSuccess() {
  268. // If we're pending approval of an invite, the user will have just joined
  269. // the organization when completing 2fa enrollment. We should reload the
  270. // organization context in that case to assign them to the org.
  271. if (this.pendingInvitation) {
  272. await fetchOrganizationByMember(
  273. this.api,
  274. this.pendingInvitation.memberId.toString(),
  275. {
  276. addOrg: true,
  277. fetchOrgDetails: true,
  278. }
  279. );
  280. }
  281. this.props.router.push('/settings/account/security/');
  282. openRecoveryOptions({authenticatorName: this.authenticatorName});
  283. }
  284. // Handler when we failed to add a 2fa device
  285. handleEnrollError() {
  286. this.setState({loading: false});
  287. addErrorMessage(t('Error adding %s authenticator', this.authenticatorName));
  288. }
  289. // Removes an authenticator
  290. handleRemove = async () => {
  291. const {authenticator} = this.state;
  292. if (!authenticator || !authenticator.authId) {
  293. return;
  294. }
  295. // `authenticator.authId` is NOT the same as `props.params.authId` This is
  296. // for backwards compatibility with API endpoint
  297. try {
  298. await this.api.requestPromise(this.authenticatorEndpoint, {method: 'DELETE'});
  299. } catch (err) {
  300. addErrorMessage(t('Error removing authenticator'));
  301. return;
  302. }
  303. this.props.router.push('/settings/account/security/');
  304. addSuccessMessage(t('Authenticator has been removed'));
  305. };
  306. renderBody() {
  307. const {authenticator, hasSentCode, sendingCode} = this.state;
  308. if (!authenticator) {
  309. return null;
  310. }
  311. const fields = getFields({
  312. authenticator,
  313. hasSentCode,
  314. sendingCode,
  315. onSmsReset: this.handleSmsReset,
  316. onU2fTap: this.handleU2fTap,
  317. });
  318. // Attempt to extract `defaultValue` from server generated form fields
  319. const defaultValues = fields
  320. ? fields
  321. .filter(
  322. field =>
  323. typeof field !== 'function' && typeof field.defaultValue !== 'undefined'
  324. )
  325. .map(field => [
  326. field.name,
  327. typeof field !== 'function' ? field.defaultValue : '',
  328. ])
  329. .reduce((acc, [name, value]) => {
  330. acc[name] = value;
  331. return acc;
  332. }, {})
  333. : {};
  334. const isActive = authenticator.isEnrolled || authenticator.status === 'rotation';
  335. return (
  336. <Fragment>
  337. <SettingsPageHeader
  338. title={
  339. <Fragment>
  340. <span>{authenticator.name}</span>
  341. <CircleIndicator
  342. role="status"
  343. aria-label={
  344. isActive
  345. ? t('Authentication Method Active')
  346. : t('Authentication Method Inactive')
  347. }
  348. enabled={isActive}
  349. css={{marginLeft: 6}}
  350. />
  351. </Fragment>
  352. }
  353. action={
  354. authenticator.isEnrolled &&
  355. authenticator.removeButton && (
  356. <RemoveConfirm onConfirm={this.handleRemove}>
  357. <Button priority="danger">{authenticator.removeButton}</Button>
  358. </RemoveConfirm>
  359. )
  360. }
  361. />
  362. <TextBlock>{authenticator.description}</TextBlock>
  363. {authenticator.rotationWarning && authenticator.status === 'rotation' && (
  364. <Alert type="warning" showIcon>
  365. {authenticator.rotationWarning}
  366. </Alert>
  367. )}
  368. {!!authenticator.form?.length && (
  369. <Form
  370. model={this.formModel}
  371. apiMethod="POST"
  372. apiEndpoint={this.authenticatorEndpoint}
  373. onSubmit={this.handleSubmit}
  374. initialData={{...defaultValues, ...authenticator}}
  375. hideFooter
  376. >
  377. <JsonForm forms={[{title: 'Configuration', fields: fields ?? []}]} />
  378. </Form>
  379. )}
  380. </Fragment>
  381. );
  382. }
  383. }
  384. const CodeContainer = styled(PanelItem)`
  385. justify-content: center;
  386. `;
  387. const Actions = styled(PanelItem)`
  388. justify-content: flex-end;
  389. `;
  390. const StyledQRCode = styled(QRCodeCanvas)`
  391. background: white;
  392. padding: ${space(2)};
  393. `;
  394. export default withSentryRouter(AccountSecurityEnroll);