Skip to content

📈 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!

Implemented 2FA setting

Blue Mouseda43b425047e
diff --git a/package.json b/package.json
index 2c19f6b3d..04f92c962 100644
--- a/package.json
+++ b/package.json
@@ -31,6 +31,7 @@
"react-flatpickr": "^3.10.12",
"react-helmet-async": "^1.3.0",
"react-i18next": "^11.16.9",
+ "react-qr-code": "^2.0.7",
"react-redux": "^8.0.2",
"react-router-dom": "^5.3.1",
"react-router-hash-link": "^2.4.3",
diff --git a/public/locales/en.json b/public/locales/en.json
index f3b812b71..819c7077b 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -17,7 +17,8 @@
"quitProject": "You have quit the project",
"acceptInvitationError": "Error occurred while accepting the project invitation",
"acceptInvitation": "The project invitation has been accepted",
- "subscriptionUpdated": "Your subscription has been updated"
+ "subscriptionUpdated": "Your subscription has been updated",
+ "generate2FAError": "Error occurred while generating 2FA code"
},
"common": {
"features": "Features",
@@ -50,7 +51,9 @@
"accept": "Accept",
"reject": "Reject",
"delete": "Delete",
- "quit": "Quit"
+ "quit": "Quit",
+ "enable": "Enable",
+ "disable": "Disable"
},
"main": {
"ukrSupport": "Support the Ukrainian army to fight Russian invasion.",
@@ -223,7 +226,21 @@
"role": "Role",
"joinedOn": "Joined on"
},
- "noSharedProjects": "Nobody is sharing a project with you yet."
+ "noSharedProjects": "Nobody is sharing a project with you yet.",
+ "2fa": "Two-factor authentication (2FA)",
+ "2faEnable": "Enable 2FA to make your account more secure.",
+ "2faEnableBtn": "Enable 2FA",
+ "2faDisableBtn": "Disable 2FA",
+ "2faDesc": "An authenticator app that supports time-based, one-time passwords (TOTP) such as andOTP or Google Authenticator can scan the QR code below to enable 2FA on your Swetrix account:",
+ "2faQRAlt": "Can't scan the QR code?\nUse this secret key instead: {{key}}",
+ "enter2faToEnable": "Enter your one-time code to enable 2FA",
+ "enter2faToDisable": "Enter your one-time code or a recovery code",
+ "yourOneTimeCode": "Your one-time code",
+ "invalid2fa": "Invalid 2FA code, please try again",
+ "2faRecoveryNote": "Important: If you cannot use your authenticator app, because you've deleted the app or lost your device, you'll need a way to access your account and disable 2FA.\n\nYou can use this recovery code to disable 2FA. Write it down and store it in a safe, secure place.",
+ "2faRecoverySaved": "I have saved this recovery code",
+ "2faEnabled": "Two-factor authenticated is enabled on your account.",
+ "2faDisableHint": "To disable two-factor authentication, please enter your 6-digit code or one of your recovery codes below."
},
"dashboard": {
"newProject": "New project",
diff --git a/src/api/index.js b/src/api/index.js
index 883baad07..5b14cd07b 100644
--- a/src/api/index.js
+++ b/src/api/index.js
@@ -325,3 +325,36 @@ export const changeShareRole = (id, data) =>
? error.response.data
: error.response.data.message
})
+
+export const generate2FA = () =>
+ api
+ .post('2fa/generate')
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
+export const enable2FA = (twoFactorAuthenticationCode) =>
+ api
+ .post('2fa/enable', { twoFactorAuthenticationCode })
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
+export const disable2FA = (twoFactorAuthenticationCode) =>
+ api
+ .post('2fa/disable', { twoFactorAuthenticationCode })
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
diff --git a/src/pages/UserSettings/UserSettings.container.jsx b/src/pages/UserSettings/UserSettings.container.jsx
index 50430c271..3327fc417 100644
--- a/src/pages/UserSettings/UserSettings.container.jsx
+++ b/src/pages/UserSettings/UserSettings.container.jsx
@@ -59,10 +59,18 @@ const UserSettingsContainer = () => {
}
}
+ const updateUserData = (data) => {
+ dispatch(authActions.updateUserData(data))
+ }
+
const onDeleteProjectCache = () => {
dispatch(UIActions.deleteProjectCache())
}
+ const login = (user) => {
+ dispatch(authActions.loginSuccess(user))
+ }
+
const onSubmit = (data) => {
delete data.repeat
// eslint-disable-next-line no-restricted-syntax
@@ -110,6 +118,10 @@ const UserSettingsContainer = () => {
dispatch(errorsActions.sharedProjectFailed(message))
}
+ const genericError = (message) => {
+ dispatch(errorsActions.genericError(message))
+ }
+
const removeProject = (projectId) => {
dispatch(UIActions.removeProject(projectId))
}
@@ -141,6 +153,9 @@ const UserSettingsContainer = () => {
sharedProjectError={sharedProjectError}
onEmailConfirm={onEmailConfirm}
onDeleteProjectCache={onDeleteProjectCache}
+ updateUserData={updateUserData}
+ login={login}
+ genericError={genericError}
/>
)
}
diff --git a/src/pages/UserSettings/UserSettings.jsx b/src/pages/UserSettings/UserSettings.jsx
index 669c95366..9f52e852a 100644
--- a/src/pages/UserSettings/UserSettings.jsx
+++ b/src/pages/UserSettings/UserSettings.jsx
@@ -2,12 +2,15 @@ import React, {
useState, useEffect, memo,
} from 'react'
import { useSelector } from 'react-redux'
+import cx from 'clsx'
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 { MailIcon } from '@heroicons/react/outline'
+import QRCode from 'react-qr-code'
import PropTypes from 'prop-types'
import dayjs from 'dayjs'
@@ -22,8 +25,11 @@ import TimezonePicker from 'ui/TimezonePicker'
import {
isValidEmail, isValidPassword, MIN_PASSWORD_CHARS,
} from 'utils/validator'
+import { setAccessToken } from 'utils/accessToken'
-import { deleteShareProject, acceptShareProject } from 'api'
+import {
+ deleteShareProject, acceptShareProject, generate2FA, enable2FA, disable2FA,
+} from 'api'
const ProjectList = ({
item, t, removeShareProject, removeProject, setProjectsShareData, setUserShareData,
@@ -125,12 +131,206 @@ const NoSharedProjects = ({ t }) => (
</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 () => {
+ setIsTwoFaLoading(true)
+
+ try {
+ const result = await generate2FA()
+ setTwoFAConfigurating(true)
+ setTwoFAConfigData(result)
+ } catch (e) {
+ console.error(`[ERROR] Failed to generate 2FA: ${e}`)
+ genericError(t('apiNotifications.generate2FAError'))
+ setTwoFAConfigurating(false)
+ setTwoFAConfigData({})
+ }
+
+ setIsTwoFaLoading(false)
+ }
+
+ const _enable2FA = async () => {
+ setIsTwoFaLoading(true)
+
+ try {
+ const { twoFactorRecoveryCode, accessToken, user: updatedUser } = await enable2FA(twoFACode)
+ login(updatedUser)
+ setAccessToken(accessToken, dontRemember)
+ setTwoFARecovery(twoFactorRecoveryCode)
+ } catch {
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
+ }
+
+ setTwoFACode('')
+ setIsTwoFaLoading(false)
+ }
+
+ const _disable2FA = async () => {
+ setIsTwoFaLoading(true)
+
+ try {
+ await disable2FA(twoFACode)
+ updateUserData({ isTwoFactorAuthenticationEnabled: false })
+ } catch {
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
+ }
+
+ setTwoFACode('')
+ setIsTwoFaLoading(false)
+ }
+
+ const recoverySaved = () => {
+ setTwoFARecovery(null)
+ }
+
+ 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}
+ 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}
+ error={twoFACodeError}
+ />
+ <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}
+ error={twoFACodeError}
+ />
+ <Button
+ className={cx('ml-2', {
+ '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>
+ </>
+ )
+}
+
const UserSettings = ({
onDelete, onExport, onSubmit, onEmailConfirm, onDeleteProjectCache, t,
removeProject, removeShareProject, setUserShareData, setProjectsShareData, language,
- userSharedUpdate, sharedProjectError,
+ userSharedUpdate, sharedProjectError, updateUserData, login, genericError,
}) => {
- const { user } = useSelector(state => state.auth)
+ const { user, dontRemember } = useSelector(state => state.auth)
const [form, setForm] = useState({
email: user.email || '',
@@ -275,11 +475,8 @@ const UserSettings = ({
{t('profileSettings.update')}
</Button>
<hr className='mt-5' />
- <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.timezone')}
- <div className='ml-5'>
- <Beta />
- </div>
</h3>
<div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>
<div>
@@ -310,6 +507,14 @@ const UserSettings = ({
<Button className='mt-4' onClick={handleReportSave} primary large>
{t('common.save')}
</Button>
+ <hr className='mt-5' />
+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2fa')}
+ <div className='ml-5'>
+ <Beta />
+ </div>
+ </h3>
+ <TwoFA t={t} user={user} dontRemember={dontRemember} updateUserData={updateUserData} login={login} genericError={genericError} />
<hr className='mt-5' />
<h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
@@ -439,6 +644,9 @@ UserSettings.propTypes = {
language: PropTypes.string.isRequired,
userSharedUpdate: PropTypes.func.isRequired,
sharedProjectError: PropTypes.func.isRequired,
+ updateUserData: PropTypes.func.isRequired,
+ login: PropTypes.func.isRequired,
+ genericError: PropTypes.func.isRequired,
}
export default memo(UserSettings)
diff --git a/src/redux/actions/auth/index.js b/src/redux/actions/auth/index.js
index 8543b39ee..b04b0c317 100644
--- a/src/redux/actions/auth/index.js
+++ b/src/redux/actions/auth/index.js
@@ -54,6 +54,20 @@ export const authActions = {
}
},
+ setDontRemember(dontRemember) {
+ return {
+ type: types.SET_DONT_REMEMBER,
+ payload: { dontRemember },
+ }
+ },
+
+ updateUserData(data) {
+ return {
+ type: types.UPDATE_USER_DATA,
+ payload: { data },
+ }
+ },
+
deleteAccountSuccess() {
removeAccessToken()
removeItem('user_info')
diff --git a/src/redux/actions/auth/types.js b/src/redux/actions/auth/types.js
index e5bf24879..12daf9529 100644
--- a/src/redux/actions/auth/types.js
+++ b/src/redux/actions/auth/types.js
@@ -11,6 +11,8 @@ export const types = {
DELETE_ACCOUNT_SUCCESS: 'DELETE_ACCOUNT_SUCCESS',
DELETE_SHARE_PROJECT: 'DELETE_SHARE_PROJECT',
SET_USER_SHARE_DATA: 'SET_USER_SHARE_DATA',
+ SET_DONT_REMEMBER: 'SET_DONT_REMEMBER',
+ UPDATE_USER_DATA: 'UPDATE_USER_DATA',
// Asynchronous
LOGIN_ASYNC: 'LOGIN_ASYNC',
diff --git a/src/redux/reducers/auth.js b/src/redux/reducers/auth.js
index ae47d2bb1..3c6e565ce 100644
--- a/src/redux/reducers/auth.js
+++ b/src/redux/reducers/auth.js
@@ -7,6 +7,7 @@ const initialState = {
authenticated: false,
loading: true,
user: {},
+ dontRemember: false,
}
// eslint-disable-next-line default-param-last
@@ -38,6 +39,16 @@ const authReducer = (state = initialState, { type, payload }) => {
return { ...state, user: { ...state.user, sharedProjects: _filter(state.user.sharedProjects, (item) => item.id !== id) } }
}
+ case types.SET_DONT_REMEMBER: {
+ const { dontRemember } = payload
+ return { ...state, dontRemember }
+ }
+
+ case types.UPDATE_USER_DATA: {
+ const { data } = payload
+ return { ...state, user: { ...state.user, ...data } }
+ }
+
case types.SET_USER_SHARE_DATA: {
// eslint-disable-next-line no-case-declarations
const { data, id } = payload
diff --git a/src/redux/sagas/auth/workers/signin.js b/src/redux/sagas/auth/workers/signin.js
index 9e5644c6e..8d4fcc348 100644
--- a/src/redux/sagas/auth/workers/signin.js
+++ b/src/redux/sagas/auth/workers/signin.js
@@ -14,6 +14,7 @@ export default function* singinWorker({ payload: { credentials, callback } }) {
yield put(authActions.loginSuccess(response.user))
yield call(setAccessToken, response.access_token, dontRemember)
+ yield put(authActions.setDontRemember(dontRemember))
yield put(UIActions.loadProjects())
callback(true)
} catch (error) {
diff --git a/src/redux/sagas/auth/workers/signup.js b/src/redux/sagas/auth/workers/signup.js
index 2732fe905..42408d4cb 100644
--- a/src/redux/sagas/auth/workers/signup.js
+++ b/src/redux/sagas/auth/workers/signup.js
@@ -14,6 +14,7 @@ export default function* signupWorder({ payload: { data: rawData, callback, t }
yield put(authActions.signupSuccess(response.user))
yield call(setAccessToken, response.access_token, dontRemember)
+ yield put(authActions.setDontRemember(dontRemember))
yield put(UIActions.loadProjects())
callback(true)
} catch (error) {