-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.js
78 lines (64 loc) · 1.51 KB
/
session.js
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
import { supabase } from "../supabaseclient";
// constants
const SET_USER = "session/SET_USER";
const REMOVE_USER = "session/REMOVE_USER";
export const setUser = (user) => ({
type: SET_USER,
payload: user,
});
const removeUser = () => ({
type: REMOVE_USER,
});
const initialState = { user: null };
export const authenticate = () => async (dispatch) => {
const response = await fetch("/api/auth/", {
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
const data = await response.json();
if (data.errors) {
return;
}
dispatch(setUser(data));
}
};
export const login = (email, password) => async (dispatch) => {
const response = await supabase.auth.signInWithPassword({
email: email,
password: password,
options: {
redirectTo: 'https//example.com/welcome'
}
})
console.log('RESPONSE', response)
if (response.data.user) {
const data = response.data
localStorage.setItem('user', data.user)
dispatch(setUser(data));
return data;
} else if (response.error) {
const data = response.error
console.log(data)
return data.errors;
} else {
return ["An error occurred. Please try again."];
}
};
export const logout = () => async (dispatch) => {
const response = await supabase.auth.signOut()
if (!response.error) {
dispatch(removeUser());
}
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case SET_USER:
return { user: action.payload };
case REMOVE_USER:
return { user: null };
default:
return state;
}
}