Skip to content
Snippets Groups Projects
utils.js 2.48 KiB
Newer Older
import { omit, get } from 'lodash'
import { create } from 'pubsweet-client/src/helpers/api'
import { loginUser } from 'pubsweet-component-login/actions'

import { handleFormError } from '../utils'

const generatePasswordHash = () =>
  Array.from({ length: 4 }, () =>
    Math.random()
      .toString(36)
      .slice(4),
  ).join('')

export const parseSignupAuthor = ({ token, confirmPassword, ...values }) => ({
  ...values,
  admin: false,
  isConfirmed: false,
  editorInChief: false,
  handlingEditor: false,
  username: values.email,
  confirmationToken: generatePasswordHash(),
Alexandru Munteanu's avatar
Alexandru Munteanu committed
  notifications: {
Alexandru Munteanu's avatar
Alexandru Munteanu committed
    email: {
Alexandru Munteanu's avatar
Alexandru Munteanu committed
      system: true,
      user: true,
    },
  },

export const parseSearchParams = url => {
  const params = new URLSearchParams(url)
  const parsedObject = {}
  for ([key, value] of params) {
    parsedObject[key] = value
  }
  return parsedObject
}

export const login = (dispatch, values, history) =>
  dispatch(loginUser(values))
    .then(() => {
      history.replace('/')
    })
    .catch(handleFormError)

export const confirmUser = (email, token, history) => (values, dispatch) => {
  const request = { ...values, email, token }
  if (values) {
    return create('/users/reset-password', omit(request, ['confirmPassword']))
      .then(r => {
        const { username } = r
        const { password } = values
        login(dispatch, { username, password }, history)
      })
      .catch(handleFormError)
  }
}

export const signUpUser = history => (values, dispatch) =>
  create('/users', parseSignupAuthor(values))
    .then(r => {
      const { username } = r
      const { password } = values
      login(dispatch, { username, password }, history).then(() => {
        create('/emails', {
          email: values.email,
          type: 'signup',
        })
      })
    })
    .catch(handleFormError)

export const resetUserPassword = history => ({ email }, dispatch) =>
  create(`/users/forgot-password`, { email })
    .then(r => {
      const message = get(r, 'message', 'Password reset email has been sent.')
      history.push('/info-page', {
        title: 'Reset Password',
        content: message,
      })
    })
    .catch(handleFormError)

export const setNewPassword = history => (
  { email, token, password },
  dispatch,
) =>
  create(`/users/reset-password`, { email, token, password })
    .then(() => {
      login(dispatch, { username: email, password }, history).then(() =>
        history.push('/'),
      )
    })
    .catch(handleFormError)