Using Google OAuth without Firebase(Expo)-Login

전채원·2022년 7월 1일
0

expo

목록 보기
2/2

feat. AsyncStorage

My environment
MacBook Air M1
RAM: 16GB
SSD: 500GB
Phone: Samsung Z flip 3, Samsung Note 10

If you don’t know how to build Expo project? See this first

Make your Project in Google Cloud Platform

Google Cloud Platform

  1. Move to Console

  2. Create your project and move to your project

    Watch Video

  1. Set OAuth consent screen

  2. Move to Credentials and create Credentials

    1. Select Web Application(Expo Client ID)

      1. Create and copy your Client ID (should not show your Client ID to others

      2. Add “https://auth.expo.io” to **Authorized JavaScript origins**

      3. Add "http://auth.expo.io/@your-expo-userId/projectname" to Redirect URL

        Watch Video

    2. Select Android

      1. Set package name to “host.exp.exponent”

      2. Get SHA-1 key from terminal

        expo fetch:android:hashes
      3. Create

    3. Select Ios

      1. set Bundle Id to “host.exp.exponent”
      2. create
    4. Select Web Application

      1. Add “https://localhost:19006” to **Authorized JavaScript origins** and **Redirect URL**
  3. Move to your project folder open on VS code

  4. Open terminal on your project location

  5. Install expo-auth-session

Reference: AuthSession

expo install expo-auth-session expo-random

※ Caution ※

There are some issues on Auth library.

expo-auth-session is work well before standalone your application, but after standalone this doesn’t work well.

So, forum said use use expo-google-sign-in after your app standalone.

  1. Open app.json file and add code below
{
  "expo": {
    "scheme": "your_project_name"
  }
}

→ This will remove Linking warning

Login

  1. Open App.js file or other screen file where you want to use login function and copy paste code below
    1. This code includes uses of AsyncStorage(save data on your local DB)
      1. Try clone a new project from your Github when AsyncStorage doesn’t work
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

WebBrowser.maybeCompleteAuthSession();   //This will close your web browser after login

//paste ClientId which you copy from above
export default function App() {
	const [gUser, setGUser] = useState('');
  const [reqError, setReqError] = useState('');
  const [isLoding,setIsLoding]=useState(false);  

  const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
    webClientId: 'GOOGLE_GUID.apps.googleusercontent.com', 
		scopes: ['profile', 'email'],
  });

  useEffect(() => {
        if (response?.type === 'success') {
            const { authentication } = response;

            getGoogleUser(authentication.accessToken)
            giveGoogleUser(authentication.accessToken)
            
        }
    }, [response]);
   
    //Request user information to Google API
    const getGoogleUser = async (accessToken) => {
        try{
            let gUserReq =await axios.get('https://www.googleapis.com/oauth2/v2/userinfo',
                {
                    headers: {
                        Authorization: `Bearer ${accessToken}`
                    }
                }
            )
            
            console.log(gUserReq.data);
            setGUser(gUserReq.data);
            
        }
        catch(error){
            console.log('GoogleUserReq error: ', error.response.data);
            setReqError(error.response.data);
        }
        
    }

 
const giveGoogleUser = async (accessToken) => {
        const giveUser = await axios.post('your-backDB-apiURL', {
					//you can edit Data sturcture
          "accessToken": accessToken,
          "userInfo": {
            "id": JSON.stringify(gUser.id),
            "email": JSON.stringify(gUser.email),
            "verified_email": JSON.stringify(gUser.verified_email),
            "name": JSON.stringify(gUser.name),
            "given_name": JSON.stringify(gUser.given_name),
            "family_name": JSON.stringify(gUser.family_name),
            "picture": JSON.stringify(gUser.picture),
            "locale": JSON.stringify(gUser.locale),
            "hd": JSON.stringify(gUser.hd)
          }
        }).then(response=>{
              console.log(response.status); //To check
              storageData(); //storageData to local DB
            } 
          )
        .catch(console.error)
        .finally(()=>setIsLoding(false));
    }

storageData=async()=>{
      await AsyncStorage.setItem(
        'User',
        JSON.stringify({
          id: gUser.id,
          email: gUser.email,
          picture: gUser.picture,
        }),
        () => {
          console.log('User Info Saved!');
        })
    }

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync();
        }}
    />
  );
}

Now you can use Google Login function in your Expo project!!

0개의 댓글