autenticacion.js 1.35 KB
import { tap } from 'ramda'
import { SENATICS_URL } from '../../constants'

export const ACCESS_TOKEN_REQUESTED = 'ACCESS_TOKEN_REQUESTED'
export const accessTokenRequested = () => ({
    type: ACCESS_TOKEN_REQUESTED
  })


export const ACCESS_TOKEN_RECEIVED = 'ACCESS_TOKEN_RECEIVED'
export const accessTokenReceived = (accessToken) => ({
  type: ACCESS_TOKEN_RECEIVED,
  token: {
    accessToken,
    receivedAt: Date.now()
  }
})


const ACCESS_TOKEN_URL = `${SENATICS_URL}/auth/token`
export const fetchToken = (token, secret) => (dispatch) => {
    dispatch(accessTokenRequested())

    const payload = {
      clientSecret: secret
    }

    const options = {
        method: 'POST',
        body: JSON.stringify(payload),
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: `Basic ${token}`
        },
      }

    const internal = () => fetch(ACCESS_TOKEN_URL, options)
      .then(response => response.text())
      .then(tap(text => dispatch({ type: 'TEXT_RECEIVED', text })))
      .then(JSON.parse)
      .then(json => dispatch(accessTokenReceived(json.accessToken)))
      .catch(error => dispatch(accessTokenFailed(error)))
    return internal()
  }


export const ACCESS_TOKEN_FAILED = 'ACCESS_TOKEN_FAILED'
export const accessTokenFailed = (error) => ({
  type: ACCESS_TOKEN_FAILED,
  error
})