Recommit, without build falire (native_modules.gradle' line: 401, finished with non-zero exit value 1)

This commit is contained in:
2024-08-03 23:07:41 +08:00
parent 804eb6f024
commit 7f7f686ef8
6 changed files with 404 additions and 337 deletions

View File

@@ -1,2 +1,2 @@
NODE_ENV=development NODE_ENV=development
BASE_URL=http://192.168.1.30:8080 BASE_URL=http://192.168.10.247:8080

View File

@@ -2,18 +2,22 @@ import axios from 'axios';
import Constants from 'expo-constants'; import Constants from 'expo-constants';
const { API_BASE_URL, ENVIRONMENT } = Constants.expoConfig.extra; const { API_BASE_URL, ENVIRONMENT } = Constants.expoConfig.extra;
import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth'; import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth';
//const API_BASE_URL = 'https://localhost:8443';
const API_URL_DETECT = "/v1/qrcodetypes/detect";
const API_URL_VERIFY_URL = "/v1/qrcodetypes/verifyURL" const API_URL_SCAN = "/v1/qrcodetypes/scan";
const API_URL_VIRUS_TOTAL_CHECK = "/v1/qrcodetypes/virusTotalCheck" const API_URL_GET_QR_DETAILS = "/v1/qrcodetypes/getQRDetails";
const API_URL_CHECK_REDIRECTS = "/v1/qrcodetypes/checkRedirects"
const API_URL_GET_HISTORIES = "/v1/user/getScannedHistories"
const API_URL_DELETE_SCANNED_HISTORY = "/v1/user/deleteScannedHistories" const API_URL_GET_HISTORIES = "/v1/user/getScannedHistories";
const API_URL_GET_BOOKMARKS = "/v1/user/getBookmarks" const API_URL_DELETE_SCANNED_HISTORY = "/v1/user/deleteScannedHistories";
const API_URL_SET_BOOKMARK = "/v1/user/setBookmark" const API_URL_DELETE_ALL_HISTORIES = "/v1/user/deleteAllScannedHistories";
const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark" const API_URL_GET_BOOKMARKS = "/v1/user/getBookmarks";
const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails" const API_URL_SET_BOOKMARK = "/v1/user/setBookmark";
const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark";
const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails";
const API_URL_GET_USER = "/v1/user/getUser"; // New endpoint
// Create an Axios instance // Create an Axios instance
const apiClient = axios.create({ const apiClient = axios.create({
@@ -36,6 +40,9 @@ apiClient.interceptors.request.use(
} }
} }
// Log the X-USER-ID header
console.log('X-USER-ID:', config.headers['X-USER-ID']);
return config; return config;
}, },
(error) => { (error) => {
@@ -47,22 +54,17 @@ apiClient.interceptors.request.use(
export const apiRequest = async (config) => { export const apiRequest = async (config) => {
try { try {
console.log("ENVIRONMENT:", ENVIRONMENT); console.log("ENVIRONMENT:", ENVIRONMENT);
console.log(`API Call - ${config.method.toUpperCase()}:`, config.url, config.data || ''); console.log(`API Call - ${config.method.toUpperCase()}:`, config.url, config.data || '');
console.log(config); console.log(config);
const response = await apiClient(config); const response = await apiClient(config);
console.log('API Response:', response.data); console.log('API Response:', response.data);
return response.data; return response.data;
} catch (error) { } catch (error) {
if (error.response) { if (error.response) {
// The request was made and the server responded with a status code that falls out of the range of 2xx
console.error('API Error - Response:', error.response.data); console.error('API Error - Response:', error.response.data);
} else if (error.request) { } else if (error.request) {
// The request was made but no response was received
console.error('API Error - No Response:', error.request); console.error('API Error - No Response:', error.request);
} else { } else {
// Something happened in setting up the request that triggered an Error
console.error('API Error - General:', error.message); console.error('API Error - General:', error.message);
} }
throw error; throw error;
@@ -81,37 +83,29 @@ const fetchUserId = async () => {
return currentUser.userId; return currentUser.userId;
}; };
export const detectQRCodeType = async (data) => { // Function to handle /scan request
export const scanQRCode = async (data) => {
return apiRequest({ return apiRequest({
method: 'post', method: 'post',
url: `${API_BASE_URL}${API_URL_DETECT}`, url: `${API_BASE_URL}${API_URL_SCAN}`,
data: { data } data: { data }
}); });
}; };
export const verifyURL = async (data) => { // Function to get QR code details
export const getQRCodeDetails = async (qrCodeId: string) => {
return apiRequest({ return apiRequest({
method: 'post', method: 'get',
url: `${API_BASE_URL}${API_URL_VERIFY_URL}`, url: `${API_BASE_URL}${API_URL_GET_QR_DETAILS}`,
data: { data } headers: { 'QR-ID': qrCodeId },
}); });
}; };
export const virusTotalCheck = async (data) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_VIRUS_TOTAL_CHECK}`,
data: { data }
});
};
export const checkRedirects = async (data) => {
return apiRequest({
method: 'post', //-----------
url: `${API_BASE_URL}${API_URL_CHECK_REDIRECTS}`,
data: { data }
});
};
// GET User's Scanned Histories // GET User's Scanned Histories
export const getScannedHistories = async () => { export const getScannedHistories = async () => {
return apiRequest({ return apiRequest({
@@ -119,7 +113,8 @@ export const getScannedHistories = async () => {
url: `${API_BASE_URL}${API_URL_GET_HISTORIES}` url: `${API_BASE_URL}${API_URL_GET_HISTORIES}`
}); });
}; };
// GET All User's Bookmark
// GET All User's Bookmarks
export const getAllUserBookmarks = async () => { export const getAllUserBookmarks = async () => {
return apiRequest({ return apiRequest({
method: 'get', method: 'get',
@@ -132,7 +127,7 @@ export const setBookmark = async (qrCodeId: string) => {
return apiRequest({ return apiRequest({
method: 'post', method: 'post',
url: `${API_BASE_URL}${API_URL_SET_BOOKMARK}`, url: `${API_BASE_URL}${API_URL_SET_BOOKMARK}`,
data: { "qrCodeId": qrCodeId } data: { qrCodeId }
}); });
}; };
@@ -141,7 +136,7 @@ export const deleteBookmark = async (qrCodeId: string) => {
return apiRequest({ return apiRequest({
method: 'put', method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_BOOKMARK}`, url: `${API_BASE_URL}${API_URL_DELETE_BOOKMARK}`,
data: { "qrCodeId": qrCodeId } data: { qrCodeId }
}); });
}; };
@@ -150,7 +145,15 @@ export const deleteScannedHistory = async (qrCodeId: string) => {
return apiRequest({ return apiRequest({
method: 'put', method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_SCANNED_HISTORY}`, url: `${API_BASE_URL}${API_URL_DELETE_SCANNED_HISTORY}`,
data: { "qrCodeId": qrCodeId } data: { qrCodeId }
});
};
// Function to delete all scanned histories
export const deleteAllScannedHistories = async () => {
return apiRequest({
method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_ALL_HISTORIES}`,
}); });
}; };
@@ -161,3 +164,11 @@ export const getScannedGmails = async () => {
url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}` url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}`
}); });
}; };
// Get user information
export const getUserInfo = async () => {
return apiRequest({
method: 'get',
url: `${API_BASE_URL}${API_URL_GET_USER}`,
});
};

View File

@@ -1,40 +1,78 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, Modal } from 'react-native'; import { View, Text, StyleSheet, Image, TouchableOpacity, Modal, ActivityIndicator, Alert } from 'react-native';
import QRCode from 'react-native-qrcode-svg'; import QRCode from 'react-native-qrcode-svg';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import * as Sharing from 'expo-sharing'; //import * as Sharing from 'expo-sharing';
import { WebView } from 'react-native-webview'; //import * as Clipboard from 'expo-clipboard'; // >.<
import { getQRCodeDetails } from '../api/qrCodeAPI';
import SecureWebView from '../components/SecureWebView'; // Import the SecureWebView component
// Define Props for ScannedDataBox component // Define Props for ScannedDataBox component
interface ScannedDataBoxProps { interface ScannedDataBoxProps {
data: string; qrCodeId: string;
dataType: string;
clearScanData: () => void; clearScanData: () => void;
scanResult: {
secureConnection: boolean;
virusTotalCheck: boolean;
redirects: number;
};
} }
const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearScanData, scanResult }) => { const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ qrCodeId, clearScanData }) => {
const [isModalVisible, setIsModalVisible] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false);
const [qrDetails, setQrDetails] = useState<any>(null);
const [isWebViewVisible, setIsWebViewVisible] = useState(false); const [isWebViewVisible, setIsWebViewVisible] = useState(false);
console.log("ScannedDataBox -> Data", data); const [webViewUrl, setWebViewUrl] = useState('');
console.log("DataType", dataType);
useEffect(() => { useEffect(() => {
console.log("Scan result set:", scanResult); const fetchQRDetails = async () => {
}, [data]); try {
const details = await getQRCodeDetails(qrCodeId);
setQrDetails(details.qrcode);
console.log('details for scannedDataBOX:', details);
} catch (error) {
console.error('Error fetching QR details:', error);
}
};
if (qrCodeId) {
fetchQRDetails();
}
}, [qrCodeId]);
if (!qrDetails) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#ff69b4" />
</View>
);
}
// Clipboard Button KIV...cause it broke everything......
/* const copyToClipboard = async () => {
try {
const contents = qrDetails.data?.contents || 'Undefined';
await Clipboard.setStringAsync(contents);
Alert.alert('Copied to Clipboard', 'The QR code content has been copied to your clipboard.');
} catch (error) {
console.error('Error copying to clipboard:', error);
}
};
*/
// Handle cases where data might be undefined
const data = qrDetails.data || {};
const details = qrDetails.details || {};
const type = data.info?.type || 'Undefined';
const contents = data.contents || 'Undefined';
const secureConnection = details.hstsHeader?.includes('HSTS Header') ? '✔️' : '✘';
const redirects = details.redirect || 0;
const securityHeaders = details.hstsHeader || ['No Headers'];
const redirectChain = details.redirectChain || ['No Redirects'];
// Determine the result text based on scan result // Determine the result text based on scan result
const getResultText = () => { const getResultText = () => {
if (!scanResult.secureConnection && !scanResult.virusTotalCheck) { if (secureConnection === '✘' || redirects > 0) {
return 'DANGEROUS'; return 'DANGEROUS';
} else if (scanResult.redirects > 0) { } else if (secureConnection === '✔️' && redirects === 0) {
return 'WARNING';
} else {
return 'SAFE'; return 'SAFE';
} else {
return 'WARNING';
} }
}; };
@@ -52,15 +90,9 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
} }
}; };
const shareQRCodeData = async () => { // Open the WebView for the URL
try { const openWebView = (url: string) => {
await Sharing.shareAsync(data); setWebViewUrl(url);
} catch (error) {
console.error('Error sharing QR code data:', error);
}
};
const openWebView = () => {
setIsWebViewVisible(true); setIsWebViewVisible(true);
}; };
@@ -74,12 +106,12 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
{/* Display scanned data */} {/* Display scanned data */}
<View style={styles.row}> <View style={styles.row}>
<Image source={require('../assets/ScanIcon3.png')} style={styles.scan_icon} /> <Image source={require('../assets/ScanIcon3.png')} style={styles.scan_icon} />
<Text style={styles.payload}>{data}</Text> <Text style={styles.payload}>{contents}</Text>
</View> </View>
<View style={styles.divider} /> <View style={styles.divider} />
<Text style={styles.timestampText}>{new Date().toLocaleString()}</Text> <Text style={styles.timestampText}>{data.createdAt ? new Date(data.createdAt).toLocaleString() : 'Invalid Date'}</Text>
<View style={styles.qrContainer}> <View style={styles.qrContainer}>
<QRCode value={data || 'No Data'} size={75} backgroundColor="transparent" /> <QRCode value={contents || 'No Data'} size={75} backgroundColor="transparent" />
<Text style={[styles.resultText, { color: getResultColor() }]}> <Text style={[styles.resultText, { color: getResultColor() }]}>
Result: {getResultText()} Result: {getResultText()}
</Text> </Text>
@@ -87,25 +119,46 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
<View style={styles.divider} /> <View style={styles.divider} />
{/* Display data type */} {/* Display data type */}
<Text style={styles.typeText}>Type: {dataType}</Text> <Text style={styles.typeText}>Type: {type}</Text>
<Text style={styles.blankLine}>{'\n'}</Text> <Text style={styles.blankLine}>{'\n'}</Text>
{/* Display scan checks */} {/* Display scan checks */}
{type === 'URL' && (
<>
<Text style={styles.checksText}>Checks</Text> <Text style={styles.checksText}>Checks</Text>
<Text style={styles.checksText}>Secure Connection: {scanResult.secureConnection ? '✔️' : '✘'}</Text> <Text style={styles.checksText}>Secure Connection: {secureConnection}</Text>
<Text style={styles.checksText}>Virus Total Check: {scanResult.virusTotalCheck ? '✔️' : '✘'}</Text> <Text style={styles.checksText}>Redirects: {redirects}</Text>
<Text style={styles.checksText}>Redirects: {scanResult.redirects}</Text> <TouchableOpacity style={styles.showAllButton} onPress={() => Alert.alert('Redirect Chain', redirectChain.join('\n'))}>
<Text style={styles.showAllButtonText}>Show all redirects</Text>
</TouchableOpacity>
</>
)}
{type === 'SMS' && (
<>
<Text style={styles.checksText}>Recipient Phone Number: {details.phone || 'Undefined'}</Text>
<Text style={styles.checksText}>Message Content: {details.message || 'Undefined'}</Text>
</>
)}
{type === 'TEXT' && (
<>
<Text style={styles.checksText}>Content: {contents}</Text>
</>
)}
{/* Action buttons */} {/* Action buttons */}
<View style={styles.iconContainer}> <View style={styles.iconContainer}>
<TouchableOpacity style={styles.iconButton} onPress={shareQRCodeData}> <TouchableOpacity style={styles.iconButton} /*onPress={copyToClipboard}*/>
<Ionicons name="share-social" size={18} color="#2196F3" /> <Ionicons name="copy-outline" size={18} color="#2196F3" />
<Text style={styles.iconText}>Share</Text> <Text style={styles.iconText}>Copy</Text>
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity style={styles.iconButton} onPress={openWebView}> {type === 'URL' && (
<TouchableOpacity style={styles.iconButton} onPress={() => openWebView(contents)}>
<Ionicons name="open" size={18} color="#2196F3" /> <Ionicons name="open" size={18} color="#2196F3" />
<Text style={styles.iconText}>Open</Text> <Text style={styles.iconText}>Open</Text>
</TouchableOpacity> </TouchableOpacity>
)}
</View> </View>
<View style={styles.divider} /> <View style={styles.divider} />
@@ -127,20 +180,17 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
<View style={styles.modalContainer}> <View style={styles.modalContainer}>
<View style={styles.modalContent}> <View style={styles.modalContent}>
<Text style={styles.modalTitle}>Security Headers</Text> <Text style={styles.modalTitle}>Security Headers</Text>
<Text style={styles.modalText}>Name: Strict-Transport-Security</Text> {securityHeaders.map((header, index) => (
<Text style={styles.modalText}>Value: max-age=31536000; includeSubDomains</Text> <Text key={index} style={styles.modalText}>{header}</Text>
<Text style={styles.modalText}>Name: X-Frame-Options</Text> ))}
<Text style={styles.modalText}>Value: DENY</Text>
<Text style={styles.modalText}>Name: X-Content-Type-Options</Text>
<Text style={styles.modalText}>Value: nosniff</Text>
<Text style={styles.modalText}>Name: Content-Security-Policy</Text>
<Text style={styles.modalText}>Value: default-src 'self'</Text>
<TouchableOpacity style={styles.closeModalButton} onPress={() => setIsModalVisible(false)}> <TouchableOpacity style={styles.closeModalButton} onPress={() => setIsModalVisible(false)}>
<Text style={styles.closeModalButtonText}>Close</Text> <Text style={styles.closeModalButtonText}>Close</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
</Modal> </Modal>
{/* SecureWebView Modal */}
<Modal <Modal
visible={isWebViewVisible} visible={isWebViewVisible}
transparent={true} transparent={true}
@@ -149,14 +199,7 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
> >
<View style={styles.modalContainer}> <View style={styles.modalContainer}>
<View style={styles.webViewContainer}> <View style={styles.webViewContainer}>
<WebView <SecureWebView url={webViewUrl} />
source={{ uri: data }}
javaScriptEnabled={false}
domStorageEnabled={false}
allowFileAccess={false}
originWhitelist={['*']}
onShouldStartLoadWithRequest={(request) => true}
/>
<TouchableOpacity style={styles.closeModalButton} onPress={() => setIsWebViewVisible(false)}> <TouchableOpacity style={styles.closeModalButton} onPress={() => setIsWebViewVisible(false)}>
<Text style={styles.closeModalButtonText}>Close</Text> <Text style={styles.closeModalButtonText}>Close</Text>
</TouchableOpacity> </TouchableOpacity>
@@ -303,13 +346,28 @@ const styles = StyleSheet.create({
fontSize: 12, fontSize: 12,
color: '#fff', color: '#fff',
}, },
loadingContainer: {
justifyContent: 'center',
alignItems: 'center',
},
showAllButton: {
backgroundColor: '#2196F3',
borderRadius: 7.5,
padding: 5,
marginTop: 5,
},
showAllButtonText: {
color: '#fff',
fontSize: 12,
textAlign: 'center',
},
webViewContainer: { webViewContainer: {
width: '100%', width: '100%',
height: '80%', height: '80%',
backgroundColor: 'white', backgroundColor: 'white',
borderRadius: 7.5, borderRadius: 7.5,
overflow: 'hidden' overflow: 'hidden'
}, }
}); });
export default ScannedDataBox; export default ScannedDataBox;

View File

@@ -1,5 +1,5 @@
import React, { useCallback, useState, useEffect, useRef } from 'react'; import React, { useCallback, useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, BackHandler, Modal } from 'react-native'; import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, Modal, ActivityIndicator } from 'react-native';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import ScannedDataBox from '../components/ScannedDataBox'; import ScannedDataBox from '../components/ScannedDataBox';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
@@ -20,6 +20,9 @@ const HistoryScreen: React.FC = () => {
const [historiesLoading, setHistoriesLoading] = useState(false); const [historiesLoading, setHistoriesLoading] = useState(false);
const [historiesError, setHistoriesError] = useState<string | null>(null); const [historiesError, setHistoriesError] = useState<string | null>(null);
const [selectedQrCodeId, setSelectedQrCodeId] = useState<string | null>(null);
const fetchHistories = useCallback(async () => { const fetchHistories = useCallback(async () => {
if (!userAttributes?.sub) return; if (!userAttributes?.sub) return;
@@ -27,8 +30,6 @@ const HistoryScreen: React.FC = () => {
setHistoriesLoading(true); setHistoriesLoading(true);
const historiesData = await getScannedHistories(); const historiesData = await getScannedHistories();
dispatch(setScannedHistories(historiesData)); dispatch(setScannedHistories(historiesData));
setHistoriesLoading(false);
} catch (error: any) { } catch (error: any) {
setHistoriesError(error.message); setHistoriesError(error.message);
} finally { } finally {
@@ -50,44 +51,18 @@ const HistoryScreen: React.FC = () => {
}, [dispatch, userAttributes]); }, [dispatch, userAttributes]);
const [selectedData, setSelectedData] = useState<string | null>(null);
const [selectedScanResult, setSelectedScanResult] = useState<any | null>(null);
const [selectedType, setSelectedType] = useState<string | null>(null);
useEffect(() => {
const backAction = () => {
if (selectedData) {
setSelectedData(null);
setSelectedScanResult(null);
setSelectedType(null);
return true;
}
return false;
};
const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
return () => backHandler.remove();
}, [selectedData]);
const filteredQrCodes = showBookmarks ? histories.filter(qr => qr.bookmarked) : histories; const filteredQrCodes = showBookmarks ? histories.filter(qr => qr.bookmarked) : histories;
const handleItemPress = (item: QRCodeType) => { const handleItemPress = (item: QRCodeType) => {
// setSelectedData(item.data); setSelectedQrCodeId(item.data.id || null);
// setSelectedScanResult(item.scanResult);
// setSelectedType(item.type);
//setSelectedData(item.contents);
setSelectedType(item.data.type);
console.log('Selected QR code data:', item);
// console.log('Selected QR code type:', item.type);
}; };
const clearSelectedData = () => { const clearSelectedData = () => {
setSelectedData(null); setSelectedQrCodeId(null);
setSelectedScanResult(null);
setSelectedType(null);
}; };
return ( return (
<View style={styles.container}> <View style={styles.container}>
{/* Header for toggling between History and Bookmarks */} {/* Header for toggling between History and Bookmarks */}
@@ -99,18 +74,28 @@ const HistoryScreen: React.FC = () => {
<Text style={showBookmarks ? styles.headerTextActive : styles.headerTextInactive}>Bookmarks</Text> <Text style={showBookmarks ? styles.headerTextActive : styles.headerTextInactive}>Bookmarks</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
{/* Display scanned data details */}
{selectedData && ( {/* Loading Indicator */}
<View style={styles.scannedDataBoxContainer}> {historiesLoading && <ActivityIndicator size="large" color="#ff69b4" />}
<ScannedDataBox data={selectedData} scanResult={selectedScanResult} dataType={selectedType} clearScanData={clearSelectedData} />
</View> {/* Display message when there are no histories or bookmarks */}
{!historiesLoading && filteredQrCodes.length === 0 && (
<Text style={styles.emptyMessage}>
{showBookmarks ? 'No bookmarks available' : 'No history available'}
</Text>
)} )}
{/* Display scanned data details */}
{selectedQrCodeId && (
<View style={styles.scannedDataBoxContainer}>
<ScannedDataBox qrCodeId={selectedQrCodeId} clearScanData={clearSelectedData} />
</View>
)}
{/* List of QR codes */} {/* List of QR codes */}
<FlatList <FlatList
data={filteredQrCodes} data={filteredQrCodes}
renderItem={({ item }) => { renderItem={({ item }) => (
// console.log('Rendering QR code item:', item);
return (
<View style={styles.itemContainer}> <View style={styles.itemContainer}>
<View style={styles.itemLeft}> <View style={styles.itemLeft}>
<TouchableOpacity onPress={() => handleItemPress(item)} style={styles.itemContent}> <TouchableOpacity onPress={() => handleItemPress(item)} style={styles.itemContent}>
@@ -135,15 +120,11 @@ const HistoryScreen: React.FC = () => {
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
); )}
}} keyExtractor={(item, index) => index.toString()}
keyExtractor={(item, index) => {
//console.log(item, index);
return index.toString();
}}
contentContainerStyle={styles.flatListContent} contentContainerStyle={styles.flatListContent}
/> />
{/* Modal for delete confirmation */} {/* Modal for delete confirmation */}
<Modal <Modal
transparent={true} transparent={true}
@@ -234,6 +215,15 @@ const styles = StyleSheet.create({
flatListContent: { flatListContent: {
paddingBottom: 100, paddingBottom: 100,
}, },
emptyMessage: {
textAlign: 'center',
fontSize: 16,
color: '#ff69b4',
marginVertical: 20,
},
scannedDataBoxContainer: {
marginBottom: 20,
},
modalContainer: { modalContainer: {
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: 'center',
@@ -271,9 +261,6 @@ const styles = StyleSheet.create({
fontSize: 16, fontSize: 16,
color: '#000', color: '#000',
}, },
scannedDataBoxContainer: {
marginBottom: 20,
},
}); });
export default HistoryScreen; export default HistoryScreen;

View File

@@ -1,40 +1,29 @@
import React, { useState, useEffect, useContext, useCallback } from 'react'; import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, TouchableOpacity, Alert, Modal } from 'react-native'; import { View, Text, StyleSheet, ActivityIndicator, TouchableOpacity, Modal, TouchableWithoutFeedback } from 'react-native';
import { Camera, CameraView, scanFromURLAsync } from 'expo-camera'; import { Camera, CameraView, scanFromURLAsync } from 'expo-camera';
import { QRCodeContext } from '../types'; import { Ionicons } from '@expo/vector-icons';
import axios from 'axios'; // For URL calls
import { Ionicons } from '@expo/vector-icons'; // For icons
import { useFocusEffect, useNavigation } from '@react-navigation/native'; import { useFocusEffect, useNavigation } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker'; import * as ImagePicker from 'expo-image-picker';
import ScannedDataBox from '../components/ScannedDataBox'; import ScannedDataBox from '../components/ScannedDataBox';
import { useDispatch } from 'react-redux'; import { useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '../store'; import { AppDispatch } from '../store';
import { addQRCode } from '../reducers/qrCodesReducer'; // Assuming you have actions defined for Redux import { addQRCode } from '../reducers/qrCodesReducer';
import { detectQRCodeType, verifyURL, checkRedirects } from '../api/qrCodeAPI'; // Import utility functions import { scanQRCode, getUserInfo } from '../api/qrCodeAPI';
import SettingsScreen from './SettingsScreen'; // Import the Settings screen import SettingsScreen from './SettingsScreen';
const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanData }) => { const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanData }) => {
const navigation = useNavigation(); // call Navigation bar const navigation = useNavigation(); // Navigation hook
const dispatch = useDispatch<AppDispatch>(); // Use dispatch for Redux actions const dispatch = useDispatch<AppDispatch>(); // Use dispatch for Redux actions
const [showSplash, setShowSplash] = useState<boolean>(true); // call splash screen // State variables
const qrCodeContext = useContext(QRCodeContext); // From ./types.ts const [showSplash, setShowSplash] = useState<boolean>(true); // State for splash screen visibility
const { qrCodes, setQrCodes } = qrCodeContext || { qrCodes: [], setQrCodes: () => {} };
const [hasPermission, setHasPermission] = useState<boolean | null>(null); const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const [scanned, setScanned] = useState<boolean>(false); const [scanned, setScanned] = useState<boolean>(false);
const [scannedData, setScannedData] = useState<string>(''); // State for QR scanned Data const [qrCodeId, setQRCodeId] = useState<string | null>(null); // State for QR code ID
const [dataType, setDataType] = useState<string>(''); // State for data type
const [enableTorch, setEnableTorch] = useState<boolean>(false); // State for torch const [enableTorch, setEnableTorch] = useState<boolean>(false); // State for torch
const [cameraVisible, setCameraVisible] = useState<boolean>(true); // State to control camera visibility const [cameraVisible, setCameraVisible] = useState<boolean>(true); // State to control camera visibility
const [isScannedDataBoxVisible, setIsScannedDataBoxVisible] = useState<boolean>(false); // State for ScannedDataBox modal visibility
// State to control the visibility of the modal const [isSettingsModalVisible, setIsSettingsModalVisible] = useState<boolean>(false); // State for modal visibility
const [isSettingsModalVisible, setIsSettingsModalVisible] = useState<boolean>(false);
// Add state variables for scan results
const [secureConnection, setSecureConnection] = useState<boolean | null>(null);
const [virusTotalCheck, setVirusTotalCheck] = useState<boolean | null>(null);
const [redirects, setRedirects] = useState<number | null>(null);
// Request Camera Permission and initialize the app // Request Camera Permission and initialize the app
useEffect(() => { useEffect(() => {
@@ -43,79 +32,71 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
setHasPermission(status === 'granted'); setHasPermission(status === 'granted');
setShowSplash(false); setShowSplash(false);
console.log("Camera permissions initialized"); console.log("Camera permissions initialized");
// Fetch and log user information
fetchUserInformation();
}; };
initializeApp(); initializeApp();
}, []); }, []);
// Focus effect to enable camera and clear data on focus
useFocusEffect(
useCallback(() => {
setCameraVisible(true);
clearScanDataInternal();
console.log("Screen focused, scan data cleared and camera enabled");
return () => {
setCameraVisible(false);
console.log("Screen unfocused, camera disabled");
};
}, [navigation])
);
// Clear Scan Data // Clear Scan Data
const clearScanDataInternal = () => { const clearScanDataInternal = () => {
setScannedData('');
setScanned(false); setScanned(false);
setDataType(''); setQRCodeId(null);
console.log("Scan data cleared"); console.log("Scan data cleared");
}; };
// Handle scanning of payload (QR code data) and get the QR-ID
const handlePayload = async (payload: string) => { const handlePayload = async (payload: string) => {
setScanned(true); setScanned(true);
console.log("Scanning Completed. Payload is:", payload); console.info("Decoded QR Code, Payload is: ", payload);
const type = await detectQRCodeType(payload);
const secureConnectionResult = await verifyURL(payload);
const redirectResult = await checkRedirects(payload);
setSecureConnection(secureConnectionResult.isSecure);
setVirusTotalCheck(!secureConnectionResult.isMalicious); // Assuming you have virusTotalCheck logic integrated here
setRedirects(redirectResult.redirects);
const qrCode = {
data: payload,
type,
scanResult: {
secureConnection: secureConnectionResult.isSecure,
virusTotalCheck: !secureConnectionResult.isMalicious,
redirects: redirectResult.redirects
},
bookmarked: false // by default
};
setScannedData(payload);
console.log("Payload received:", payload);
console.log("Type received from server:", type);
setDataType(type);
dispatch(addQRCode(qrCode)); // Dispatch action to save QR code data
console.log("QR code data added to history");
};
const sendToAPIServer = async (payload: string): Promise<string> => {
console.log('Sending QR code data to backend:', payload);
try { try {
const response = await axios.post('http://192.168.1.30:8080/v1/qrcodetypes/scan', { const response = await scanQRCode(payload);
data: payload, const qrCodeId = response.qrcode.data.id;
}, { // Store the QR code ID for later use
headers: { setQRCodeId(qrCodeId);
'Content-Type': 'application/json', setIsScannedDataBoxVisible(true); // Show ScannedDataBox modal
},
}); // Optionally, show a message or perform another action
console.log('Response from backend:', response.data); console.log("QR code scanned successfully, ID:", qrCodeId);
return response.data;
} catch (error) { } catch (error) {
console.error('Error detecting QR code type:', error); console.error("Error scanning QR code:", error);
return 'UNKNOWN';
} }
}; };
// Fetch and log user information
const fetchUserInformation = async () => {
try {
const userInfo = await getUserInfo();
console.log('User Info:', userInfo);
} catch (error) {
console.error('Error fetching user information:', error);
}
};
// Toggle torch (flashlight) on/off
const toggleTorch = () => { const toggleTorch = () => {
setEnableTorch((prev) => !prev); setEnableTorch((prev) => !prev);
console.log("Torch toggled:", enableTorch ? "off" : "on"); console.log("Torch toggled:", enableTorch ? "off" : "on");
}; };
const handleTestScan = () => { // Read QR from image
handlePayload('TEST123');
console.log("Test scan executed");
};
const readQRFromImage = async () => { const readQRFromImage = async () => {
clearScanDataInternal(); clearScanDataInternal();
console.log("Reading QR code from image"); console.log("Reading QR code from image");
@@ -133,30 +114,15 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
handlePayload(scannedResult[0].data); handlePayload(scannedResult[0].data);
console.log('QR code data from image:', scannedResult[0].data); console.log('QR code data from image:', scannedResult[0].data);
} else { } else {
setScannedData("No QR Code Found");
console.log("No QR code found in the selected image"); console.log("No QR code found in the selected image");
Alert.alert('No QR code found in the selected image.');
} }
} catch (error) { } catch (error) {
console.error('Error scanning QR code from image:', error); console.error('Error scanning QR code from image:', error);
Alert.alert('Failed to scan QR code from image.');
} }
} }
}; };
useFocusEffect( // Conditional rendering based on state
useCallback(() => {
setCameraVisible(true);
clearScanDataInternal();
console.log("Screen focused, scan data cleared and camera enabled");
return () => {
setCameraVisible(false);
console.log("Screen unfocused, camera disabled");
};
}, [navigation])
);
if (showSplash) { if (showSplash) {
return ( return (
<View style={styles.splashContainer}> <View style={styles.splashContainer}>
@@ -175,7 +141,7 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.headerText}>SafeQR v0.89</Text> <Text style={styles.headerText}>SafeQR</Text>
<Text style={styles.welcomeText}>Welcome to SafeQR code Scanner</Text> <Text style={styles.welcomeText}>Welcome to SafeQR code Scanner</Text>
<View style={styles.cameraContainer}> <View style={styles.cameraContainer}>
@@ -196,20 +162,16 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
</TouchableOpacity> </TouchableOpacity>
</View> </View>
{scannedData !== '' && ( {/* Scanned Data Box */}
<View style={styles.scannedDataBox}> {isScannedDataBoxVisible && (
<View style={styles.scannedDataBoxPopup}>
<ScannedDataBox <ScannedDataBox
data={scannedData} qrCodeId={qrCodeId}
dataType={dataType} clearScanData={() => setIsScannedDataBoxVisible(false)}
clearScanData={clearScanDataInternal}
scanResult={{
secureConnection,
virusTotalCheck,
redirects
}}
/> />
</View> </View>
)} )}
{/* Settings Icon */} {/* Settings Icon */}
<TouchableOpacity onPress={() => setIsSettingsModalVisible(true)} style={styles.settingsButton}> <TouchableOpacity onPress={() => setIsSettingsModalVisible(true)} style={styles.settingsButton}>
@@ -222,9 +184,10 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
transparent={true} transparent={true}
visible={isSettingsModalVisible} visible={isSettingsModalVisible}
onRequestClose={() => setIsSettingsModalVisible(false)} onRequestClose={() => setIsSettingsModalVisible(false)}
style={styles.settingsModal}
> >
<View style={styles.modalContainer}> <View style={styles.settingsModalContainer}>
<View style={styles.modalContent}> <View style={styles.settingsModalContent}>
<SettingsScreen /> <SettingsScreen />
<TouchableOpacity onPress={() => setIsSettingsModalVisible(false)} style={styles.closeButton}> <TouchableOpacity onPress={() => setIsSettingsModalVisible(false)} style={styles.closeButton}>
<Text style={styles.closeButtonText}>Close</Text> <Text style={styles.closeButtonText}>Close</Text>
@@ -290,13 +253,18 @@ const styles = StyleSheet.create({
backgroundColor: '#000', backgroundColor: '#000',
borderRadius: 25, borderRadius: 25,
}, },
scannedDataBox: { scannedDataBoxPopup: {
position: 'absolute', position: 'absolute',
top: '10%', top: '10%',
left: '5%', left: '5%',
right: '5%', right: '5%',
zIndex: 2, zIndex: 2,
backgroundColor: 'white', // Optional: Set a background color if needed
borderRadius: 10, // Optional: Add rounded corners
padding: 10, // Optional: Add padding around the content
elevation: 5, // Optional: Add elevation for shadow effect
}, },
welcomeText: { welcomeText: {
textAlign: 'center', textAlign: 'center',
fontSize: 20, fontSize: 20,
@@ -309,19 +277,21 @@ const styles = StyleSheet.create({
right: 20, right: 20,
zIndex: 2, zIndex: 2,
}, },
modalContainer: { settingsModal: {
flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.5)', // Semi-transparent background
justifyContent: 'center', },
height: '90%', settingsModalContainer: {
alignItems: 'center', flex: 2,
justifyContent: 'center', // Center the modal vertically
backgroundColor: 'rgba(0, 0, 0, 0.5)', backgroundColor: 'rgba(0, 0, 0, 0.5)',
}, },
modalContent: { settingsModalContent: {
width: '100%', // Adjust the width to cover more space width: '100%',
height: '90%', // Adjust the height to cover more space height: '80%', // Increase the height to make the modal taller
backgroundColor: 'white', backgroundColor: 'white',
padding: 20, // Reduce the padding padding: 20,
borderRadius: 10, borderTopLeftRadius: 10,
borderTopRightRadius: 10,
alignItems: 'center', alignItems: 'center',
}, },
closeButton: { closeButton: {
@@ -333,6 +303,7 @@ const styles = StyleSheet.create({
closeButtonText: { closeButtonText: {
color: 'white', color: 'white',
fontWeight: 'bold', fontWeight: 'bold',
}, }
}); });
export default QRScannerScreen; export default QRScannerScreen;

View File

@@ -1,16 +1,16 @@
import { View, Text, StyleSheet, TouchableOpacity, Linking, Button } from 'react-native'; import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Linking, Alert, Button } from 'react-native';
import { useAuthenticator } from '@aws-amplify/ui-react-native'; import { useAuthenticator } from '@aws-amplify/ui-react-native';
import useFetchUserAttributes from '../hooks/useFetchUserAttributes'; import useFetchUserAttributes from '../hooks/useFetchUserAttributes';
import { fetchAuthSession, getCurrentUser, signInWithRedirect } from 'aws-amplify/auth'; import { fetchAuthSession, getCurrentUser, signInWithRedirect } from 'aws-amplify/auth';
import { useEffect, useState } from 'react'; import { deleteAllScannedHistories } from '../api/qrCodeAPI'; // Import the API function
import { Buffer } from 'buffer'; import { Buffer } from 'buffer';
import { createDrawerNavigator } from '@react-navigation/drawer';
function SignOutButton() { function SignOutButton() {
const { signOut } = useAuthenticator(); const { signOut } = useAuthenticator();
return <Button title="Sign Out" onPress={signOut} />; return <Button title="Sign Out" onPress={signOut} />;
} }
const handleSignInWithRedirect = async () => { const handleSignInWithRedirect = async () => {
try { try {
await signInWithRedirect(); await signInWithRedirect();
@@ -42,7 +42,6 @@ const SettingsScreen: React.FC = () => {
const parts = idToken.split('.'); const parts = idToken.split('.');
if (parts.length !== 3) { if (parts.length !== 3) {
throw new Error('ID token is not a valid JWT'); throw new Error('ID token is not a valid JWT');
} }
const payload = parts[1]; const payload = parts[1];
@@ -70,7 +69,6 @@ const SettingsScreen: React.FC = () => {
second: '2-digit' second: '2-digit'
}; };
if (parsedPayload["custom:access_token"]) { if (parsedPayload["custom:access_token"]) {
console.log('Google Access Token:', parsedPayload["custom:access_token"]); console.log('Google Access Token:', parsedPayload["custom:access_token"]);
console.log('Google Refresh Token: ', parsedPayload["custom:refresh_token"]); console.log('Google Refresh Token: ', parsedPayload["custom:refresh_token"]);
@@ -84,7 +82,6 @@ const SettingsScreen: React.FC = () => {
} else { } else {
console.error('No Google access token found in the payload'); console.error('No Google access token found in the payload');
} }
} else { } else {
console.error('No ID token found in the session'); console.error('No ID token found in the session');
} }
@@ -102,14 +99,25 @@ const SettingsScreen: React.FC = () => {
Linking.openURL(url); Linking.openURL(url);
}; };
const handleDeleteAllHistories = async () => {
try {
const response = await deleteAllScannedHistories();
Alert.alert('Success', response.message);
} catch (error) {
Alert.alert('Error', 'Failed to delete histories. Please try again.');
}
};
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.header}>Settings</Text> <Text style={styles.header}>Settings</Text>
<View style={styles.profileSection}>
{/* Profile Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Profile</Text> <Text style={styles.sectionTitle}>Profile</Text>
{userAttributes ? ( {userAttributes ? (
<View> <View>
<Text style={styles.userName}>Hello, {userAttributes?.name}</Text> <Text style={styles.userName}>Hello, {userAttributes.name || 'Unknown User'}</Text>
{googleAccessToken && ( {googleAccessToken && (
<Text>Google Access Token: {googleAccessToken.substring(0, 10)}...</Text> <Text>Google Access Token: {googleAccessToken.substring(0, 10)}...</Text>
)} )}
@@ -121,8 +129,22 @@ const SettingsScreen: React.FC = () => {
</TouchableOpacity> </TouchableOpacity>
)} )}
</View> </View>
<View style={styles.divider} /> <View style={styles.divider} />
<View style={styles.aboutUsSection}>
{/* History & Bookmarks Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>History & Bookmarks</Text>
<TouchableOpacity style={styles.deleteAllButton} onPress={handleDeleteAllHistories}>
<Text style={styles.deleteAllButtonText}>Delete All History</Text>
</TouchableOpacity>
</View>
<View style={styles.divider} />
{/* About Us Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>About Us</Text> <Text style={styles.sectionTitle}>About Us</Text>
<TouchableOpacity onPress={() => handleLinkPress('https://safeqr.github.io/marketing/')}> <TouchableOpacity onPress={() => handleLinkPress('https://safeqr.github.io/marketing/')}>
<Text style={styles.linkText}>safeqr.github.io/marketing</Text> <Text style={styles.linkText}>safeqr.github.io/marketing</Text>
@@ -134,6 +156,7 @@ const SettingsScreen: React.FC = () => {
<Text style={styles.linkText}>Terms Of Service</Text> <Text style={styles.linkText}>Terms Of Service</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
<Text style={styles.versionText}>Version 1.2</Text> <Text style={styles.versionText}>Version 1.2</Text>
</View> </View>
); );
@@ -143,17 +166,17 @@ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
backgroundColor: '#f8f0fc', backgroundColor: '#f8f0fc',
padding: 10, // Reduce padding padding: 10,
width: '100%', // Increase width to fill the modal width: '100%',
}, },
header: { header: {
fontSize: 24, fontSize: 24,
fontWeight: 'bold', fontWeight: 'bold',
color: '#ff69b4', color: '#ff69b4',
marginBottom: 20, marginBottom: 20,
textAlign: 'center', // Center the header text textAlign: 'center',
}, },
profileSection: { section: {
marginBottom: 20, marginBottom: 20,
}, },
sectionTitle: { sectionTitle: {
@@ -162,6 +185,11 @@ const styles = StyleSheet.create({
color: '#000', color: '#000',
marginBottom: 10, marginBottom: 10,
}, },
userName: {
fontSize: 16,
color: '#000',
marginBottom: 10,
},
loginButton: { loginButton: {
backgroundColor: '#ff69b4', backgroundColor: '#ff69b4',
paddingVertical: 8, paddingVertical: 8,
@@ -175,14 +203,26 @@ const styles = StyleSheet.create({
color: '#000', color: '#000',
fontSize: 16, fontSize: 16,
}, },
deleteAllButton: {
backgroundColor: '#ff0000', // Red color
borderRadius: 25, // Round button
paddingVertical: 10,
paddingHorizontal: 20,
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'flex-start',
marginVertical: 10,
},
deleteAllButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
divider: { divider: {
height: 1, height: 1,
backgroundColor: '#ccc', backgroundColor: '#ccc',
marginVertical: 20, marginVertical: 20,
}, },
aboutUsSection: {
marginBottom: 20,
},
linkText: { linkText: {
fontSize: 16, fontSize: 16,
color: '#0000ff', color: '#0000ff',
@@ -194,7 +234,7 @@ const styles = StyleSheet.create({
color: '#aaa', color: '#aaa',
marginTop: 20, marginTop: 20,
}, },
}); });
export default SettingsScreen; export default SettingsScreen;