|
1 | 1 | import axios from 'axios'; |
| 2 | +import jwtDecode from 'jwt-decode'; |
| 3 | +import setAuthorizationToken from '../utils/setAuthorizationToken'; |
2 | 4 |
|
3 | | -export const LOGGED_IN = 'LOGGED_IN'; |
4 | | -export const LOGGED_OUT = 'LOGGED_OUT'; |
| 5 | +export const SET_CURRENT_USER = 'SET_CURRENT_USER'; |
5 | 6 |
|
6 | | -export function loggedIn(data) { |
7 | | - return { type: LOGGED_IN, data }; |
| 7 | +export function setCurrentUser(user) { |
| 8 | + return { type: SET_CURRENT_USER, user } |
8 | 9 | } |
9 | 10 |
|
10 | | -export function loggedOut(data) { |
11 | | - return { type: LOGGED_OUT, data }; |
12 | | -} |
13 | | - |
14 | | -export function logIn(data) { |
| 11 | +export function logout() { |
15 | 12 | return dispatch => { |
16 | | - const { identifier, password } = data; |
17 | | - axios.post('/api/auth/login', { identifier, password }) |
18 | | - .then(response => dispatch(loggedIn(response.data))) |
19 | | - .catch(err => console.error(err)); |
20 | | - }; |
21 | | -}; |
| 13 | + // Remove token from storage |
| 14 | + localStorage.removeItem('jwtToken'); |
| 15 | + // Remove token from request headers |
| 16 | + setAuthorizationToken(false); |
| 17 | + // Send empty user to reducer |
| 18 | + dispatch(setCurrentUser({})); |
| 19 | + } |
| 20 | +} |
22 | 21 |
|
23 | | -export function logOut(data) { |
| 22 | +export function login(data) { |
24 | 23 | return dispatch => { |
25 | | - const { identifier } = data; |
26 | | - axios.get('/api/auth/logout', { identifier }) |
27 | | - .then(() => dispatch(loggedOut(identifier))) |
28 | | - .catch(err => console.error(err)); |
29 | | - }; |
| 24 | + return axios.post('/api/auth', data).then(res => { |
| 25 | + // Receive token |
| 26 | + const token = res.data.token; |
| 27 | + // Create token key in storage |
| 28 | + localStorage.setItem('jwtToken', token); |
| 29 | + // Add token in header requests for future actions |
| 30 | + setAuthorizationToken(token); |
| 31 | + // Promises data to reducer |
| 32 | + dispatch(setCurrentUser(jwtDecode(token))); |
| 33 | + }); |
| 34 | + } |
30 | 35 | } |
0 commit comments