2016-02-25 12:31:21 -08:00
|
|
|
import { currentBackend } from '../backends/backend';
|
|
|
|
|
|
|
|
export const AUTH_REQUEST = 'AUTH_REQUEST';
|
|
|
|
export const AUTH_SUCCESS = 'AUTH_SUCCESS';
|
|
|
|
export const AUTH_FAILURE = 'AUTH_FAILURE';
|
2016-11-01 14:35:20 +01:00
|
|
|
export const LOGOUT = 'LOGOUT';
|
2016-02-25 12:31:21 -08:00
|
|
|
|
|
|
|
export function authenticating() {
|
|
|
|
return {
|
2016-11-01 14:35:20 +01:00
|
|
|
type: AUTH_REQUEST,
|
2016-02-25 12:31:21 -08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function authenticate(userData) {
|
|
|
|
return {
|
|
|
|
type: AUTH_SUCCESS,
|
2016-11-01 14:35:20 +01:00
|
|
|
payload: userData,
|
2016-02-25 12:31:21 -08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function authError(error) {
|
|
|
|
return {
|
|
|
|
type: AUTH_FAILURE,
|
|
|
|
error: 'Failed to authenticate',
|
|
|
|
payload: error,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-11-01 14:35:20 +01:00
|
|
|
export function logout() {
|
|
|
|
return {
|
|
|
|
type: LOGOUT,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2017-01-26 19:23:42 -02:00
|
|
|
// Check if user data token is cached and is valid
|
|
|
|
export function authenticateUser() {
|
|
|
|
return (dispatch, getState) => {
|
|
|
|
const state = getState();
|
|
|
|
const backend = currentBackend(state.config);
|
|
|
|
dispatch(authenticating());
|
|
|
|
return backend.currentUser()
|
|
|
|
.then((user) => {
|
|
|
|
if (user) dispatch(authenticate(user));
|
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
dispatch(authError(error));
|
|
|
|
dispatch(logoutUser());
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-02-25 12:31:21 -08:00
|
|
|
export function loginUser(credentials) {
|
|
|
|
return (dispatch, getState) => {
|
|
|
|
const state = getState();
|
|
|
|
const backend = currentBackend(state.config);
|
|
|
|
|
|
|
|
dispatch(authenticating());
|
2016-05-30 17:13:40 -07:00
|
|
|
return backend.authenticate(credentials)
|
2016-11-01 14:35:20 +01:00
|
|
|
.then((user) => {
|
|
|
|
dispatch(authenticate(user));
|
2017-01-26 19:23:42 -02:00
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
dispatch(authError(error));
|
2016-11-01 14:35:20 +01:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function logoutUser() {
|
|
|
|
return (dispatch, getState) => {
|
|
|
|
const state = getState();
|
|
|
|
const backend = currentBackend(state.config);
|
|
|
|
backend.logout();
|
|
|
|
dispatch(logout());
|
2016-02-25 12:31:21 -08:00
|
|
|
};
|
|
|
|
}
|