Advertisement
Guest User

Untitled

a guest
Nov 9th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import api from './../helpers/api'
  2. import {addNotification} from './notifications'
  3. import cookie from 'react-cookie'
  4. import {push} from 'redux-router'
  5.  
  6. const AUTH_SUCCESS = 'auth/signin/success'
  7. const AUTH_LOADING = 'auth/signin/loading'
  8. const AUTH_FAILURE = 'auth/signin/failure'
  9.  
  10. function signIn(email, password, redirect = '/') {
  11. return (dispatch, getState, api) => {
  12. api.post('/user/signin', {
  13. email: email,
  14. password: password
  15. })
  16. .then(data => data.data)
  17. .then(data => {
  18. dispatch(authSuccess(data))
  19. dispatch(push(redirect))
  20. },
  21. error => {
  22. if(error.data && error.data.message) {
  23. dispatch(authFailure(error.data.message))
  24. }else{
  25. dispatch(authFailure(error.data))
  26. }
  27. })
  28. }
  29. }
  30.  
  31. function signUp(d, redirect = '/') {
  32. console.log(d)
  33. return (dispatch, getState, api) => {
  34. api.post('/user/signup', d)
  35. .then(data => data.data)
  36. .then(data => {
  37. console.log(data)
  38. dispatch(addNotification('success', 'You successfully registered'))
  39. dispatch(authSuccess(data))
  40. dispatch(push(redirect))
  41. },
  42. error => {
  43. if(error.data && error.data.message) {
  44. dispatch(authFailure(error.data.message))
  45. }else{
  46. dispatch(authFailure(error.data))
  47. }
  48. })
  49. }
  50. }
  51.  
  52. function checkToken(token) {
  53. return (dispatch, getState, api) => {
  54. api.get(`/user/check?token=${token}`)
  55. .then(data => data.data)
  56. .then(data => {
  57. dispatch(authSuccess(data, token))
  58. })
  59. .catch(error => {
  60. if(error.data && error.data.message) {
  61. dispatch(authFailure(error.data.message))
  62. }else{
  63. dispatch(authFailure(error.data))
  64. }
  65. })
  66. }
  67. }
  68.  
  69. function authSuccess(data, token = data.token) {
  70. localStorage.setItem('token', token)
  71. return dispatch => {
  72. dispatch(addNotification('success', `Welcome back, ${data.username}`))
  73. dispatch({
  74. type: AUTH_SUCCESS,
  75. user: data.user,
  76. token: token
  77. })
  78. }
  79. }
  80.  
  81. function authFailure(error) {
  82. localStorage.removeItem('token')
  83. return dispatch => {
  84. dispatch(addNotification('danger', `Error: ${error}`))
  85. dispatch({
  86. type: AUTH_FAILURE,
  87. error: error
  88. })
  89. }
  90. }
  91.  
  92.  
  93. export {
  94. AUTH_LOADING, AUTH_SUCCESS, AUTH_FAILURE,
  95. signIn, signUp, checkToken
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement