summaryrefslogtreecommitdiff
path: root/app/client/auth/auth.actions.js
blob: 31719964a7528f3fee86038d12f3a3bf92307ee2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import types from '../types'
import { put } from '../api/crud.fetch'

export const setToken = (data) => {
  return { type: types.auth.set_token, data }
}
export const setReturnTo = (data) => {
  return { type: types.auth.set_return_to, data }
}
export const setError = (data) => {
  return { type: types.auth.set_error, data }
}
export const setCurrentUser = (data) => {
  return { type: types.auth.set_current_user, data }
}
export function logout() {
  return { type: types.auth.logout_user }
}
export function initialized() {
  return { type: types.auth.initialized }
}
export function loading() {
  return { type: types.auth.loading }
}

export function InvalidCredentialsException(message) {
  this.message = message
  this.name = 'InvalidCredentialsException'
}

const api = {
  login: '/api/login',
  logout: '/api/logout',
  signup: '/api/signup',
  checkin: '/api/checkin',
}

export function login(username, password) {
  return (dispatch) => {
    dispatch(loading())
    fetch(api.login, put({
      username,
      password
    }))
    .then(req => req.json())
    .then(data => {
      console.log(data)
      dispatch(setToken(data.token))
      dispatch(checkin())
    })
    .catch(error => {
      console.log(error)
      dispatch(setError(true))
    })
  }
}

export function signup(data) {
  return (dispatch) => {
    dispatch(loading())
    fetch(api.signup, put(data))
    .then(req => req.json())
    .then(data => {
      console.log(data)
      dispatch(login(data.username, data.password))
    })
    .catch(error => {
      console.log(error)
      dispatch(initialized())
    })
  }
}

export function checkin(history) {
  return (dispatch) => {
    dispatch(loading())
    fetch(api.checkin, put({}))
    .then(req => req.json())
    .then(data => {
      console.log(data)
      dispatch(setCurrentUser(data))
      console.log('set current user')
    })
    .catch(error => {
      console.log(error)
      // history.go('/login')
      dispatch(initialized(true))
    })
  }
}