autenticacion.js 1.53 KB
import EC from 'elliptic'
import { tap } from 'ramda'
import uuid from 'uuid/v1'
import { Buffer } from 'buffer/'
import { ownPrivate } from '../../constants/keys'
import { BACKEND_URL } from '../../constants'

const ec = new EC.ec('secp256k1')
const clientPriv = ec.keyFromPrivate(ownPrivate)

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()
  }
})


export const fetchToken = () => (dispatch) => {
    dispatch(accessTokenRequested())
    const nonce = uuid()
    const firma = new Buffer(clientPriv.sign(nonce).toDER()).toString('hex')
    const options = {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      }

    const ACCESS_TOKEN_URL = `${BACKEND_URL}/token/${nonce}/${firma}`
    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
})