Skip to content

Instantly share code, notes, and snippets.

@belozer
Created August 8, 2016 08:17
Show Gist options
  • Save belozer/29ad24f22262090861ac0b3f36eabb71 to your computer and use it in GitHub Desktop.
Save belozer/29ad24f22262090861ac0b3f36eabb71 to your computer and use it in GitHub Desktop.
modules.define('auth', ['store', 'server-store'],
(provide, store, server) => {
const SET_TOKEN = 'AUTH/SET_TOKEN';
const SET_USER_DATA = 'AUTH/SET_USER_DATA';
const DESTROY = 'AUTH/DESTROY';
/**
* Редьюсер для аутентификации пользователя
* @param {object} state - prevent state
* @param {object} action - action
* @return {object} new auth state
*/
function authReducer(state = {}, action) {
switch (action.type) {
case SET_TOKEN:
return Object.assign({}, state, action.payload);
case SET_USER_DATA:
return Object.assign({}, state, action.payload);
case DESTROY:
return {};
default:
return state;
}
}
store.injectAsyncReducer('auth', authReducer);
/**
* @exports API
*/
provide({
login: data => {
server.load('userToken', {body: data})
.then(tokenData => {
store.dispatch({type: SET_TOKEN, payload: {token: tokenData.token}});
return server.load('userData', {token: tokenData.token});
})
.then(userData => {
store.dispatch({type: SET_USER_DATA, payload: {user: userData}});
})
.catch(err => {
console.error(err);
});
},
logout: () => {
store.dispatch({type: DESTROY});
},
isAuth: () => {
const state = store.getState();
if (state.auth && state.auth.user) {
return true;
}
return false;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment