client/src/reducers/authReducer.js
author Alexandre Segura <mex.zktk@gmail.com>
Mon, 26 Jun 2017 16:48:52 +0200
changeset 91 143ff08ec2cc
parent 90 990f2c928b15
child 100 6fd752d98933
permissions -rw-r--r--
DRY

import Immutable from 'immutable';
import * as types from '../constants/actionTypes';
import UserRecord from '../store/userRecord';
import asyncRequest from '../constants/asyncRequest';

export const isAuthenticated = (state = false, action) => {
  switch (action.type) {
    case types.AUTH_DEAUTHENTICATE:
    case types.AUTH_LOGOUT:
      return false;
    case types.AUTH_LOGIN_SUCCESS:
      return true;
    default:
      return state;
  }
}

export const currentUser = (state = null, action) => {
  switch (action.type) {
    case types.AUTH_DEAUTHENTICATE:
    case types.AUTH_LOGOUT:
      return null;
    case types.AUTH_LOGIN_SUCCESS:
      return new UserRecord(action.user);
    case types.USER_UPDATE_SETTINGS:
      return state.merge({
        first_name: action.firstname,
        last_name: action.lastname
      });
    default:
      return state;
  }
}

export const token = (state = null, action) => {
  switch (action.type) {
    case types.AUTH_DEAUTHENTICATE:
    case types.AUTH_LOGOUT:
      return null;
    case types.AUTH_STORE_TOKEN:
      return action.token;
    default:
      return state;
  }
}

export const login = (state = asyncRequest, action) => {
  switch (action.type) {
    case types.AUTH_LOGIN_REQUEST:
      return Immutable.Map({
        loading: true,
        success: false,
        error: false,
      })
    case types.AUTH_LOGIN_SUCCESS:
    case types.AUTH_LOGIN_ERROR:
      return Immutable.Map({
        loading: false,
        success: action.type === types.AUTH_LOGIN_SUCCESS,
        error: action.type === types.AUTH_LOGIN_ERROR,
        errorMessages: action.type === types.AUTH_LOGIN_ERROR ? Immutable.Map(action.error) : Immutable.Map({})
      })
    default:
      return state
  }
}

export const register = (state = asyncRequest, action) => {
  switch (action.type) {
    case types.AUTH_REGISTER_REQUEST:
      return Immutable.Map({
        loading: true,
        success: false,
        error: false,
      })
    case types.AUTH_LOGIN_SUCCESS:
    case types.AUTH_REGISTER_ERROR:
      return Immutable.Map({
        loading: false,
        success: action.type === types.AUTH_LOGIN_SUCCESS,
        error: action.type === types.AUTH_REGISTER_ERROR,
        errorMessages: action.type === types.AUTH_REGISTER_ERROR ? Immutable.Map(action.error) : Immutable.Map({})
      })
    default:
      return state
  }
}