autenticacion.js
1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
})