blob: 7eabacc594c6421cc4b1504a58af269d000376b7 (
plain)
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
|
import fetch from 'node-fetch'
import jsonwebtoken from 'jsonwebtoken'
import * as types from 'app/types'
import { session } from 'app/session'
const urls = {
login: "/api/v1/auth/login",
}
export const login = data => dispatch => (
fetch(urls.login, {
method: 'POST',
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(req => req.json())
.then(res => {
if (!res.token) {
throw new Error(res.description)
}
session.set('access_token', res.token)
load_access_token()(dispatch)
})
)
export const load_access_token = () => dispatch => {
const access_token = session.get('access_token') || null
if (access_token) {
const creds = jsonwebtoken.decode(access_token)
return dispatch({ type: types.auth.logged_in, user: creds.sub })
} else {
return dispatch({ type: types.auth.logged_out })
}
}
export const logout = (e) => dispatch => {
e && e.preventDefault()
session.set('access_token', '')
return dispatch({ type: types.auth.logged_out })
}
|