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!

some updates

Blue Mouse99661c92c96f
diff --git a/public/locales/en.json b/public/locales/en.json
index 819c7077b..fff2fb3ce 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -135,7 +135,11 @@
"signin": {
"title": "Sign in to your account",
"forgot": "Forgot password?",
- "button": "Sign in"
+ "button": "Sign in",
+ "2fa": "Two-factor authentication",
+ "2faDesc": "Open the two-factor authentication app on your device to view your authentication code and verify your identity.\nYou can also use your backup code.",
+ "2faUnavailable": "Don't have access to 2FA?\n<ctl>Contact support</ctl>.",
+ "6digitCode": "6-digit authentication code"
},
"signup": {
"button": "Sign up",
diff --git a/src/App.js b/src/App.js
index b1d5be71c..e1abc1334 100644
--- a/src/App.js
+++ b/src/App.js
@@ -128,7 +128,7 @@ const App = () => {
}
}
})()
- }, [accessToken, authenticated]) // eslint-disable-line
+ }, [authenticated]) // eslint-disable-line
useEffect(() => {
if (error) {
diff --git a/src/api/index.js b/src/api/index.js
index 5b14cd07b..ad9584e41 100644
--- a/src/api/index.js
+++ b/src/api/index.js
@@ -358,3 +358,14 @@ export const disable2FA = (twoFactorAuthenticationCode) =>
? error.response.data
: error.response.data.message
})
+
+export const submit2FA = (twoFactorAuthenticationCode) =>
+ api
+ .post('2fa/authenticate', { 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/Auth/Signin/Signin.container.jsx b/src/pages/Auth/Signin/Signin.container.jsx
index 309c3356e..d03491ff2 100644
--- a/src/pages/Auth/Signin/Signin.container.jsx
+++ b/src/pages/Auth/Signin/Signin.container.jsx
@@ -1,11 +1,21 @@
import { connect } from 'react-redux'
+
import { authActions } from 'redux/actions/auth'
+import { errorsActions } from 'redux/actions/errors'
+import UIActions from 'redux/actions/ui'
import Signin from './Signin'
const mapDispatchToProps = (dispatch) => ({
login: (data, callback) => {
dispatch(authActions.loginAsync(data, callback))
},
+ loginSuccess: (user) => {
+ dispatch(authActions.loginSuccess(user))
+ dispatch(UIActions.loadProjects())
+ },
+ loginFailed: (error) => {
+ dispatch(errorsActions.loginFailed(error))
+ },
})
export default connect(null, mapDispatchToProps)(Signin)
diff --git a/src/pages/Auth/Signin/Signin.jsx b/src/pages/Auth/Signin/Signin.jsx
index d3111fee0..1d5b448df 100644
--- a/src/pages/Auth/Signin/Signin.jsx
+++ b/src/pages/Auth/Signin/Signin.jsx
@@ -1,9 +1,10 @@
import React, { useState, useEffect, memo } from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
-import { useTranslation } from 'react-i18next'
+import { useTranslation, Trans } from 'react-i18next'
import _keys from 'lodash/keys'
import _isEmpty from 'lodash/isEmpty'
+import _isString from 'lodash/isString'
import Title from 'components/Title'
import { withAuthentication, auth } from 'hoc/protected'
@@ -15,8 +16,10 @@ import {
isValidEmail, isValidPassword, MIN_PASSWORD_CHARS,
} from 'utils/validator'
import { isSelfhosted } from 'redux/constants'
+import { submit2FA } from 'api'
+import { setAccessToken } from 'utils/accessToken'
-const Signin = ({ login }) => {
+const Signin = ({ login, loginSuccess, loginFailed }) => {
const { t } = useTranslation('common')
const [form, setForm] = useState({
email: '',
@@ -27,6 +30,9 @@ const Signin = ({ login }) => {
const [errors, setErrors] = useState({})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [isLoading, setIsLoading] = useState(false)
+ const [isTwoFARequired, setIsTwoFARequired] = useState(false)
+ const [twoFACode, setTwoFACode] = useState('')
+ const [twoFACodeError, setTwoFACodeError] = useState(null)
const validate = () => {
const allErrors = {}
@@ -49,17 +55,48 @@ const Signin = ({ login }) => {
validate()
}, [form]) // eslint-disable-line
+ const handle2FAInput = event => {
+ const { target: { value } } = event
+ setTwoFACode(value)
+ setTwoFACodeError(null)
+ }
+
const onSubmit = data => {
if (!isLoading) {
setIsLoading(true)
- login(data, (result) => {
+ login(data, (result, twoFARequired) => {
if (!result) {
setIsLoading(false)
+ setIsTwoFARequired(twoFARequired)
}
})
}
}
+ const _submit2FA = async (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ if (!isLoading) {
+ setIsLoading(true)
+
+ try {
+ const { access_token: accessToken, user } = await submit2FA(twoFACode)
+ setAccessToken(accessToken, form.dontRemember)
+ loginSuccess(user)
+ } catch (err) {
+ if (_isString(err)) {
+ loginFailed(err)
+ }
+ console.error(`[ERROR] Failed to authenticate with 2FA: ${err}`)
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
+ }
+
+ setTwoFACode('')
+ setIsLoading(false)
+ }
+ }
+
const handleInput = ({ target }) => {
const value = target.type === 'checkbox' ? target.checked : target.value
@@ -79,6 +116,49 @@ const Signin = ({ login }) => {
}
}
+ if (isTwoFARequired) {
+ return (
+ <Title title={t('titles.signin')}>
+ <div className='min-h-page bg-gray-50 dark:bg-gray-800 flex flex-col py-6 px-4 sm:px-6 lg:px-8'>
+ <form className='max-w-prose mx-auto' onSubmit={_submit2FA}>
+ <h2 className='mt-2 text-3xl font-extrabold text-gray-900 dark:text-gray-50'>
+ {t('auth.signin.2fa')}
+ </h2>
+ <p className='mt-4 text-base whitespace-pre-line text-gray-900 dark:text-gray-50'>
+ {t('auth.signin.2faDesc')}
+ </p>
+ <Input
+ type='text'
+ label={t('profileSettings.enter2faToDisable')}
+ value={twoFACode}
+ placeholder={t('auth.signin.6digitCode')}
+ className='mt-4'
+ onChange={handle2FAInput}
+ disabled={isLoading}
+ error={twoFACodeError}
+ />
+ <div className='flex justify-between mt-3'>
+ <div className='whitespace-pre-line text-sm text-gray-600 dark:text-gray-50'>
+ {!isSelfhosted && (
+ <Trans
+ t={t}
+ i18nKey='auth.signin.2faUnavailable'
+ components={{
+ ctl: <Link to={routes.contact} className='underline hover:text-gray-900 dark:hover:text-gray-300' />,
+ }}
+ />
+ )}
+ </div>
+ <Button type='submit' loading={isLoading} primary large>
+ {t('common.continue')}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </Title>
+ )
+ }
+
return (
<Title title={t('titles.signin')}>
<div className='min-h-page bg-gray-50 dark:bg-gray-800 flex flex-col py-6 px-4 sm:px-6 lg:px-8'>
@@ -143,6 +223,8 @@ const Signin = ({ login }) => {
Signin.propTypes = {
login: PropTypes.func.isRequired,
+ loginSuccess: PropTypes.func.isRequired,
+ loginFailed: PropTypes.func.isRequired,
}
export default memo(withAuthentication(Signin, auth.notAuthenticated))
diff --git a/src/pages/UserSettings/UserSettings.jsx b/src/pages/UserSettings/UserSettings.jsx
index 9f52e852a..0df1cf314 100644
--- a/src/pages/UserSettings/UserSettings.jsx
+++ b/src/pages/UserSettings/UserSettings.jsx
@@ -9,6 +9,7 @@ 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 { MailIcon } from '@heroicons/react/outline'
import QRCode from 'react-qr-code'
import PropTypes from 'prop-types'
@@ -150,54 +151,79 @@ const TwoFA = ({
}
const _generate2FA = async () => {
- setIsTwoFaLoading(true)
+ 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({})
+ }
- 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)
}
-
- setIsTwoFaLoading(false)
}
const _enable2FA = async () => {
- setIsTwoFaLoading(true)
+ 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'))
+ }
- try {
- const { twoFactorRecoveryCode, accessToken, user: updatedUser } = await enable2FA(twoFACode)
- login(updatedUser)
- setAccessToken(accessToken, dontRemember)
- setTwoFARecovery(twoFactorRecoveryCode)
- } catch {
- setTwoFACodeError(t('profileSettings.invalid2fa'))
+ setTwoFACode('')
+ setIsTwoFaLoading(false)
}
-
- setTwoFACode('')
- setIsTwoFaLoading(false)
}
const _disable2FA = async () => {
- setIsTwoFaLoading(true)
+ if (!isTwoFaLoading) {
+ setIsTwoFaLoading(true)
+
+ try {
+ await disable2FA(twoFACode)
+ updateUserData({ isTwoFactorAuthenticationEnabled: false })
+ } catch (e) {
+ if (_isString(e)) {
+ genericError(e)
+ }
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
+ }
- try {
- await disable2FA(twoFACode)
- updateUserData({ isTwoFactorAuthenticationEnabled: false })
- } catch {
- setTwoFACodeError(t('profileSettings.invalid2fa'))
+ setTwoFACode('')
+ setIsTwoFaLoading(false)
}
+ }
- 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) {
@@ -210,7 +236,6 @@ const TwoFA = ({
type='text'
className='mt-4'
value={twoFARecovery}
- twoFARecovery
/>
<Button
onClick={recoverySaved}
@@ -238,7 +263,9 @@ const TwoFA = ({
placeholder={t('profileSettings.yourOneTimeCode')}
className='sm:col-span-3'
onChange={handle2FAInput}
+ onKeyDown={callFnOnKeyPress(_disable2FA)}
error={twoFACodeError}
+ disabled={isTwoFaLoading}
/>
<Button
className={cx('ml-2', {
@@ -294,7 +321,9 @@ const TwoFA = ({
placeholder={t('profileSettings.yourOneTimeCode')}
className='sm:col-span-3'
onChange={handle2FAInput}
+ onKeyDown={callFnOnKeyPress(_enable2FA)}
error={twoFACodeError}
+ disabled={isTwoFaLoading}
/>
<Button
className={cx('ml-2', {
diff --git a/src/redux/actions/auth/index.js b/src/redux/actions/auth/index.js
index b04b0c317..c3b381c5f 100644
--- a/src/redux/actions/auth/index.js
+++ b/src/redux/actions/auth/index.js
@@ -4,7 +4,6 @@ import { LS_VIEW_PREFS_SETTING } from 'redux/constants'
import { types } from './types'
export const authActions = {
- // Synchronous
loginSuccess(user) {
return {
type: types.LOGIN_SUCCESSFUL,
diff --git a/src/redux/sagas/auth/workers/signin.js b/src/redux/sagas/auth/workers/signin.js
index 8d4fcc348..c8ee1c222 100644
--- a/src/redux/sagas/auth/workers/signin.js
+++ b/src/redux/sagas/auth/workers/signin.js
@@ -10,17 +10,25 @@ import { login } from 'api'
export default function* singinWorker({ payload: { credentials, callback } }) {
try {
const { dontRemember } = credentials
- const response = yield call(login, credentials)
+ const { user, access_token: accessToken } = yield call(login, credentials)
- yield put(authActions.loginSuccess(response.user))
- yield call(setAccessToken, response.access_token, dontRemember)
yield put(authActions.setDontRemember(dontRemember))
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ yield call(setAccessToken, accessToken, true)
+ yield put(authActions.updateUserData(user))
+ callback(false, true)
+ return
+ }
+
+ yield put(authActions.loginSuccess(user))
+ yield call(setAccessToken, accessToken, dontRemember)
yield put(UIActions.loadProjects())
- callback(true)
+ callback(true, false)
} catch (error) {
const err = _isObject(error) ? error.message : error
yield put(errorsActions.loginFailed(err))
- callback(false)
+ callback(false, false)
} finally {
yield put(authActions.finishLoading())
}
diff --git a/src/ui/Input.jsx b/src/ui/Input.jsx
index c4e3d4160..2a3c8e2df 100644
--- a/src/ui/Input.jsx
+++ b/src/ui/Input.jsx
@@ -5,7 +5,7 @@ import PropTypes from 'prop-types'
import { ExclamationCircleIcon } from '@heroicons/react/solid'
const Input = ({
- label, hint, placeholder, type, id, name, className, onChange, error, value, disabled,
+ label, hint, placeholder, type, id, name, className, onChange, error, value, disabled, onKeyDown,
}) => {
const identifier = id || name || type
const isError = !_isEmpty(error)
@@ -26,6 +26,7 @@ const Input = ({
name={name}
id={identifier}
onChange={onChange}
+ onKeyDown={onKeyDown}
className={cx('shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:text-gray-50 dark:placeholder-gray-400 dark:border-gray-800 dark:bg-gray-700 rounded-md', {
'border-red-300 text-red-900 placeholder-red-300': isError,
})}
@@ -55,6 +56,7 @@ Input.propTypes = {
hint: PropTypes.string,
placeholder: PropTypes.string,
onChange: PropTypes.func,
+ onKeyDown: PropTypes.func,
id: PropTypes.string,
type: PropTypes.string,
className: PropTypes.string,
@@ -70,6 +72,7 @@ Input.defaultProps = {
hint: '',
placeholder: '',
onChange: () => { },
+ onKeyDown: () => { },
id: '',
type: '',
className: '',
diff --git a/src/utils/accessToken.js b/src/utils/accessToken.js
index 6e92ac197..f6fe941dc 100644
--- a/src/utils/accessToken.js
+++ b/src/utils/accessToken.js
@@ -2,6 +2,7 @@ import _isEmpty from 'lodash/isEmpty'
import { TOKEN } from 'redux/constants'
import { getItem, setItem, removeItem } from './localstorage'
+// It's important to first check in local storage, then in session storage, not vice versa.
export const getAccessToken = () => {
let accessToken = getItem(TOKEN)