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'
- 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 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
- })
- }
- }
- export {
- AUTH_LOADING, AUTH_SUCCESS, AUTH_FAILURE,
- signIn, signUp, checkToken
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement