Fakultas Ilmu Komputer UI

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

import { Toast } from 'components/core';
import CACHE_KEYS from 'constants/cacheKeys';
import { removeCache, getCache, setCache } from 'utils/cache';
7
8
import { googleLoginApi, signupApi } from 'services/auth';
import { User, RegistrationRequest } from 'services/auth/models';
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
import { set401Callback, setAuthHeader, resetAuthHeader } from 'services/api';

import { iUserContext } from './types';

const initialUser = {
  id: null,
  email: '',
  name: '',
};

export const UserContext = createContext<iUserContext>({
  user: initialUser,
  isAuthenticated: false,
  isLoading: false,
  signup: () => Promise.reject(),
  login: () => Promise.reject(),
  loginWithGoogle: () => Promise.reject(),
  logout: () => Promise.reject(),
});

export const useUserContext = (): iUserContext => {
  const [user, setUser] = useState<User>(initialUser);
  const [isLoading, setIsLoading] = useState(false);

  const getUser = useCallback(async () => {
    const token = await getCache(CACHE_KEYS.authToken);
    if (token) {
      setAuthHeader(token);
      // TODO: fetch user data
    }
  }, []);

41
42
43
44
45
46
47
48
49
50
51
52
  const signup = async (registerData: RegistrationRequest) => {
    const response = await signupApi(registerData);

    if (response.success && response.data) {
      await setCache(CACHE_KEYS.authToken, response.data?.access_token);
      await setCache(CACHE_KEYS.refreshToken, response.data?.refresh_token);

      setUser(response.data.user);
    }

    return response;
  };
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

  // TODO
  const login = async () => {};

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

  const loginWithGoogle = async () => {
    setIsLoading(true);
    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) {
        await setCache(CACHE_KEYS.authToken, response.data.access_token);
        await setCache(CACHE_KEYS.authToken, response.data.access_token);
        setUser(response.data.user);
      } else {
        await logout();
        Toast.show({
          type: 'error',
          text1: 'Sesi Anda sudah berakhir.',
          text2: 'Silakan coba masuk lagi.',
        });
      }
    } catch (error) {
      console.log(error);
    }
    setIsLoading(false);
  };

  useEffect(() => {
    // TODO: save to .env
    GoogleSignin.configure({
      webClientId:
        '813112248680-ulv0amtocut652j31qbpvubtclbd2c7o.apps.googleusercontent.com',
    });

    getUser();
    set401Callback(logout);
  }, [getUser, logout]);

  return {
    user,
    isAuthenticated: user.id !== null,
    isLoading,
    signup,
    login,
    loginWithGoogle,
    logout,
  };
};