Fakultas Ilmu Komputer UI

index.ts 4.56 KB
Newer Older
1
import { createContext, useCallback, useState } from 'react';
2
3
import { GoogleSignin } from '@react-native-google-signin/google-signin';

4
import Toast from 'react-native-toast-message';
5
6
import CACHE_KEYS from 'constants/cacheKeys';
import { removeCache, getCache, setCache } from 'utils/cache';
7
8
9
10
11
12
13
14

import {
  googleLoginApi,
  loginApi,
  signupApi,
  retrieveUserApi,
  linkUserDataApi,
} from 'services/auth';
15
16
17
18
import {
  RegistrationRequest,
  LoginRequest,
  LoginResponse,
19
  AuthUserResponse,
20
} from 'services/auth/models';
21
import { setAuthHeader, resetAuthHeader } from 'services/api';
22
23

import { iUserContext } from './types';
24
import { TransactionStatus } from 'services/payment/models';
25

26
export const initialUser = {
27
28
29
  id: null,
  email: '',
  name: '',
30
  role: null,
31
  transaction_status: null,
32
  is_finished_onboarding: false,
Wulan Mantiri's avatar
Wulan Mantiri committed
33
  cart_id: null,
Wulan Mantiri's avatar
Wulan Mantiri committed
34
  nutritionist: null,
35
  all_carts_are_expired: false,
36
37
};

38
39
40
41
export const UserContext = createContext<iUserContext>({
  user: initialUser,
  isAuthenticated: false,
  isLoading: false,
42
  isFirstLoading: false,
43
  setUser: (_: AuthUserResponse) => {},
44
  getUser: () => Promise.reject(),
45
46
47
48
49
50
51
  signup: () => Promise.reject(),
  login: () => Promise.reject(),
  loginWithGoogle: () => Promise.reject(),
  logout: () => Promise.reject(),
});

export const useUserContext = (): iUserContext => {
52
  const [user, setUser] = useState<AuthUserResponse>(initialUser);
53
  const [isLoading, setIsLoading] = useState(false);
54
55
56
57
58
59
60
  const [isFirstLoading, setIsFirstLoading] = useState(false);

  const logout = useCallback(async () => {
    await GoogleSignin.signOut();
    await removeCache(CACHE_KEYS.authToken);
    await removeCache(CACHE_KEYS.refreshToken);
    resetAuthHeader();
61
    setUser(initialUser);
62
  }, []);
63
64

  const getUser = useCallback(async () => {
65
    setIsFirstLoading(true);
66
67
68
    const token = await getCache(CACHE_KEYS.authToken);
    if (token) {
      setAuthHeader(token);
69
70
      const response = await retrieveUserApi();
      if (response.success && response.data) {
71
        setUser(response.data);
72
73
74
75
76
77
78
79
      } else {
        await logout();
        Toast.show({
          type: 'error',
          text1: 'Sesi Anda sudah berakhir.',
          text2: 'Silakan coba masuk lagi.',
        });
      }
80
    }
81
82
83
84
85
86
87
88
    setIsFirstLoading(false);
  }, [logout]);

  const authSuccess = async (data: LoginResponse) => {
    const accessToken = data.access_token;
    await setCache(CACHE_KEYS.authToken, accessToken);
    await setCache(CACHE_KEYS.refreshToken, data.refresh_token);
    setAuthHeader(accessToken);
89
    setUser(data.user);
90
91
  };

92
93
  // For signup, link user to cart and diet profile
  const linkUserData = async (data: LoginResponse) => {
94
95
    const dietProfileId = await getCache(CACHE_KEYS.dietProfileId);
    const cartId = await getCache(CACHE_KEYS.cartId);
96

97
98
    if (dietProfileId && cartId) {
      const response = await linkUserDataApi({
99
        email: data.user.email,
100
101
102
        diet_profile_id: parseInt(dietProfileId, 10),
        cart_id: parseInt(cartId, 10),
      });
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
      await authSuccess({
        ...data,
        user: {
          ...data.user,
          cart_id: response.data?.cart.id || null,
          transaction_status: TransactionStatus.UNPAID,
        },
      });
    } else {
      await logout();
      Toast.show({
        type: 'error',
        text1: 'Gagal registrasi akun',
        text2: 'Terjadi kesalahan di sisi kami. Silakan coba lagi',
      });
118
119
    }
  };
120

121
122
  const signup = async (registerData: RegistrationRequest) => {
    const response = await signupApi(registerData);
123
    if (response.success && response.data) {
124
      await linkUserData(response.data);
125
    }
126
127
    return response;
  };
128

129
130
  const login = async (loginData: LoginRequest) => {
    const response = await loginApi(loginData);
131
132
133
    if (response.success && response.data) {
      await authSuccess(response.data);
    }
134
135
    return response;
  };
136

137
  const loginWithGoogle = async (isLogin: boolean = true) => {
138
139
140
141
142
143
144
145
    try {
      await GoogleSignin.hasPlayServices();
      await GoogleSignin.signIn();
      const tokens = await GoogleSignin.getTokens();
      const response = await googleLoginApi({
        access_token: tokens.accessToken,
      });
      if (response.success && response.data) {
146
147
        const authProcess = isLogin ? authSuccess : linkUserData;
        await authProcess(response.data);
148
149
150
151
152
153
154
155
156
157
158
159
160
      } else {
        await logout();
      }
    } catch (error) {
      console.log(error);
    }
    setIsLoading(false);
  };

  return {
    user,
    isAuthenticated: user.id !== null,
    isLoading,
161
    isFirstLoading,
162
    setUser,
163
    getUser,
164
165
166
167
168
169
    signup,
    login,
    loginWithGoogle,
    logout,
  };
};