Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import api from './../helpers/api'
- import {addNotification} from './notifications'
- import cookie from 'react-cookie'
- import {push} from 'redux-router'
- const AUTH_SUCCESS = 'auth/signin/success'
- const AUTH_LOADING = 'auth/signin/loading'
- const AUTH_FAILURE = 'auth/signin/failure'
- const LOGOUT = 'auth/logout'
- const UPDATE_USER_INFORMATION = 'user/update/information'
- function signIn(email, password, redirect = '/') {
- return (dispatch, getState, api) => {
- api.post('/user/signin', {
- email: email,
- password: password
- })
- .then(data => data.data)
- .then(data => {
- dispatch(authSuccess(data))
- dispatch(push(redirect))
- },
- error => {
- if(error.data && error.data.message) {
- dispatch(authFailure(error.data.message))
- }else{
- dispatch(authFailure(error.data))
- }
- })
- }
- }
- function signUp(d, redirect = '/') {
- console.log(d)
- return (dispatch, getState, api) => {
- api.post('/user/signup', d)
- .then(data => data.data)
- .then(data => {
- console.log(data)
- dispatch(addNotification('success', 'You successfully registered'))
- dispatch(authSuccess(data))
- dispatch(push(redirect))
- },
- error => {
- if(error.data && error.data.message) {
- dispatch(authFailure(error.data.message))
- }else{
- dispatch(authFailure(error.data))
- }
- })
- }
- }
- function checkToken(token) {
- return (dispatch, getState, api) => {
- api.get(`/user/check?token=${token}`)
- .then(data => data.data)
- .then(data => {
- dispatch(authSuccess(data, token))
- })
- .catch(error => {
- if(error.data && error.data.message) {
- dispatch(authFailure(error.data.message))
- }else{
- dispatch(authFailure(error.data))
- }
- })
- }
- }
- function logout() {
- localStorage.removeItem('token');
- return (dispatch, getState) => {
- let state = getState()
- console.log(state.user)
- dispatch(addNotification('success', `Good bye, ${state.user.user.username}`))
- dispatch({type: LOGOUT, logout: true})
- }
- }
- function authSuccess(data, token = data.token) {
- localStorage.setItem('token', token)
- return dispatch => {
- dispatch(addNotification('success', `Welcome back, ${data.username}`))
- dispatch({
- type: AUTH_SUCCESS,
- user: data.user,
- token: token
- })
- }
- }
- function authFailure(error) {
- localStorage.removeItem('token')
- return dispatch => {
- dispatch(addNotification('danger', `Error: ${error}`))
- dispatch({
- type: AUTH_FAILURE,
- error: error
- })
- }
- }
- function updateUserInformation(data) {
- return dispatch => {
- dispatch({
- type: UPDATE_USER_INFORMATION
- })
- }
- }
- export {
- AUTH_LOADING, AUTH_SUCCESS, AUTH_FAILURE, LOGOUT,
- UPDATE_USER_INFORMATION,
- signIn, signUp, checkToken, logout,
- updateUserInformation
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement