Advertisement
spaceofmiah

React Auth component with Firebase Phone Auth

Jan 21st, 2022
832
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import { Redirect, useHistory } from 'react-router';
  3. import { useDispatch, useSelector } from 'react-redux';
  4.  
  5. import {
  6.     getAuth,
  7.     RecaptchaVerifier,
  8.     signInWithPhoneNumber
  9. } from "firebase/auth";
  10. import app from '../../../firebaseSetup';
  11. import { API_BASE_URL, ROUTES } from '../../../constants';
  12. import { setAuthenticatedAccountAction } from '../actions';
  13. import { selectCartMerchant } from '../selectors';
  14.  
  15.  
  16.  
  17. const UserAuth = () => {
  18.     const history = useHistory();
  19.     const dispatch = useDispatch();
  20.  
  21.     const cartMerchant = useSelector(selectCartMerchant);
  22.     const redirectURL = `${ROUTES['merchants']}/${cartMerchant.slug}` || ROUTES['merchants']
  23.  
  24.     const auth = getAuth(app);
  25.  
  26.     const authenticate = (token, phoneNumber) => {
  27.         const data = {'fb_token': token, 'phone': phoneNumber};
  28.         const url = `${API_BASE_URL}/accounts/token/`;
  29.  
  30.         fetch(url, {
  31.             method: "POST",
  32.             body: JSON.stringify(data),
  33.             headers: {'content-type': 'application/json'}
  34.         })
  35.         .then(res => res.json())
  36.         .then(data => {
  37.             dispatch(setAuthenticatedAccountAction(data.user))
  38.             localStorage.setItem('u_t', data.access);
  39.             localStorage.setItem('u_id', JSON.stringify(data.user));
  40.             history.push(redirectURL)
  41.         })
  42.         .catch(err => console.log(err))
  43.     }
  44.  
  45.     const configureRecaptcha = () => {
  46.         window.recaptchaVerifier = new RecaptchaVerifier(
  47.             'recaptcha-container',
  48.             {
  49.                 'size': 'invisible',
  50.                 'callback': (response) => {
  51.                     onSignInSubmit();
  52.                 }
  53.             },
  54.             auth
  55.         );
  56.     }
  57.  
  58.     const onSignInSubmit = ( event ) => {
  59.         event.preventDefault();
  60.         configureRecaptcha();
  61.  
  62.         const phoneNumber = event.target.phone.value;
  63.         const appVerifier = window.recaptchaVerifier;
  64.  
  65.         signInWithPhoneNumber(auth, phoneNumber, appVerifier)
  66.         .then((confirmationResult) => {
  67.             window.confirmationResult = confirmationResult;
  68.  
  69.             const code = window.prompt("Enter your OTP");
  70.             confirmationResult.confirm(code).then((result) => {
  71.                 const user = result.user;
  72.                 // Login to the server with the generated accessToken
  73.                 authenticate(user.accessToken, user.phoneNumber)
  74.             }).catch((error) => {
  75.                 // window.recaptchaVerifier.render().then(function(widgetId) {
  76.                 //     grecaptcha.reset(widgetId);
  77.                 // })
  78.             });
  79.         })
  80.         .catch((error) => {
  81.             // window.recaptchaVerifier.render().then(function(widgetId) {
  82.             //     grecaptcha.reset(window.recaptchaWidgetId);
  83.             // })
  84.         });
  85.     }
  86.  
  87.  
  88.     return <div className="items-center flex m-2 flex-col mt-20">
  89.         <div className="w-full md:w-5/12 shadow-md p-10 rounded-md">
  90.             <h1 className="font-extrabold">Authenticate</h1>
  91.  
  92.             <form className="flex mt-8 flex-col gap-2" onSubmit={onSignInSubmit}>
  93.                 <div id="recaptcha-container"></div>
  94.                 <small>Enter your phone number to authenticate</small>
  95.                 <div className="flex flex-col sm:flex-row justify-between gap-2 items-center">
  96.                     <input type="text" placeholder="phone number" className="
  97.                        bg-gray-100 p-2 rounded-sm text-black outline-none
  98.                        focus:bg-gray-200 w-full
  99.                        " name="phone"
  100.                     />
  101.                 </div>
  102.  
  103.                 <div className="text-center mt-3">
  104.                     <input type="submit" className="
  105.                        p-2 w-40 cursor-pointer
  106.                        bg-red-500 rounded-md
  107.                        text-white hover:bg-red-600"  
  108.                         value="Authenticate"
  109.                     />
  110.                 </div>
  111.             </form>
  112.         </div>
  113.     </div>
  114. }
  115.  
  116. export default UserAuth;
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement