You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.9 KiB
56 lines
1.9 KiB
|
|
import { connect } from 'react-redux'
|
|
import { handleApiError } from 'src/api/errors'
|
|
import { authenticate } from 'src/actions/authentication'
|
|
import { showNotification } from 'src/actions/notifications'
|
|
import { getChecked, getAuthenticated } from 'src/selectors/authentication'
|
|
import { getFieldValue } from 'src/selectors/forms'
|
|
import { getIsFetching } from 'src/selectors/requests'
|
|
import { initForm, initField, setFieldNotification } from 'src/actions/forms'
|
|
import { AppState, AppThunkDispatch, NotificationType, RequestKey } from 'src/types'
|
|
|
|
import Login, { Props } from './login'
|
|
|
|
const mapStateToProps = (state: AppState) => ({
|
|
checked: getChecked(state),
|
|
authenticated: getAuthenticated(state),
|
|
name: getFieldValue(state, 'name', ''),
|
|
password: getFieldValue(state, 'password', ''),
|
|
authenticating: getIsFetching(state, RequestKey.Authenticate),
|
|
})
|
|
|
|
const mapDispatchToProps = (dispatch: AppThunkDispatch, ownProps: Props) => ({
|
|
initForm: () => {
|
|
dispatch(initForm())
|
|
dispatch(initField('name', 'id'))
|
|
dispatch(initField('password'))
|
|
},
|
|
authenticate: async (name: string, password: string) => {
|
|
let invalid = false
|
|
|
|
if (!name) {
|
|
dispatch(setFieldNotification('name', NotificationType.Error, 'This is required'))
|
|
invalid = true
|
|
}
|
|
|
|
if (!password) {
|
|
dispatch(setFieldNotification('password', NotificationType.Error, 'This is required'))
|
|
invalid = true
|
|
}
|
|
|
|
if (invalid) return
|
|
|
|
try {
|
|
const id = await dispatch(authenticate(name, password))
|
|
dispatch(showNotification(NotificationType.Welcome, `Welcome back ${id}!`))
|
|
ownProps.history.push('/')
|
|
} catch (err) {
|
|
handleApiError(err, dispatch, ownProps.history)
|
|
}
|
|
},
|
|
})
|
|
|
|
export default connect(
|
|
mapStateToProps,
|
|
mapDispatchToProps
|
|
)(Login)
|