Added logic to auto fetch Google Access Token and Refresh Token for EmailScreen

This commit is contained in:
2024-08-10 23:24:04 +08:00
parent 5f974c8d71
commit 9972de364f

View File

@@ -3,10 +3,8 @@ import { View, Text, TouchableOpacity, FlatList, StyleSheet, ActivityIndicator,
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import { getEmails, getScannedEmails, getUserInfo } from '../api/qrCodeAPI'; import { getEmails, getScannedEmails, getUserInfo } from '../api/qrCodeAPI';
import { useAuthenticator } from '@aws-amplify/ui-react-native'; import { fetchAuthSession } from 'aws-amplify/auth';
import useFetchUserAttributes from '../hooks/useFetchUserAttributes'; import { Buffer } from 'buffer';
import { fetchAuthSession, getCurrentUser, signInWithRedirect } from 'aws-amplify/auth';
const { width: screenWidth, height: screenHeight } = Dimensions.get('window'); const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
@@ -18,8 +16,6 @@ const EmailScreen: React.FC = () => {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [userEmail, setUserEmail] = useState(''); const [userEmail, setUserEmail] = useState('');
const [bannerOpacity] = useState(new Animated.Value(0)); const [bannerOpacity] = useState(new Animated.Value(0));
const [googleAccessToken, setGoogleAccessToken] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
startPollingForScannedEmails(); startPollingForScannedEmails();
@@ -42,13 +38,29 @@ const EmailScreen: React.FC = () => {
const initiateEmailFetch = async () => { const initiateEmailFetch = async () => {
setRescanLoading(true); setRescanLoading(true);
showBanner(); showBanner();
try { try {
// Call to start email fetching process // Fetch the current authentication session
const response = await getEmails( const { tokens } = await fetchAuthSession();
'Google Access Token', const idToken = tokens.idToken.toString();
'Refresh Token'
); const parts = idToken.split('.');
const payload = parts[1];
const decodedPayload = Buffer.from(payload, 'base64').toString('utf8');
const parsedPayload = JSON.parse(decodedPayload);
const googleAccessToken = parsedPayload["custom:access_token"];
const googleRefreshToken = parsedPayload["custom:refresh_token"];
if (googleAccessToken && googleRefreshToken) {
// Use the fetched tokens to initiate email fetching
const response = await getEmails(googleAccessToken, googleRefreshToken);
setRescanLoading(false); setRescanLoading(false);
} else {
console.error('Google access token or refresh token not found in the payload');
setError('Google access token or refresh token missing.');
setRescanLoading(false);
}
} catch (error) { } catch (error) {
console.error('Error initiating email fetch:', error); console.error('Error initiating email fetch:', error);
setError('Error rescanning inbox.'); setError('Error rescanning inbox.');