Fakultas Ilmu Komputer UI

index.ts 4.52 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
24

import { iUserContext } from './types';

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

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

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

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

  const getUser = useCallback(async () => {
64
    setIsFirstLoading(true);
65
66
67
    const token = await getCache(CACHE_KEYS.authToken);
    if (token) {
      setAuthHeader(token);
68
69
      const response = await retrieveUserApi();
      if (response.success && response.data) {
70
        setUser(response.data);
71
72
73
74
75
76
77
78
      } else {
        await logout();
        Toast.show({
          type: 'error',
          text1: 'Sesi Anda sudah berakhir.',
          text2: 'Silakan coba masuk lagi.',
        });
      }
79
    }
80
81
82
83
84
85
86
87
    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);
88
    setUser(data.user);
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  };

  const linkUserData = async (email: string) => {
    const dietProfileId = await getCache(CACHE_KEYS.dietProfileId);
    const cartId = await getCache(CACHE_KEYS.cartId);
    if (dietProfileId && cartId) {
      const response = await linkUserDataApi({
        email,
        diet_profile_id: parseInt(dietProfileId, 10),
        cart_id: parseInt(cartId, 10),
      });
      return response;
    }
    return {
      success: false,
    };
  };
106

107
108
  const signup = async (registerData: RegistrationRequest) => {
    const response = await signupApi(registerData);
109
    if (response.success && response.data) {
110
      await linkUserData(response.data.user.email);
111
112
      await authSuccess(response.data);
    }
113
114
    return response;
  };
115

116
117
  const login = async (loginData: LoginRequest) => {
    const response = await loginApi(loginData);
118
119
120
    if (response.success && response.data) {
      await authSuccess(response.data);
    }
121
122
    return response;
  };
123

124
  const loginWithGoogle = async (isLogin: boolean = true) => {
125
126
127
128
129
130
131
132
    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) {
133
        // If signup, link user to cart and diet profile
134
135
136
137
138
139
140
141
142
143
        if (!isLogin) {
          const linkResponse = await linkUserData(response.data.user.email);
          if (!linkResponse.success) {
            await logout();
            Toast.show({
              type: 'error',
              text1: 'Gagal registrasi dengan Google',
              text2: 'Terjadi kesalahan di sisi kami. Silakan coba lagi',
            });
          }
144
        }
145
146

        await authSuccess(response.data);
147
148
149
150
151
152
153
154
155
156
157
158
159
      } else {
        await logout();
      }
    } catch (error) {
      console.log(error);
    }
    setIsLoading(false);
  };

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