Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion admin/src/components/auth/sign-in-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@ class SignInForm extends Component {
<Field component="input" name="password" type="password" />
</div>
</div>
<button type="submit">Sign In</button>
{!this.props.tooManySignInAttempts && (
<button type="submit">Sign In</button>
)}
</form>
{this.props.tooManySignInAttempts && (
<h4 style={{ color: 'red' }}>Too many attempts!</h4>
)}
</div>
)
}
Expand Down
15 changes: 12 additions & 3 deletions admin/src/components/routes/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Route, NavLink } from 'react-router-dom'
import { connect } from 'react-redux'
import SignInForm from '../../auth/sign-in-form'
import SignUpForm from '../../auth/sign-up-form'
import { signIn, signUp } from '../../../ducks/auth'
import { signIn, signUp, tooManySignInAttempts } from '../../../ducks/auth'

class AuthPage extends Component {
static propTypes = {}
Expand All @@ -25,14 +25,23 @@ class AuthPage extends Component {
)
}

getSignInForm = () => <SignInForm onSubmit={this.handleSignIn} />
getSignInForm = () => (
<SignInForm
onSubmit={this.handleSignIn}
tooManySignInAttempts={this.props.tooManySignInAttempts}
/>
)
getSignUpForm = () => <SignUpForm onSubmit={this.handleSignUp} />

handleSignIn = ({ email, password }) => this.props.signIn(email, password)
handleSignUp = ({ email, password }) => this.props.signUp(email, password)
}

const mapStateToProps = (state) => ({
tooManySignInAttempts: tooManySignInAttempts(state)
})

export default connect(
null,
mapStateToProps,
{ signIn, signUp }
)(AuthPage)
77 changes: 77 additions & 0 deletions admin/src/ducks/auth.adv.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { recordSaga } from './utils'
import {
signInSaga,
signInErrorSaga,
signInError,
signIn,
signInSuccess,
SIGN_IN_ATTEMPT_COUNT_INC,
SIGN_IN_ATTEMPT_COUNT_RESET,
moduleName,
ReducerRecord,
MAX_SIGN_IN_ATTEMPT_COUNT
} from './auth'
import api from '../services/api'

describe('Auth', () => {
beforeEach(() => {
jest.resetAllMocks()
})

it('should successfully sign in user', async () => {
const email = '[email protected]'
const password = 'joHNdoE'
const initialAction = signIn(email, password)
const user = {
id: 42,
name: 'John Doe'
}

api.signIn = jest
.fn()
.mockImplementation((email, password) => Promise.resolve(user))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок, но идея в том, что тут юнит тесты не нуждаются в моках. А это уже интеграционные

const dispatched = await recordSaga(signInSaga, initialAction)

expect(api.signIn).toHaveBeenCalledWith(email, password)
expect(dispatched).toContainEqual(signInSuccess(user))
})

it('should emit sign in error', async () => {
const error = new Error('something happened')
const email = '[email protected]'
const password = 'joHNdoE'
const initialAction = signIn(email, password)

api.signIn = jest
.fn()
.mockImplementation((email, password) => Promise.reject(error))
const dispatched = await recordSaga(signInSaga, initialAction)

expect(api.signIn).toHaveBeenCalledWith(email, password)
expect(dispatched).toContainEqual(signInError(error))
})

it('should increment failed attempt count', async () => {
const initialAction = signInError(new Error('something happened'))
const initialState = { [moduleName]: new ReducerRecord() }

const dispatched = await recordSaga(
signInErrorSaga,
initialAction,
initialState
)

expect(dispatched).toContainEqual({ type: SIGN_IN_ATTEMPT_COUNT_INC })
})

// it('should reset sign in errors count', async () => {
// const initialAction = signInError(new Error('something happened'))
// const initialState = { [moduleName]: new ReducerRecord({ signInAttemptCount: MAX_SIGN_IN_ATTEMPT_COUNT + 1 }) }
// delay.mockImplementation(() => Promise.resolve())

// const dispatched = await recordSaga(signInErrorSaga, initialAction, initialState)

// expect(dispatched).toContainEqual({ type: SIGN_IN_ATTEMPT_COUNT_INC })
// expect(dispatched).toContainEqual({ type: SIGN_IN_ATTEMPT_COUNT_RESET })
// })
})
84 changes: 71 additions & 13 deletions admin/src/ducks/auth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { appName } from '../config'
import { Record } from 'immutable'
import { createSelector } from 'reselect'
import { takeEvery, call, put, all } from 'redux-saga/effects'
import { takeEvery, call, put, all, select, delay } from 'redux-saga/effects'
import api from '../services/api'

/**
Expand All @@ -13,14 +13,24 @@ const prefix = `${appName}/${moduleName}`
export const SIGN_IN_REQUEST = `${prefix}/SIGN_IN_REQUEST`
export const SIGN_IN_SUCCESS = `${prefix}/SIGN_IN_SUCCESS`
export const SIGN_IN_ERROR = `${prefix}/SIGN_IN_ERROR`

export const SIGN_UP_REQUEST = `${prefix}/SIGN_UP_REQUEST`
export const SIGN_UP_SUCCESS = `${prefix}/SIGN_UP_SUCCESS`
export const SIGN_UP_ERROR = `${prefix}/SIGN_UP_ERROR`

export const AUTH_STATE_CHANGE = `${prefix}/AUTH_STATE_CHANGE`

export const SIGN_IN_ATTEMPT_COUNT_INC = `${prefix}/SIGN_IN_ATTEMPT_COUNT_INC`
export const SIGN_IN_ATTEMPT_COUNT_RESET = `${prefix}/SIGN_IN_ATTEMPT_COUNT_RESET`

export const MAX_SIGN_IN_ATTEMPT_COUNT = 3

/**
* Reducer
* */
export const ReducerRecord = Record({
user: null
user: null,
signInAttemptCount: 0
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот это можно на уровне саги делать, не обязательно в сторе хранить

})

export default function reducer(state = new ReducerRecord(), action) {
Expand All @@ -31,7 +41,13 @@ export default function reducer(state = new ReducerRecord(), action) {
case SIGN_UP_SUCCESS:
case AUTH_STATE_CHANGE:
return state.set('user', payload.user)

case SIGN_IN_ATTEMPT_COUNT_INC:
return state.set(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.update

'signInAttemptCount',
state.get('signInAttemptCount') + 1
)
case SIGN_IN_ATTEMPT_COUNT_RESET:
return state.set('signInAttemptCount', 0)
default:
return state
}
Expand All @@ -47,6 +63,13 @@ export const isAuthorizedSelector = createSelector(
(user) => !!user
)

export const signInAttemptCount = (state) =>
state[moduleName].signInAttemptCount
export const tooManySignInAttempts = createSelector(
signInAttemptCount,
(count) => count > MAX_SIGN_IN_ATTEMPT_COUNT
)

/**
* Init logic
*/
Expand All @@ -71,13 +94,24 @@ export function signIn(email, password) {
}

export function signUp(email, password) {
return (dispatch) =>
api.signUp(email, password).then((user) =>
dispatch({
type: SIGN_UP_SUCCESS,
payload: { user }
})
)
return {
type: SIGN_UP_REQUEST,
payload: { email, password }
}
}

export function signInSuccess(user) {
return {
type: SIGN_IN_SUCCESS,
payload: { user }
}
}

export function signInError(error) {
return {
type: SIGN_IN_ERROR,
error
}
}

/**
Expand All @@ -88,18 +122,42 @@ export function* signInSaga({ payload: { email, password } }) {
try {
const user = yield call(api.signIn, email, password)

yield put(signInSuccess(user))
} catch (error) {
yield put(signInError(error))
}
}

export function* signUpSaga({ payload: { email, password } }) {
try {
const user = yield call(api.signUp, email, password)

yield put({
type: SIGN_IN_SUCCESS,
type: SIGN_UP_SUCCESS,
payload: { user }
})
} catch (error) {
yield put({
type: SIGN_IN_ERROR,
type: SIGN_UP_ERROR,
error
})
}
}

export function* signInErrorSaga(action) {
yield put({ type: SIGN_IN_ATTEMPT_COUNT_INC })
const tooManyAttempts = yield select(tooManySignInAttempts)

if (tooManyAttempts) {
yield delay(3000)
yield put({ type: SIGN_IN_ATTEMPT_COUNT_RESET })
}
}

export function* saga() {
yield all([takeEvery(SIGN_IN_REQUEST, signInSaga)])
yield all([
takeEvery(SIGN_IN_REQUEST, signInSaga),
takeEvery(SIGN_UP_REQUEST, signUpSaga),
takeEvery(SIGN_IN_ERROR, signInErrorSaga)
])
}
77 changes: 77 additions & 0 deletions admin/src/ducks/auth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { put, call, select, delay } from 'redux-saga/effects'
import {
signInSaga,
signInErrorSaga,
signIn,
signInSuccess,
signInError,
tooManySignInAttempts,
SIGN_IN_ATTEMPT_COUNT_INC,
SIGN_IN_ATTEMPT_COUNT_RESET
} from './auth'
import api from '../services/api'

describe('Auth', () => {
it('should successfully sign in user', () => {
const user = {
id: 42,
name: 'John Doe'
}
const email = '[email protected]'
const password = 'joHNdoE'
const action = signIn(email, password)

const gen = signInSaga(action)

expect(gen.next().value).toEqual(call(api.signIn, email, password))

expect(gen.next(user).value).toEqual(put(signInSuccess(user)))

expect(gen.next(false).done).toBe(true)
})

it('should fail to sign in user', () => {
const error = new Error('something happened')
const email = '[email protected]'
const password = 'joHNdoE'
const action = signIn(email, password)

const gen = signInSaga(action)

expect(gen.next().value).toEqual(call(api.signIn, email, password))

expect(gen.throw(error).value).toEqual(put(signInError(error)))

expect(gen.next(false).done).toBe(true)
})

it('should increment failed attempt count', () => {
const action = signInError({})

const gen = signInErrorSaga(action)

expect(gen.next().value).toEqual(put({ type: SIGN_IN_ATTEMPT_COUNT_INC }))

expect(gen.next().value).toEqual(select(tooManySignInAttempts))

expect(gen.next(false).done).toBe(true)
})

it('should reset failed attempt count', () => {
const action = signInError({})

const gen = signInErrorSaga(action)

expect(gen.next().value).toEqual(put({ type: SIGN_IN_ATTEMPT_COUNT_INC }))

expect(gen.next().value).toEqual(select(tooManySignInAttempts))

expect(gen.next(true).value).toEqual(delay(3000))

expect(gen.next(true).value).toEqual(
put({ type: SIGN_IN_ATTEMPT_COUNT_RESET })
)

expect(gen.next(false).done).toBe(true)
})
})
17 changes: 17 additions & 0 deletions admin/src/ducks/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
import { runSaga } from 'redux-saga'

export function generateId() {
return Date.now()
}

export async function recordSaga(saga, initialAction, initialState) {
const dispatched = []

await runSaga(
{
dispatch: (action) => dispatched.push(action),
getState: () => initialState || {}
},
saga,
initialAction
).done

return dispatched
}