fix: url resolver and minor fixes

This commit is contained in:
Sérgio Salgado 2021-04-20 16:45:30 +01:00 committed by Josh Harvey
parent 2062413c75
commit 75a2ecd3c2
15 changed files with 274 additions and 290 deletions

View file

@ -220,17 +220,14 @@ const resetPassword = (token, userID, newPassword, context) => {
.then(() => true)
}
const reset2FA = (token, userID, code, secret, context) => {
const isCodeValid = otplib.authenticator.verify({ token: code, secret })
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
const reset2FA = (token, userID, code, context) => {
return users.getUserById(userID)
.then(user => {
const isCodeValid = otplib.authenticator.verify({ token: code, secret: user.temp_twofa_code })
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
destroySessionIfSameUser(context, user)
if (user.temp_twofa_code !== secret) {
throw new authErrors.InvalidTwoFactorError()
}
return users.reset2FASecret(token, user.id, secret)
return users.reset2FASecret(token, user.id, user.temp_twofa_code)
})
.then(() => true)
}

View file

@ -28,7 +28,7 @@ const resolver = {
createRegisterToken: (...[, { username, role }]) => authentication.createRegisterToken(username, role),
register: (...[, { token, username, password, role }]) => authentication.register(token, username, password, role),
resetPassword: (...[, { token, userID, newPassword }, context]) => authentication.resetPassword(token, userID, newPassword, context),
reset2FA: (...[, { token, userID, code, secret }, context]) => authentication.reset2FA(token, userID, code, secret, context)
reset2FA: (...[, { token, userID, code }, context]) => authentication.reset2FA(token, userID, code, context)
}
}

View file

@ -71,7 +71,7 @@ const typeDef = `
createRegisterToken(username: String!, role: String!): RegistrationToken @auth(requires: [SUPERUSER])
register(token: String!, username: String!, password: String!, role: String!): Boolean
resetPassword(token: String!, userID: ID!, newPassword: String!): Boolean
reset2FA(token: String!, userID: ID!, secret: String!, code: String!): Boolean
reset2FA(token: String!, userID: ID!, code: String!): Boolean
}
`

View file

@ -1,4 +1,4 @@
import { useLazyQuery } from '@apollo/react-hooks'
import { useQuery } from '@apollo/react-hooks'
import CssBaseline from '@material-ui/core/CssBaseline'
import Grid from '@material-ui/core/Grid'
import Slide from '@material-ui/core/Slide'
@ -11,7 +11,7 @@ import {
import gql from 'graphql-tag'
import { create } from 'jss'
import extendJss from 'jss-plugin-extend'
import React, { useContext, useEffect, useState } from 'react'
import React, { useContext, useState } from 'react'
import {
useLocation,
useHistory,
@ -91,17 +91,13 @@ const Main = () => {
const history = useHistory()
const { wizardTested, userData, setUserData } = useContext(AppContext)
const [getUserData, { loading }] = useLazyQuery(GET_USER_DATA, {
const { loading } = useQuery(GET_USER_DATA, {
onCompleted: userResponse => {
if (!userData && userResponse?.userData)
setUserData(userResponse.userData)
}
})
useEffect(() => {
getUserData()
}, [getUserData])
const route = location.pathname
const sidebar = hasSidebar(route)

View file

@ -47,6 +47,19 @@ const Input2FAState = ({ state, dispatch }) => {
const [invalidToken, setInvalidToken] = useState(false)
const [getUserData, { error: queryError }] = useLazyQuery(GET_USER_DATA, {
onCompleted: ({ userData }) => {
setUserData(userData)
history.push('/')
}
})
const [input2FA, { error: mutationError }] = useMutation(INPUT_2FA, {
onCompleted: ({ input2FA: success }) => {
success ? getUserData() : setInvalidToken(true)
}
})
const handle2FAChange = value => {
dispatch({
type: STATES.INPUT_2FA,
@ -73,19 +86,6 @@ const Input2FAState = ({ state, dispatch }) => {
})
}
const [input2FA, { error: mutationError }] = useMutation(INPUT_2FA, {
onCompleted: ({ input2FA: success }) => {
success ? getUserData() : setInvalidToken(true)
}
})
const [getUserData, { error: queryError }] = useLazyQuery(GET_USER_DATA, {
onCompleted: ({ userData }) => {
setUserData(userData)
history.push('/')
}
})
const getErrorMsg = () => {
if (queryError) return 'Internal server error'
if (state.twoFAField.length !== 6 && invalidToken)

View file

@ -69,12 +69,12 @@ const Register = () => {
const initialState = {
username: null,
role: null,
wasSuccessful: false
result: ''
}
const reducer = (state, action) => {
const { type, payload } = action
return { ...state, [type]: payload }
return { ...state, ...payload, result: type }
}
const [state, dispatch] = useReducer(reducer, initialState)
@ -83,15 +83,23 @@ const Register = () => {
variables: { token: token },
onCompleted: ({ validateRegisterLink: info }) => {
if (!info) {
dispatch({ type: 'wasSuccessful', payload: false })
dispatch({
type: 'failure'
})
} else {
dispatch({ type: 'wasSuccessful', payload: true })
dispatch({ type: 'username', payload: info.username })
dispatch({ type: 'role', payload: info.role })
dispatch({
type: 'success',
payload: {
username: info.username,
role: info.role
}
})
}
},
onError: () => {
dispatch({ type: 'wasSuccessful', payload: false })
dispatch({
type: 'failure'
})
}
})
@ -127,7 +135,7 @@ const Register = () => {
<Logo className={classes.icon} />
<H2 className={classes.title}>Lamassu Admin</H2>
</div>
{!loading && state.wasSuccessful && (
{!loading && state.result === 'success' && (
<Formik
validationSchema={validationSchema}
initialValues={initialValues}
@ -176,7 +184,7 @@ const Register = () => {
)}
</Formik>
)}
{!loading && !state.wasSuccessful && (
{!loading && state.result === 'failure' && (
<>
<Label3>Link has expired</Label3>
</>

View file

@ -3,7 +3,7 @@ import { makeStyles, Grid } from '@material-ui/core'
import Paper from '@material-ui/core/Paper'
import gql from 'graphql-tag'
import QRCode from 'qrcode.react'
import React, { useState } from 'react'
import React, { useReducer, useState } from 'react'
import { useLocation, useHistory } from 'react-router-dom'
import { ActionButton, Button } from 'src/components/buttons'
@ -28,13 +28,8 @@ const VALIDATE_RESET_2FA_LINK = gql`
`
const RESET_2FA = gql`
mutation reset2FA(
$token: String!
$userID: ID!
$secret: String!
$code: String!
) {
reset2FA(token: $token, userID: $userID, secret: $secret, code: $code)
mutation reset2FA($token: String!, $userID: ID!, $code: String!) {
reset2FA(token: $token, userID: $userID, code: $code)
}
`
@ -42,37 +37,52 @@ const Reset2FA = () => {
const classes = useStyles()
const history = useHistory()
const token = QueryParams().get('t')
const [userID, setUserID] = useState(null)
const [isLoading, setLoading] = useState(true)
const [wasSuccessful, setSuccess] = useState(false)
const [secret, setSecret] = useState(null)
const [otpauth, setOtpauth] = useState(null)
const [isShowing, setShowing] = useState(false)
const [invalidToken, setInvalidToken] = useState(false)
const [twoFAConfirmation, setTwoFAConfirmation] = useState('')
const initialState = {
userID: null,
secret: null,
otpauth: null,
result: null
}
const reducer = (state, action) => {
const { type, payload } = action
return { ...state, ...payload, result: type }
}
const [state, dispatch] = useReducer(reducer, initialState)
const handle2FAChange = value => {
setTwoFAConfirmation(value)
setInvalidToken(false)
}
const { error: queryError } = useQuery(VALIDATE_RESET_2FA_LINK, {
const { error: queryError, loading } = useQuery(VALIDATE_RESET_2FA_LINK, {
variables: { token: token },
onCompleted: ({ validateReset2FALink: info }) => {
setLoading(false)
if (!info) {
setSuccess(false)
dispatch({
type: 'failure'
})
} else {
setUserID(info.user_id)
setSecret(info.secret)
setOtpauth(info.otpauth)
setSuccess(true)
dispatch({
type: 'success',
payload: {
userID: info.user_id,
secret: info.secret,
otpauth: info.otpauth
}
})
}
},
onError: () => {
setLoading(false)
setSuccess(false)
dispatch({
type: 'failure'
})
}
})
@ -107,7 +117,7 @@ const Reset2FA = () => {
<Logo className={classes.icon} />
<H2 className={classes.title}>Lamassu Admin</H2>
</div>
{!isLoading && wasSuccessful && (
{!loading && state.result === 'success' && (
<>
<div className={classes.infoWrapper}>
<Label2 className={classes.info2}>
@ -117,7 +127,11 @@ const Reset2FA = () => {
</Label2>
</div>
<div className={classes.qrCodeWrapper}>
<QRCode size={240} fgColor={primaryColor} value={otpauth} />
<QRCode
size={240}
fgColor={primaryColor}
value={state.otpauth}
/>
</div>
<div className={classes.secretWrapper}>
<Label2 className={classes.secretLabel}>
@ -127,7 +141,7 @@ const Reset2FA = () => {
className={
isShowing ? classes.secret : classes.hiddenSecret
}>
{secret}
{state.secret}
</Label2>
<ActionButton
color="primary"
@ -160,8 +174,7 @@ const Reset2FA = () => {
reset2FA({
variables: {
token: token,
userID: userID,
secret: secret,
userID: state.userID,
code: twoFAConfirmation
}
})
@ -172,7 +185,7 @@ const Reset2FA = () => {
</div>
</>
)}
{!isLoading && !wasSuccessful && (
{!loading && state.result === 'failure' && (
<>
<Label3>Link has expired</Label3>
</>

View file

@ -2,7 +2,7 @@ import { useQuery } from '@apollo/react-hooks'
import { makeStyles, Box, Chip } from '@material-ui/core'
import gql from 'graphql-tag'
import * as R from 'ramda'
import React, { useState, useContext } from 'react'
import React, { useReducer, useState, useContext } from 'react'
import AppContext from 'src/AppContext'
import { Link } from 'src/components/buttons'
@ -39,23 +39,27 @@ const Users = () => {
const { data: userResponse } = useQuery(GET_USERS)
const [showCreateUserModal, setShowCreateUserModal] = useState(false)
const toggleCreateUserModal = () =>
setShowCreateUserModal(!showCreateUserModal)
const initialState = {
showCreateUserModal: false,
showResetPasswordModal: false,
showReset2FAModal: false,
showRoleModal: false,
showEnableUserModal: false
}
const [showResetPasswordModal, setShowResetPasswordModal] = useState(false)
const toggleResetPasswordModal = () =>
setShowResetPasswordModal(!showResetPasswordModal)
const reducer = (_, action) => {
const { type, payload } = action
switch (type) {
case 'close':
return initialState
case 'open':
return { ...initialState, [payload]: true }
default:
return initialState
}
}
const [showReset2FAModal, setShowReset2FAModal] = useState(false)
const toggleReset2FAModal = () => setShowReset2FAModal(!showReset2FAModal)
const [showRoleModal, setShowRoleModal] = useState(false)
const toggleRoleModal = () => setShowRoleModal(!showRoleModal)
const [showEnableUserModal, setShowEnableUserModal] = useState(false)
const toggleEnableUserModal = () =>
setShowEnableUserModal(!showEnableUserModal)
const [state, dispatch] = useReducer(reducer, initialState)
const [userInfo, setUserInfo] = useState(null)
@ -103,7 +107,10 @@ const Users = () => {
checked={u.role === 'superuser'}
onClick={() => {
setUserInfo(u)
toggleRoleModal()
dispatch({
type: 'open',
payload: 'showRoleModal'
})
}}
value={u.role === 'superuser'}
/>
@ -130,7 +137,10 @@ const Users = () => {
className={classes.actionChip}
onClick={() => {
setUserInfo(u)
toggleResetPasswordModal()
dispatch({
type: 'open',
payload: 'showResetPasswordModal'
})
}}
/>
<Chip
@ -139,7 +149,10 @@ const Users = () => {
className={classes.actionChip}
onClick={() => {
setUserInfo(u)
toggleReset2FAModal()
dispatch({
type: 'open',
payload: 'showReset2FAModal'
})
}}
/>
</>
@ -157,7 +170,10 @@ const Users = () => {
checked={u.enabled}
onClick={() => {
setUserInfo(u)
toggleEnableUserModal()
dispatch({
type: 'open',
payload: 'showEnableUserModal'
})
}}
value={u.enabled}
/>
@ -174,36 +190,40 @@ const Users = () => {
className={classes.tableWidth}
display="flex"
justifyContent="flex-end">
<Link color="primary" onClick={toggleCreateUserModal}>
<Link
color="primary"
onClick={() => {
dispatch({
type: 'open',
payload: 'showCreateUserModal'
})
}}>
Add new user
</Link>
</Box>
<DataTable elements={elements} data={R.path(['users'])(userResponse)} />
<CreateUserModal
showModal={showCreateUserModal}
toggleModal={toggleCreateUserModal}
/>
<CreateUserModal state={state} dispatch={dispatch} />
<ResetPasswordModal
showModal={showResetPasswordModal}
toggleModal={toggleResetPasswordModal}
state={state}
dispatch={dispatch}
user={userInfo}
requiresConfirmation={userInfo?.role === 'superuser'}
/>
<Reset2FAModal
showModal={showReset2FAModal}
toggleModal={toggleReset2FAModal}
state={state}
dispatch={dispatch}
user={userInfo}
requiresConfirmation={userInfo?.role === 'superuser'}
/>
<ChangeRoleModal
showModal={showRoleModal}
toggleModal={toggleRoleModal}
state={state}
dispatch={dispatch}
user={userInfo}
requiresConfirmation={userInfo?.role === 'superuser'}
/>
<EnableUserModal
showModal={showEnableUserModal}
toggleModal={toggleEnableUserModal}
state={state}
dispatch={dispatch}
user={userInfo}
requiresConfirmation={userInfo?.role === 'superuser'}
/>

View file

@ -29,12 +29,7 @@ const CHANGE_USER_ROLE = gql`
const useStyles = makeStyles(styles)
const ChangeRoleModal = ({
showModal,
toggleModal,
user,
requiresConfirmation
}) => {
const ChangeRoleModal = ({ state, dispatch, user, requiresConfirmation }) => {
const classes = useStyles()
const [changeUserRole] = useMutation(CHANGE_USER_ROLE, {
@ -56,18 +51,21 @@ const ChangeRoleModal = ({
const handleClose = () => {
setConfirmation(null)
toggleModal()
dispatch({
type: 'close',
payload: 'showRoleModal'
})
}
return (
(showModal && requiresConfirmation && !confirmation && (
(state.showRoleModal && requiresConfirmation && !confirmation && (
<Input2FAModal
showModal={showModal}
showModal={state.showRoleModal}
handleClose={handleClose}
setConfirmation={setConfirmation}
/>
)) ||
(showModal && (
(state.showRoleModal && (
<Modal
closeOnBackdropClick={true}
width={450}

View file

@ -12,7 +12,7 @@ import { Button } from 'src/components/buttons'
import { TextInput, RadioGroup } from 'src/components/inputs/formik'
import { H1, H3, Info2, P, Mono } from 'src/components/typography'
import CopyToClipboard from 'src/pages/Transactions/CopyToClipboard'
import { URI } from 'src/utils/apollo'
import { urlResolver } from 'src/utils/urlResolver'
import styles from '../UserManagement.styles'
@ -39,7 +39,7 @@ const initialValues = {
role: ''
}
const CreateUserModal = ({ showModal, toggleModal }) => {
const CreateUserModal = ({ state, dispatch }) => {
const classes = useStyles()
const [usernameField, setUsernameField] = useState('')
@ -58,12 +58,15 @@ const CreateUserModal = ({ showModal, toggleModal }) => {
const handleClose = () => {
setCreateUserURL(null)
toggleModal()
dispatch({
type: 'close',
payload: 'showCreateUserModal'
})
}
const [createUser, { error }] = useMutation(CREATE_USER, {
onCompleted: ({ createRegisterToken: token }) => {
setCreateUserURL(`${URI}/register?t=${token.token}`)
setCreateUserURL(urlResolver(`/register?t=${token.token}`))
}
})
@ -81,7 +84,7 @@ const CreateUserModal = ({ showModal, toggleModal }) => {
return (
<>
{showModal && !createUserURL && (
{state.showCreateUserModal && !createUserURL && (
<Modal
closeOnBackdropClick={true}
width={600}
@ -137,7 +140,7 @@ const CreateUserModal = ({ showModal, toggleModal }) => {
</Formik>
</Modal>
)}
{showModal && createUserURL && (
{state.showCreateUserModal && createUserURL && (
<Modal
closeOnBackdropClick={true}
width={500}

View file

@ -1,72 +0,0 @@
import { makeStyles } from '@material-ui/core/styles'
import React from 'react'
import Modal from 'src/components/Modal'
import { Button } from 'src/components/buttons'
import { Info2, P } from 'src/components/typography'
import styles from '../UserManagement.styles'
const useStyles = makeStyles(styles)
const DeleteUserModal = ({
showModal,
toggleModal,
user,
confirm,
inputConfirmToggle,
setAction
}) => {
const classes = useStyles()
const handleClose = () => {
toggleModal()
}
return (
showModal && (
<Modal
closeOnBackdropClick={true}
width={600}
height={275}
handleClose={handleClose}
open={true}>
<Info2 className={classes.modalTitle}>Delete {user.username}?</Info2>
<P className={classes.info}>
You are about to delete {user.username}. This will remove existent
sessions and revoke this user's permissions to access the system.
</P>
<P className={classes.info}>
This is a <b>PERMANENT</b> operation. Do you wish to proceed?
</P>
<div className={classes.footer}>
<Button
className={classes.submit}
onClick={() => {
if (user.role === 'superuser') {
setAction(() =>
confirm.bind(null, {
variables: {
id: user.id
}
})
)
inputConfirmToggle()
} else {
confirm({
variables: {
id: user.id
}
})
}
handleClose()
}}>
Confirm
</Button>
</div>
</Modal>
)
)
}
export default DeleteUserModal

View file

@ -29,12 +29,7 @@ const DISABLE_USER = gql`
const useStyles = makeStyles(styles)
const EnableUserModal = ({
showModal,
toggleModal,
user,
requiresConfirmation
}) => {
const EnableUserModal = ({ state, dispatch, user, requiresConfirmation }) => {
const classes = useStyles()
const [enableUser] = useMutation(ENABLE_USER, {
@ -47,37 +42,46 @@ const EnableUserModal = ({
const [confirmation, setConfirmation] = useState(null)
const disable = () => {
disableUser({
variables: {
confirmationCode: confirmation,
id: user.id
}
})
}
const enable = () => {
enableUser({
variables: {
confirmationCode: confirmation,
id: user.id
}
})
}
const submit = () => {
user?.enabled
? disableUser({
variables: {
confirmationCode: confirmation,
id: user.id
}
})
: enableUser({
variables: {
confirmationCode: confirmation,
id: user.id
}
})
user?.enabled ? disable() : enable()
handleClose()
}
const handleClose = () => {
setConfirmation(null)
toggleModal()
dispatch({
type: 'close',
payload: 'showEnableUserModal'
})
}
return (
(showModal && requiresConfirmation && !confirmation && (
(state.showEnableUserModal && requiresConfirmation && !confirmation && (
<Input2FAModal
showModal={showModal}
showModal={state.showEnableUserModal}
handleClose={handleClose}
setConfirmation={setConfirmation}
/>
)) ||
(showModal && (
(state.showEnableUserModal && (
<Modal
closeOnBackdropClick={true}
width={450}

View file

@ -6,7 +6,7 @@ import React, { useEffect, useState } from 'react'
import Modal from 'src/components/Modal'
import { Info2, P, Mono } from 'src/components/typography'
import CopyToClipboard from 'src/pages/Transactions/CopyToClipboard'
import { URI } from 'src/utils/apollo'
import { urlResolver } from 'src/utils/urlResolver'
import styles from '../UserManagement.styles'
@ -24,12 +24,7 @@ const CREATE_RESET_2FA_TOKEN = gql`
const useStyles = makeStyles(styles)
const Reset2FAModal = ({
showModal,
toggleModal,
user,
requiresConfirmation
}) => {
const Reset2FAModal = ({ state, dispatch, user, requiresConfirmation }) => {
const classes = useStyles()
const [reset2FAUrl, setReset2FAUrl] = useState('')
@ -37,7 +32,7 @@ const Reset2FAModal = ({
CREATE_RESET_2FA_TOKEN,
{
onCompleted: ({ createReset2FAToken: token }) => {
setReset2FAUrl(`${URI}/reset2fa?t=${token.token}`)
setReset2FAUrl(urlResolver(`/reset2fa?t=${token.token}`))
}
}
)
@ -45,7 +40,7 @@ const Reset2FAModal = ({
const [confirmation, setConfirmation] = useState(null)
useEffect(() => {
showModal &&
state.showReset2FAModal &&
(confirmation || !requiresConfirmation) &&
createReset2FAToken({
variables: {
@ -53,22 +48,33 @@ const Reset2FAModal = ({
userID: user?.id
}
})
}, [confirmation, createReset2FAToken, requiresConfirmation, showModal, user])
}, [
confirmation,
createReset2FAToken,
requiresConfirmation,
state.showReset2FAModal,
user?.id
])
const handleClose = () => {
setConfirmation(null)
toggleModal()
dispatch({
type: 'close',
payload: 'showReset2FAModal'
})
}
return (
(showModal && requiresConfirmation && !confirmation && (
(state.showReset2FAModal && requiresConfirmation && !confirmation && (
<Input2FAModal
showModal={showModal}
showModal={state.showReset2FAModal}
handleClose={handleClose}
setConfirmation={setConfirmation}
/>
)) ||
(showModal && (confirmation || !requiresConfirmation) && !loading && (
(state.showReset2FAModal &&
(confirmation || !requiresConfirmation) &&
!loading && (
<Modal
closeOnBackdropClick={true}
width={500}

View file

@ -6,7 +6,7 @@ import React, { useEffect, useState } from 'react'
import Modal from 'src/components/Modal'
import { Info2, P, Mono } from 'src/components/typography'
import CopyToClipboard from 'src/pages/Transactions/CopyToClipboard'
import { URI } from 'src/utils/apollo'
import { urlResolver } from 'src/utils/urlResolver'
import styles from '../UserManagement.styles'
@ -28,8 +28,8 @@ const CREATE_RESET_PASSWORD_TOKEN = gql`
const useStyles = makeStyles(styles)
const ResetPasswordModal = ({
showModal,
toggleModal,
state,
dispatch,
user,
requiresConfirmation
}) => {
@ -40,7 +40,7 @@ const ResetPasswordModal = ({
CREATE_RESET_PASSWORD_TOKEN,
{
onCompleted: ({ createResetPasswordToken: token }) => {
setResetPasswordUrl(`${URI}/resetpassword?t=${token.token}`)
setResetPasswordUrl(urlResolver(`/resetpassword?t=${token.token}`))
}
}
)
@ -48,7 +48,7 @@ const ResetPasswordModal = ({
const [confirmation, setConfirmation] = useState(null)
useEffect(() => {
showModal &&
state.showResetPasswordModal &&
(confirmation || !requiresConfirmation) &&
createResetPasswordToken({
variables: {
@ -59,25 +59,30 @@ const ResetPasswordModal = ({
}, [
confirmation,
createResetPasswordToken,
showModal,
user,
requiresConfirmation
requiresConfirmation,
state.showResetPasswordModal,
user?.id
])
const handleClose = () => {
setConfirmation(null)
toggleModal()
dispatch({
type: 'close',
payload: 'showResetPasswordModal'
})
}
return (
(showModal && requiresConfirmation && !confirmation && (
(state.showResetPasswordModal && requiresConfirmation && !confirmation && (
<Input2FAModal
showModal={showModal}
showModal={state.showResetPasswordModal}
handleClose={handleClose}
setConfirmation={setConfirmation}
/>
)) ||
(showModal && (confirmation || !requiresConfirmation) && !loading && (
(state.showResetPasswordModal &&
(confirmation || !requiresConfirmation) &&
!loading && (
<Modal
closeOnBackdropClick={true}
width={500}

View file

@ -0,0 +1,6 @@
const url =
process.env.NODE_ENV === 'development' ? 'https://localhost:3001' : ''
const urlResolver = content => `${url}${content}`
export { urlResolver }