📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
refactored UserSettings
Blue Mouseea363ea90bc7
diff --git a/src/pages/UserSettings/UserSettings.container.jsx b/src/pages/UserSettings/UserSettings.container.jsxindex 20095eb4a..0bfe1063d 100644--- a/src/pages/UserSettings/UserSettings.container.jsx+++ b/src/pages/UserSettings/UserSettings.container.jsx@@ -1,36 +1,26 @@-/* eslint-disable no-param-reassign */-import React, { memo } from 'react'-import { useHistory } from 'react-router-dom'-import { useDispatch } from 'react-redux'-import { useTranslation } from 'react-i18next'-import dayjs from 'dayjs'-import utc from 'dayjs/plugin/utc'-import _isNull from 'lodash/isNull'+import { connect } from 'react-redux'-import {- CONFIRMATION_TIMEOUT, GDPR_REQUEST, GDPR_EXPORT_TIMEFRAME,-} from 'redux/constants'-import { withAuthentication, auth } from 'hoc/protected'-import { authActions } from 'redux/actions/auth'+import UIActions from 'redux/actions/ui'import { errorsActions } from 'redux/actions/errors'+import { authActions } from 'redux/actions/auth'import { alertsActions } from 'redux/actions/alerts'-import UIActions from 'redux/actions/ui'-import { getCookie, setCookie } from 'utils/cookie'import { trackCustom } from 'utils/analytics'-import {- confirmEmail, exportUserData, generateApiKey, deleteApiKey,-} from 'api'-import routes from 'routes'-import UserSettings from './UserSettings'-dayjs.extend(utc)+import UserSettings from './UserSettings'-const UserSettingsContainer = () => {- const { t, i18n: { language } } = useTranslation('common')- const dispatch = useDispatch()- const history = useHistory()+const mapStateToProps = (state) => {+ return {+ user: state.auth.user,+ dontRemember: state.auth.dontRemember,+ isPaidTierUsed: state.auth.isPaidTierUsed,+ }+}- const onDelete = () => {+const mapDispatchToProps = (dispatch) => ({+ onGDPRExportFailed: (message) => {+ dispatch(errorsActions.GDPRExportFailed(message))+ },+ onDelete: (t, onSuccess) => {dispatch(authActions.deleteAccountAsync((error) => dispatch(@@ -38,148 +28,61 @@ const UserSettingsContainer = () => {),() => {trackCustom('ACCOUNT_DELETED')- history.push(routes.main)+ onSuccess()},t,),)- }-- const onExport = async (exportedAt) => {- try {- if (getCookie(GDPR_REQUEST) || (!_isNull(exportedAt) && !dayjs().isAfter(dayjs.utc(exportedAt).add(GDPR_EXPORT_TIMEFRAME, 'day'), 'day'))) {- dispatch(errorsActions.GDPRExportFailed(t('profileSettings.tryAgainInXDays', { amount: GDPR_EXPORT_TIMEFRAME })))- return- }- await exportUserData()-- trackCustom('GDPR_EXPORT')- dispatch(alertsActions.accountUpdated(t('profileSettings.reportSent')))- setCookie(GDPR_REQUEST, true, 1209600) // setting cookie for 14 days- } catch (e) {- dispatch(errorsActions.updateProfileFailed(e))- }- }-- const updateUserData = (data) => {+ },+ updateUserData: (data) => {dispatch(authActions.updateUserData(data))- }-- const onDeleteProjectCache = () => {+ },+ onDeleteProjectCache: () => {dispatch(UIActions.deleteProjectCache())- }-- const login = (user) => {+ },+ login: (user) => {dispatch(authActions.loginSuccess(user))- }-- const onSubmit = (data) => {- delete data.repeat- // eslint-disable-next-line no-restricted-syntax- for (const key in data) {- if (data[key] === '') {- delete data[key]- }- }-- dispatch(- authActions.updateUserProfileAsync(- data,- () => dispatch(- alertsActions.accountUpdated(t('profileSettings.updated')),- ),- ),- )- }-- const onEmailConfirm = async (errorCallback) => {- if (getCookie(CONFIRMATION_TIMEOUT)) {- dispatch(errorsActions.updateProfileFailed(t('profileSettings.confTimeout')))- return- }-- try {- const res = await confirmEmail()-- if (res) {- setCookie(CONFIRMATION_TIMEOUT, true, 600)- dispatch(alertsActions.accountUpdated(t('profileSettings.confSent')))- } else {- errorCallback(t('profileSettings.noConfLeft'))- }- } catch (e) {- dispatch(errorsActions.updateProfileFailed(e))- }- }-- const userSharedUpdate = (message) => {+ },+ userSharedUpdate: (message) => {dispatch(alertsActions.userSharedUpdate(message))- }-- const sharedProjectError = (message) => {+ },+ sharedProjectError: (message) => {dispatch(errorsActions.sharedProjectFailed(message))- }-- const genericError = (message) => {+ },+ genericError: (message) => {dispatch(errorsActions.genericError(message))- }-- const removeProject = (projectId) => {+ },+ removeProject: (projectId) => {dispatch(UIActions.removeProject(projectId, true))- }-- const removeShareProject = (id) => {+ },+ removeShareProject: (id) => {dispatch(authActions.deleteShareProject(id))- }-- const setProjectsShareData = (data, id) => {+ },+ setProjectsShareData: (data, id) => {dispatch(UIActions.setProjectsShareData(data, id, true))- }-- const setUserShareData = (data, id) => {+ },+ setUserShareData: (data, id) => {dispatch(authActions.setUserShareData(data, id))- }-- const onApiKeyGenerate = async () => {- try {- const res = await generateApiKey()- dispatch(authActions.setApiKey(res.apiKey))- } catch (e) {- dispatch(errorsActions.updateProfileFailed(e))- }- }-- const onApiKeyDelete = async () => {- try {- await deleteApiKey()- dispatch(authActions.setApiKey(null))- } catch (e) {- dispatch(errorsActions.updateProfileFailed(e))- }- }-- return (- <UserSettings- t={t}- language={language}- onDelete={onDelete}- onExport={onExport}- removeProject={removeProject}- removeShareProject={removeShareProject}- setProjectsShareData={setProjectsShareData}- setUserShareData={setUserShareData}- onSubmit={onSubmit}- userSharedUpdate={userSharedUpdate}- sharedProjectError={sharedProjectError}- onEmailConfirm={onEmailConfirm}- onDeleteProjectCache={onDeleteProjectCache}- updateUserData={updateUserData}- login={login}- genericError={genericError}- onApiKeyDelete={onApiKeyDelete}- onApiKeyGenerate={onApiKeyGenerate}- />- )-}+ },+ updateProfileFailed: (message) => {+ dispatch(errorsActions.updateProfileFailed(message))+ },+ accountUpdated: (message) => {+ dispatch(alertsActions.accountUpdated(message))+ },+ updateUserProfileAsync: (data, successMessage) => {+ dispatch(+ authActions.updateUserProfileAsync(+ data,+ () => dispatch(+ alertsActions.accountUpdated(successMessage),+ ),+ ),+ )+ },+ setAPIKey: (apiKey) => {+ dispatch(authActions.setApiKey(apiKey))+ },+})-export default memo(withAuthentication(UserSettingsContainer, auth.authenticated))+export default connect(mapStateToProps, mapDispatchToProps)(UserSettings)diff --git a/src/pages/UserSettings/UserSettings.jsx b/src/pages/UserSettings/UserSettings.jsxindex b15fdd88c..a289c22f2 100644--- a/src/pages/UserSettings/UserSettings.jsx+++ b/src/pages/UserSettings/UserSettings.jsx@@ -1,24 +1,28 @@+/* eslint-disable no-param-reassign, react/forbid-prop-types */import React, {useState, useEffect, memo, useRef,} from 'react'-import { useSelector } from 'react-redux'-import cx from 'clsx'+import { useHistory } from 'react-router-dom'+import { useTranslation } from 'react-i18next'import _size from 'lodash/size'import _isEmpty from 'lodash/isEmpty'import _isNull from 'lodash/isNull'import _findIndex from 'lodash/findIndex'import _map from 'lodash/map'import _keys from 'lodash/keys'-import _isString from 'lodash/isString'import {EnvelopeIcon, ExclamationTriangleIcon, ArrowDownTrayIcon, CurrencyDollarIcon, ClipboardDocumentIcon,} from '@heroicons/react/24/outline'-import QRCode from 'react-qr-code'import PropTypes from 'prop-types'import dayjs from 'dayjs'+import utc from 'dayjs/plugin/utc'-import { reportFrequencies, DEFAULT_TIMEZONE, WEEKLY_REPORT_FREQUENCY } from 'redux/constants'+import {+ reportFrequencies, DEFAULT_TIMEZONE, WEEKLY_REPORT_FREQUENCY, CONFIRMATION_TIMEOUT,+ GDPR_REQUEST, GDPR_EXPORT_TIMEFRAME,+} from 'redux/constants'import Title from 'components/Title'+import { withAuthentication, auth } from 'hoc/protected'import Input from 'ui/Input'import Button from 'ui/Button'import Modal from 'ui/Modal'@@ -27,326 +31,26 @@ import Select from 'ui/Select'import PaidFeature from 'modals/PaidFeature'import TimezonePicker from 'ui/TimezonePicker'import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from 'utils/validator'-import { setAccessToken } from 'utils/accessToken'-+import routes from 'routes'+import { trackCustom } from 'utils/analytics'+import { getCookie, setCookie } from 'utils/cookie'import {- deleteShareProject, acceptShareProject, generate2FA, enable2FA, disable2FA,+ confirmEmail, exportUserData, generateApiKey, deleteApiKey,} from 'api'+import ProjectList from './components/ProjectList'+import TwoFA from './components/TwoFA'+import NoSharedProjects from './components/NoSharedProjects'-const ProjectList = ({- item, t, removeShareProject, removeProject, setProjectsShareData, setUserShareData,- language, userSharedUpdate, sharedProjectError,-}) => {- const [showDeleteModal, setShowDeleteModal] = useState(false)- const {- created, confirmed, id, role, project,- } = item-- const deleteProject = async (pid) => {- try {- await deleteShareProject(pid)- removeShareProject(pid)- removeProject(project.id)- userSharedUpdate(t('apiNotifications.quitProject'))- } catch (e) {- console.error(`[ERROR] Error while quitting project: ${e}`)- sharedProjectError(t('apiNotifications.quitProjectError'))- }- }-- const onAccept = async () => {- try {- await acceptShareProject(id)- setProjectsShareData({ confirmed: true }, project.id)- setUserShareData({ confirmed: true }, id)- userSharedUpdate(t('apiNotifications.acceptInvitation'))- } catch (e) {- console.error(`[ERROR] Error while accepting project invitation: ${e}`)- sharedProjectError(t('apiNotifications.acceptInvitationError'))- }- }-- return (- <tr className='dark:bg-gray-700'>- <td className='whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 dark:text-white sm:pl-6'>- {project.name}- </td>- <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>- {t(`project.settings.roles.${role}.name`)}- </td>- <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>- {language === 'en'- ? dayjs(created).locale(language).format('MMMM D, YYYY')- : dayjs(created).locale(language).format('D MMMM, YYYY')}- </td>- <td className='relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6'>- {confirmed ? (- <Button onClick={() => setShowDeleteModal(true)} danger small>- {t('common.quit')}- </Button>- ) : (- <>- <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>- {t('common.reject')}- </Button>- <Button onClick={() => onAccept()} primary small>- {t('common.accept')}- </Button>- </>- )}- <Modal- onClose={() => {- setShowDeleteModal(false)- }}- onSubmit={() => {- setShowDeleteModal(false)- deleteProject(id)- }}- submitText={t('common.yes')}- type='confirmed'- closeText={t('common.no')}- title={t('profileSettings.quitProjectTitle', { project: project.name })}- message={t('profileSettings.quitProject')}- isOpened={showDeleteModal}- />- </td>- </tr>- )-}--ProjectList.propTypes = {- item: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types- t: PropTypes.func.isRequired,- sharedProjectError: PropTypes.func.isRequired,- removeProject: PropTypes.func.isRequired,- removeShareProject: PropTypes.func.isRequired,- userSharedUpdate: PropTypes.func.isRequired,-}--const NoSharedProjects = ({ t }) => (- <div className='flex flex-col py-6 sm:px-6 lg:px-8'>- <div className='max-w-7xl w-full mx-auto text-gray-900 dark:text-gray-50'>- <h2 className='text-2xl mb-4 text-center leading-snug'>- {t('profileSettings.noSharedProjects')}- </h2>- </div>- </div>-)--const TwoFA = ({- t, user, dontRemember, updateUserData, login, genericError,-}) => {- const [twoFAConfigurating, setTwoFAConfigurating] = useState(false)- const [twoFADisabling, setTwoFADisabling] = useState(false)- const [twoFAConfigData, setTwoFAConfigData] = useState({}) // { secret, otpauthUrl }- const [isTwoFaLoading, setIsTwoFaLoading] = useState(false)- const [twoFACode, setTwoFACode] = useState('')- const [twoFACodeError, setTwoFACodeError] = useState(null)- const [twoFARecovery, setTwoFARecovery] = useState(null)- const { isTwoFactorAuthenticationEnabled } = user-- const handle2FAInput = (event) => {- const { target: { value } } = event- setTwoFACode(value)- setTwoFACodeError(null)- }-- const _generate2FA = async () => {- if (!isTwoFaLoading) {- setIsTwoFaLoading(true)-- try {- const result = await generate2FA()- setTwoFAConfigurating(true)- setTwoFAConfigData(result)- } catch (e) {- if (_isString(e)) {- genericError(e)- } else {- genericError(t('apiNotifications.generate2FAError'))- }- console.error(`[ERROR] Failed to generate 2FA: ${e}`)- setTwoFAConfigurating(false)- setTwoFAConfigData({})- }-- setIsTwoFaLoading(false)- }- }-- const _enable2FA = async () => {- if (!isTwoFaLoading) {- setIsTwoFaLoading(true)-- try {- const { twoFactorRecoveryCode, access_token: accessToken, user: updatedUser } = await enable2FA(twoFACode)- login(updatedUser)- setAccessToken(accessToken, dontRemember)- setTwoFARecovery(twoFactorRecoveryCode)- } catch (e) {- if (_isString(e)) {- genericError(e)- }- setTwoFACodeError(t('profileSettings.invalid2fa'))- }-- setTwoFACode('')- setIsTwoFaLoading(false)- }- }-- const _disable2FA = async () => {- if (!isTwoFaLoading) {- setIsTwoFaLoading(true)-- try {- await disable2FA(twoFACode)- updateUserData({ isTwoFactorAuthenticationEnabled: false })- } catch (e) {- if (_isString(e)) {- genericError(e)- }- setTwoFACodeError(t('profileSettings.invalid2fa'))- }-- setTwoFACode('')- setIsTwoFaLoading(false)- }- }-- const callFnOnKeyPress = (fn, key = 'Enter') => (e) => {- e.stopPropagation()- if (e.key === key) {- fn(e)- }- }-- const recoverySaved = () => {- setTwoFARecovery(null)- setTwoFAConfigurating(false)- }-- if (twoFARecovery) {- return (- <div className='max-w-prose'>- <p className='text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faRecoveryNote')}- </p>- <Input type='text' className='mt-4' value={twoFARecovery} />- <Button onClick={recoverySaved} primary large>- {t('profileSettings.2faRecoverySaved')}- </Button>- </div>- )- }-- if (isTwoFactorAuthenticationEnabled) {- if (twoFADisabling) {- return (- <>- <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faDisableHint')}- </p>- <div className='flex items-center mt-4'>- <Input- type='text'- label={t('profileSettings.enter2faToDisable')}- value={twoFACode}- placeholder={t('profileSettings.yourOneTimeCode')}- className='sm:col-span-3'- onChange={handle2FAInput}- onKeyDown={callFnOnKeyPress(_disable2FA)}- error={twoFACodeError}- disabled={isTwoFaLoading}- />- <Button- className={cx('ml-2', {- 'mt-4': _isNull(twoFACodeError),- 'mb-1': !_isNull(twoFACodeError),- })}- onClick={_disable2FA}- loading={isTwoFaLoading}- danger- large- >- {t('common.disable')}- </Button>- </div>- </>- )- }-- return (- <>- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faEnabled')}- </p>- <Button className='mt-4' onClick={() => setTwoFADisabling(true)} danger large>- {t('profileSettings.2faDisableBtn')}- </Button>- </>- )- }-- if (twoFAConfigurating) {- return (- <>- <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faDesc')}- </p>- <div className='mt-4 p-4 bg-white w-max'>- <QRCode value={twoFAConfigData.otpauthUrl} />- </div>- <p className='text-base whitespace-pre-line mt-2 text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faQRAlt', { key: twoFAConfigData.secret })}- </p>- <div className='flex items-center mt-4'>- <Input- type='text'- label={t('profileSettings.enter2faToEnable')}- value={twoFACode}- placeholder={t('profileSettings.yourOneTimeCode')}- className='sm:col-span-3'- onChange={handle2FAInput}- onKeyDown={callFnOnKeyPress(_enable2FA)}- error={twoFACodeError}- disabled={isTwoFaLoading}- />- <Button- className={cx('ml-2', {- 'mt-8 xs:mt-4': _isNull(twoFACodeError),- 'mb-1': !_isNull(twoFACodeError),- })}- onClick={_enable2FA}- loading={isTwoFaLoading}- primary- large- >- {t('common.enable')}- </Button>- </div>- </>- )- }-- return (- <>- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.2faEnable')}- </p>- <Button className='mt-4' onClick={_generate2FA} loading={isTwoFaLoading} primary large>- {t('profileSettings.2faEnableBtn')}- </Button>- </>- )-}+dayjs.extend(utc)const UserSettings = ({- onDelete, onExport, onSubmit, onEmailConfirm, onDeleteProjectCache, t,- removeProject, removeShareProject, setUserShareData, setProjectsShareData, language,- userSharedUpdate, sharedProjectError, updateUserData, login, genericError, onApiKeyGenerate, onApiKeyDelete,+ onDelete, onDeleteProjectCache, removeProject, removeShareProject, setUserShareData,+ setProjectsShareData, userSharedUpdate, sharedProjectError, updateUserData, login,+ genericError, onGDPRExportFailed, updateProfileFailed, updateUserProfileAsync,+ accountUpdated, setAPIKey, user, dontRemember, isPaidTierUsed,}) => {- const { user, dontRemember, isPaidTierUsed } = useSelector(state => state.auth)+ const history = useHistory()+ const { t, i18n: { language } } = useTranslation('common')const [form, setForm] = useState({email: user.email || '',@@ -390,6 +94,18 @@ const UserSettings = ({setValidated(valid)}+ const onSubmit = (data) => {+ delete data.repeat+ // eslint-disable-next-line no-restricted-syntax+ for (const key in data) {+ if (data[key] === '') {+ delete data[key]+ }+ }++ updateUserProfileAsync(data, t('profileSettings.updated'))+ }+useEffect(() => {validate()}, [form]) // eslint-disable-line@@ -481,6 +197,66 @@ const UserSettings = ({}}+ const _onDelete = () => {+ onDelete(t, () => {+ history.push(routes.main)+ })+ }++ const onExport = async (exportedAt) => {+ try {+ if (getCookie(GDPR_REQUEST) || (!_isNull(exportedAt) && !dayjs().isAfter(dayjs.utc(exportedAt).add(GDPR_EXPORT_TIMEFRAME, 'day'), 'day'))) {+ onGDPRExportFailed(t('profileSettings.tryAgainInXDays', { amount: GDPR_EXPORT_TIMEFRAME }))+ return+ }+ await exportUserData()++ trackCustom('GDPR_EXPORT')+ accountUpdated(t('profileSettings.reportSent'))+ setCookie(GDPR_REQUEST, true, 1209600) // setting cookie for 14 days+ } catch (e) {+ updateProfileFailed(e)+ }+ }++ const onEmailConfirm = async (errorCallback) => {+ if (getCookie(CONFIRMATION_TIMEOUT)) {+ updateProfileFailed(t('profileSettings.confTimeout'))+ return+ }++ try {+ const res = await confirmEmail()++ if (res) {+ setCookie(CONFIRMATION_TIMEOUT, true, 600)+ accountUpdated(t('profileSettings.confSent'))+ } else {+ errorCallback(t('profileSettings.noConfLeft'))+ }+ } catch (e) {+ updateProfileFailed(e)+ }+ }++ const onApiKeyGenerate = async () => {+ try {+ const res = await generateApiKey()+ setAPIKey(res.apiKey)+ } catch (e) {+ updateProfileFailed(e)+ }+ }++ const onApiKeyDelete = async () => {+ try {+ await deleteApiKey()+ setAPIKey(null)+ } catch (e) {+ updateProfileFailed(e)+ }+ }+return (<Title title={t('titles.profileSettings')}><div className='min-h-min-footer bg-gray-50 dark:bg-gray-800 flex flex-col py-6 px-4 sm:px-6 lg:px-8'>@@ -736,7 +512,7 @@ const UserSettings = ({onClose={() => setShowModal(false)}onSubmit={() => {setShowModal(false)- onDelete()+ _onDelete()}}submitText={t('profileSettings.aDelete')}closeText={t('common.close')}@@ -776,23 +552,25 @@ const UserSettings = ({}UserSettings.propTypes = {- onEmailConfirm: PropTypes.func.isRequired,- onExport: PropTypes.func.isRequired,onDelete: PropTypes.func.isRequired,- t: PropTypes.func.isRequired,+ onGDPRExportFailed: PropTypes.func.isRequired,onDeleteProjectCache: PropTypes.func.isRequired,removeProject: PropTypes.func.isRequired,removeShareProject: PropTypes.func.isRequired,setUserShareData: PropTypes.func.isRequired,setProjectsShareData: PropTypes.func.isRequired,- language: PropTypes.string.isRequired,userSharedUpdate: PropTypes.func.isRequired,sharedProjectError: PropTypes.func.isRequired,updateUserData: PropTypes.func.isRequired,login: PropTypes.func.isRequired,genericError: PropTypes.func.isRequired,- onApiKeyDelete: PropTypes.func.isRequired,- onApiKeyGenerate: PropTypes.func.isRequired,+ updateProfileFailed: PropTypes.func.isRequired,+ updateUserProfileAsync: PropTypes.func.isRequired,+ accountUpdated: PropTypes.func.isRequired,+ setAPIKey: PropTypes.func.isRequired,+ user: PropTypes.object.isRequired,+ dontRemember: PropTypes.bool.isRequired,+ isPaidTierUsed: PropTypes.bool.isRequired,}-export default memo(UserSettings)+export default memo(withAuthentication(UserSettings, auth.authenticated))diff --git a/src/pages/UserSettings/components/NoSharedProjects.jsx b/src/pages/UserSettings/components/NoSharedProjects.jsxnew file mode 100644index 000000000..cf72e6711--- /dev/null+++ b/src/pages/UserSettings/components/NoSharedProjects.jsx@@ -0,0 +1,13 @@+import React from 'react'++const NoSharedProjects = ({ t }) => (+ <div className='flex flex-col py-6 sm:px-6 lg:px-8'>+ <div className='max-w-7xl w-full mx-auto text-gray-900 dark:text-gray-50'>+ <h2 className='text-2xl mb-4 text-center leading-snug'>+ {t('profileSettings.noSharedProjects')}+ </h2>+ </div>+ </div>+)++export default NoSharedProjectsdiff --git a/src/pages/UserSettings/components/ProjectList.jsx b/src/pages/UserSettings/components/ProjectList.jsxnew file mode 100644index 000000000..5a1bb6ff5--- /dev/null+++ b/src/pages/UserSettings/components/ProjectList.jsx@@ -0,0 +1,103 @@+import React, { memo, useState } from 'react'+import dayjs from 'dayjs'+import PropTypes from 'prop-types'+import { useTranslation } from 'react-i18next'++import Button from 'ui/Button'+import Modal from 'ui/Modal'+import {+ deleteShareProject, acceptShareProject,+} from 'api'++const ProjectList = ({+ item, removeShareProject, removeProject, setProjectsShareData, setUserShareData,+ userSharedUpdate, sharedProjectError,+}) => {+ const { t, i18n: { language } } = useTranslation('common')++ const [showDeleteModal, setShowDeleteModal] = useState(false)+ const {+ created, confirmed, id, role, project,+ } = item++ const deleteProject = async (pid) => {+ try {+ await deleteShareProject(pid)+ removeShareProject(pid)+ removeProject(project.id)+ userSharedUpdate(t('apiNotifications.quitProject'))+ } catch (e) {+ console.error(`[ERROR] Error while quitting project: ${e}`)+ sharedProjectError(t('apiNotifications.quitProjectError'))+ }+ }++ const onAccept = async () => {+ try {+ await acceptShareProject(id)+ setProjectsShareData({ confirmed: true }, project.id)+ setUserShareData({ confirmed: true }, id)+ userSharedUpdate(t('apiNotifications.acceptInvitation'))+ } catch (e) {+ console.error(`[ERROR] Error while accepting project invitation: ${e}`)+ sharedProjectError(t('apiNotifications.acceptInvitationError'))+ }+ }++ return (+ <tr className='dark:bg-gray-700'>+ <td className='whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 dark:text-white sm:pl-6'>+ {project.name}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>+ {t(`project.settings.roles.${role}.name`)}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-white'>+ {language === 'en'+ ? dayjs(created).locale(language).format('MMMM D, YYYY')+ : dayjs(created).locale(language).format('D MMMM, YYYY')}+ </td>+ <td className='relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6'>+ {confirmed ? (+ <Button onClick={() => setShowDeleteModal(true)} danger small>+ {t('common.quit')}+ </Button>+ ) : (+ <>+ <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>+ {t('common.reject')}+ </Button>+ <Button onClick={() => onAccept()} primary small>+ {t('common.accept')}+ </Button>+ </>+ )}+ <Modal+ onClose={() => {+ setShowDeleteModal(false)+ }}+ onSubmit={() => {+ setShowDeleteModal(false)+ deleteProject(id)+ }}+ submitText={t('common.yes')}+ type='confirmed'+ closeText={t('common.no')}+ title={t('profileSettings.quitProjectTitle', { project: project.name })}+ message={t('profileSettings.quitProject')}+ isOpened={showDeleteModal}+ />+ </td>+ </tr>+ )+}++ProjectList.propTypes = {+ item: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types+ sharedProjectError: PropTypes.func.isRequired,+ removeProject: PropTypes.func.isRequired,+ removeShareProject: PropTypes.func.isRequired,+ userSharedUpdate: PropTypes.func.isRequired,+}++export default memo(ProjectList)diff --git a/src/pages/UserSettings/components/TwoFA.jsx b/src/pages/UserSettings/components/TwoFA.jsxnew file mode 100644index 000000000..5d82a1836--- /dev/null+++ b/src/pages/UserSettings/components/TwoFA.jsx@@ -0,0 +1,224 @@+import React, { useState, memo } from 'react'+import QRCode from 'react-qr-code'+import { useTranslation } from 'react-i18next'+import cx from 'clsx'+import _isNull from 'lodash/isNull'+import _isString from 'lodash/isString'++import Input from 'ui/Input'+import Button from 'ui/Button'+import {+ generate2FA, enable2FA, disable2FA,+} from 'api'+import { setAccessToken } from 'utils/accessToken'++const TwoFA = ({+ user, dontRemember, updateUserData, login, genericError,+}) => {+ const { t } = useTranslation('common')+ const [twoFAConfigurating, setTwoFAConfigurating] = useState(false)+ const [twoFADisabling, setTwoFADisabling] = useState(false)+ const [twoFAConfigData, setTwoFAConfigData] = useState({}) // { secret, otpauthUrl }+ const [isTwoFaLoading, setIsTwoFaLoading] = useState(false)+ const [twoFACode, setTwoFACode] = useState('')+ const [twoFACodeError, setTwoFACodeError] = useState(null)+ const [twoFARecovery, setTwoFARecovery] = useState(null)+ const { isTwoFactorAuthenticationEnabled } = user++ const handle2FAInput = (event) => {+ const { target: { value } } = event+ setTwoFACode(value)+ setTwoFACodeError(null)+ }++ const _generate2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ const result = await generate2FA()+ setTwoFAConfigurating(true)+ setTwoFAConfigData(result)+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ } else {+ genericError(t('apiNotifications.generate2FAError'))+ }+ console.error(`[ERROR] Failed to generate 2FA: ${e}`)+ setTwoFAConfigurating(false)+ setTwoFAConfigData({})+ }++ setIsTwoFaLoading(false)+ }+ }++ const _enable2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ const { twoFactorRecoveryCode, access_token: accessToken, user: updatedUser } = await enable2FA(twoFACode)+ login(updatedUser)+ setAccessToken(accessToken, dontRemember)+ setTwoFARecovery(twoFactorRecoveryCode)+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ }+ setTwoFACodeError(t('profileSettings.invalid2fa'))+ }++ setTwoFACode('')+ setIsTwoFaLoading(false)+ }+ }++ const _disable2FA = async () => {+ if (!isTwoFaLoading) {+ setIsTwoFaLoading(true)++ try {+ await disable2FA(twoFACode)+ updateUserData({ isTwoFactorAuthenticationEnabled: false })+ } catch (e) {+ if (_isString(e)) {+ genericError(e)+ }+ setTwoFACodeError(t('profileSettings.invalid2fa'))+ }++ setTwoFACode('')+ setIsTwoFaLoading(false)+ }+ }++ const callFnOnKeyPress = (fn, key = 'Enter') => (e) => {+ e.stopPropagation()+ if (e.key === key) {+ fn(e)+ }+ }++ const recoverySaved = () => {+ setTwoFARecovery(null)+ setTwoFAConfigurating(false)+ }++ if (twoFARecovery) {+ return (+ <div className='max-w-prose'>+ <p className='text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faRecoveryNote')}+ </p>+ <Input type='text' className='mt-4' value={twoFARecovery} />+ <Button onClick={recoverySaved} primary large>+ {t('profileSettings.2faRecoverySaved')}+ </Button>+ </div>+ )+ }++ if (isTwoFactorAuthenticationEnabled) {+ if (twoFADisabling) {+ return (+ <>+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faDisableHint')}+ </p>+ <div className='flex items-center mt-4'>+ <Input+ type='text'+ label={t('profileSettings.enter2faToDisable')}+ value={twoFACode}+ placeholder={t('profileSettings.yourOneTimeCode')}+ className='sm:col-span-3'+ onChange={handle2FAInput}+ onKeyDown={callFnOnKeyPress(_disable2FA)}+ error={twoFACodeError}+ disabled={isTwoFaLoading}+ />+ <Button+ className={cx('ml-2', {+ 'mt-4': _isNull(twoFACodeError),+ 'mb-1': !_isNull(twoFACodeError),+ })}+ onClick={_disable2FA}+ loading={isTwoFaLoading}+ danger+ large+ >+ {t('common.disable')}+ </Button>+ </div>+ </>+ )+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faEnabled')}+ </p>+ <Button className='mt-4' onClick={() => setTwoFADisabling(true)} danger large>+ {t('profileSettings.2faDisableBtn')}+ </Button>+ </>+ )+ }++ if (twoFAConfigurating) {+ return (+ <>+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faDesc')}+ </p>+ <div className='mt-4 p-4 bg-white w-max'>+ <QRCode value={twoFAConfigData.otpauthUrl} />+ </div>+ <p className='text-base whitespace-pre-line mt-2 text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faQRAlt', { key: twoFAConfigData.secret })}+ </p>+ <div className='flex items-center mt-4'>+ <Input+ type='text'+ label={t('profileSettings.enter2faToEnable')}+ value={twoFACode}+ placeholder={t('profileSettings.yourOneTimeCode')}+ className='sm:col-span-3'+ onChange={handle2FAInput}+ onKeyDown={callFnOnKeyPress(_enable2FA)}+ error={twoFACodeError}+ disabled={isTwoFaLoading}+ />+ <Button+ className={cx('ml-2', {+ 'mt-8 xs:mt-4': _isNull(twoFACodeError),+ 'mb-1': !_isNull(twoFACodeError),+ })}+ onClick={_enable2FA}+ loading={isTwoFaLoading}+ primary+ large+ >+ {t('common.enable')}+ </Button>+ </div>+ </>+ )+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2faEnable')}+ </p>+ <Button className='mt-4' onClick={_generate2FA} loading={isTwoFaLoading} primary large>+ {t('profileSettings.2faEnableBtn')}+ </Button>+ </>+ )+}++export default memo(TwoFA)