| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import AsyncStorage from "@react-native-async-storage/async-storage";
- import * as Google from "expo-auth-session/providers/google";
- import React, { createContext, useEffect, useState } from "react";
- import { googleApi, loginApi, registerApi } from "../service/user";
-
- export const AuthContext = createContext();
-
- export const AuthProvider = ({ children }) => {
- const [userInfo, setUserInfo] = useState({});
- const [isLoading, setIsLoading] = useState(false);
-
- // Google Auth
- const [request, response, promptAsync] = Google.useAuthRequest({
- androidClientId:
- "1032296921439-dpgvgkss3ggds0egvo6puf0r7un9em6c.apps.googleusercontent.com",
- iosClientId:
- "1032296921439-j7jfahhm7q3l07aj04qvdblmcns77oul.apps.googleusercontent.com",
- expoClientId:
- "1032296921439-vfs9k28sn7kei4nft998ck3067m8ksiq.apps.googleusercontent.com",
- });
-
- useEffect(() => {
- if (response?.type === "success") {
- googleApi(response.authentication.accessToken)
- .then((res) => {
- if (res.user) {
- setUserInfo(res);
- AsyncStorage.setItem("userInfo", JSON.stringify(res));
- setIsLoading(false);
- } else {
- callback(res);
- setIsLoading(false);
- }
- })
- .catch((e) => {
- console.log("error", e);
- setIsLoading(false);
- });
- }
- }, [response]);
-
- const login = (email, password, callback) => {
- setIsLoading(true);
- loginApi({ identifier: email, password })
- .then((res) => {
- if (res.user) {
- setUserInfo(res);
- AsyncStorage.setItem("userInfo", JSON.stringify(res));
- setIsLoading(false);
- } else {
- callback(res);
- setIsLoading(false);
- }
- })
- .catch((e) => {
- console.log("error", e);
- setIsLoading(false);
- });
- };
-
- const googleAuth = () => {
- promptAsync({ useProxy: false, showInRecents: true });
- };
-
- const register = (username, email, password, callback) => {
- setIsLoading(true);
- registerApi({ username, email, password })
- .then((res) => {
- if (res.user) {
- setUserInfo(res);
- AsyncStorage.setItem("userInfo", JSON.stringify(res));
- setIsLoading(false);
- } else {
- callback(res);
- setIsLoading(false);
- }
- })
- .catch((e) => {
- console.log("error", e);
- setIsLoading(false);
- });
- };
-
- const logout = () => {
- setIsLoading(true);
- AsyncStorage.removeItem("userInfo");
- setUserInfo({});
- setIsLoading(false);
- };
-
- const isLoggedIn = async () => {
- try {
- let userInfo = await AsyncStorage.getItem("userInfo");
- userInfo = JSON.parse(userInfo);
-
- if (userInfo) {
- setUserInfo(userInfo);
- }
- } catch (e) {
- console.log(e);
- }
- };
-
- useEffect(() => {
- isLoggedIn();
- }, []);
-
- return (
- <AuthContext.Provider
- value={{ isLoading, login, logout, userInfo, register, googleAuth }}
- >
- {children}
- </AuthContext.Provider>
- );
- };
|