import types from '../types' import { put } from '../api/crud.fetch' export const setToken = (data) => { return { type: types.auth.set_token, 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 authLoading() { 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(authLoading()) fetch(api.login, put({ username, password })) .then(req => req.json()) .then(data => { dispatch(setToken(data.token)) dispatch(checkin()) }) .catch(error => { dispatch(setError(true)) if (error.response.status === 400) { throw new InvalidCredentialsException(error) } throw error }) } } export function signup(data) { return (dispatch) => { dispatch(authLoading()) 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) if (error.response.status === 400) { // dispatch(accountError("There was an error creating your account.")) throw new InvalidCredentialsException(error) } throw error }) } } export function checkin() { return (dispatch) => { dispatch(authLoading()) fetch(api.checkin) .then(req => req.json()) .then(data => { console.log(data) dispatch(setCurrentUser(data)) console.log('set current user') }) .catch(error => { if (error.response.status === 400) { throw new InvalidCredentialsException(error) } throw error }) } }