Commit 7cca654f authored by Malsha Rathnasiri's avatar Malsha Rathnasiri

add authentication and temporary remove tensorflow

parent 88281141
import React, { createContext, useContext, useState, useEffect, useLayoutEffect } from "react";
import axios from "axios";
import { LOCALHOST } from "./constants";
// import { nexlAxios } from "../../constants/helper";
import AsyncStorage from "@react-native-async-storage/async-storage";
// import {
// IAuthContext,
// IAuthRequest,
// STORAGE_BEARER_TOKEN,
// UNINITIALISED,
// USER_EMAIL,
// } from "./IAuthContext";
// import { Loading } from "./state/Loading";
// import { getEnvironment } from "../../constants/variables";
// import { AxiosError, AxiosResponse } from "axios";
// import { rollbar } from "./ErrorBoundary";
// import { ENDPOINT as endpoint } from "./constants";
// const AuthContext = createContext({
// isLoggedIn: false,
// token: "",
// email: "",
// error: "",
// loading: false,
// initialised: false,
// login: UNINITIALISED,
// logout: UNINITIALISED,
// });
// export const useAuthContext = () => useContext(AuthContext);
// export const AuthConsumer = AuthContext.Consumer;
// interface IProps {
// children: any;
// }
// interface ILoginData {
// error: string;
// user: {
// email: string;
// id: string;
// first_name: string;
// last_name: string;
// };
// }
// const endpoint = getEnvironment().endpoint;
export const login = async (username, password) => {
const endpoint = false ? 'register' : 'login';
const payload = { username: username, password: password }
const headers = new Headers({ "Content-Type": 'application./json','mode': 'no-cors', 'Access-Control-Allow-Headers': '*' })
const options = { method: 'POST', data: payload, headers }
axios.defaults.baseURL = 'http://127.0.0.1:8000';
axios.defaults.timeout = 1500;
console.log({payload})
return axios.post('/api/auth/token/obtain/', payload)
.then(response => {
const { access, refresh, user } = response.data;
axios.defaults.headers.common.Authorization = `Token ${token}`;
AsyncStorage.setItem('user_id', user.id)
AsyncStorage.setitem('username',user.username)
AsyncStorage.setItem('user_email', user.email)
AsyncStorage.setitem('access_token', access)
AsyncStorage.setItem('refresh_token', refresh)
console.log("login successful")
return true
// Actions.main();
})
.catch(error => {
throw Error(error)
});
}
// export const AuthProvider = ({ children }) => {
// const [isLoggedIn, setIsLoggedIn] = useState(false);
// const [token, setToken] = useState("");
// const [email, setEmail] = useState("");
// const [error, setError] = useState("");
// const [loading, setLoading] = useState(false);
// const [initialised, setInitialised] = useState(false);
// const login = async ({ email, password, rememberMe }) => {
// setLoading(true);
// nexlAxios(false)
// .post(`${endpoint}/accounts/sign_in.json`, {
// source: "iOS app",
// account: {
// email,
// password,
// remember_me: rememberMe ? "1" : "0",
// },
// })
// .then(async (response) => {
// setLoading(false);
// const user = response.data.user;
// user.email && setIsLoggedIn(true);
// const token = response.headers["authorization"];
// setToken(token);
// await AsyncStorage.setItem(USER_EMAIL, email);
// setEmail(email);
// rollbar.setPerson(user.id, `${user.first_name} ${user.last_name}`, user.email);
// })
// .catch((result) => {
// setLoading(false);
// setError(
// result?.response?.data?.error || result?.message || "An unknown error has occurred.",
// );
// });
// };
// const loginWithBearerToken = async (bearer) => {
// if (bearer) {
// setLoading(true);
// await nexlAxios(false, bearer)
// .post(`${endpoint}/accounts/sign_in.json`, undefined, {
// headers: {
// Authorization: bearer,
// },
// })
// .then((response) => {
// setLoading(false);
// const user = response.data.user;
// user.email && setIsLoggedIn(true);
// rollbar.setPerson(user.id, `${user.first_name} ${user.last_name}`, user.email);
// })
// .catch(() => {
// setLoading(false);
// setToken("");
// });
// }
// };
// const logout = async () => {
// const token = await AsyncStorage.getItem(STORAGE_BEARER_TOKEN);
// token && (await nexlAxios(false, token).post(`${endpoint}/sign_out.json`));
// setToken("");
// setIsLoggedIn(false);
// await AsyncStorage.removeItem(STORAGE_BEARER_TOKEN);
// rollbar.clearPerson();
// };
// // look if token / email exist in local storage on initialising the app
// // if token exists, try log in with token
// useLayoutEffect(() => {
// let isMounted = true;
// const initialise = async () => {
// const bearerToken = await AsyncStorage.getItem(STORAGE_BEARER_TOKEN);
// setToken(bearerToken || "");
// const userEmail = await AsyncStorage.getItem(USER_EMAIL);
// setEmail(userEmail || "");
// bearerToken && (await loginWithBearerToken(bearerToken));
// setInitialised(true);
// };
// if (isMounted) {
// initialise();
// }
// return () => {
// isMounted = false;
// };
// }, []);
// // update token to local storage on token change
// useEffect(() => {
// AsyncStorage.setItem(STORAGE_BEARER_TOKEN, token);
// }, [token]);
// return (
// <AuthContext.Provider
// value={{
// login,
// isLoggedIn,
// logout,
// token,
// email: email.toLowerCase(),
// loading,
// error,
// initialised,
// }}
// >
// {initialised ? children : <Loading copy="Logging in..." />}
// </AuthContext.Provider>
// );
// };
\ No newline at end of file
export const LOCALHOST = "http://127.0.0.1:8000"
\ No newline at end of file
import React, { createContext, useContext, useState, useEffect, useLayoutEffect } from "react";
import { nexlAxios } from "../../constants/helper";
import AsyncStorage from "@react-native-community/async-storage";
import {
IAuthContext,
IAuthRequest,
STORAGE_BEARER_TOKEN,
UNINITIALISED,
USER_EMAIL,
} from "./IAuthContext";
import { Loading } from "./state/Loading";
import { getEnvironment } from "../../constants/variables";
import { AxiosError, AxiosResponse } from "axios";
import { rollbar } from "./ErrorBoundary";
const AuthContext = createContext({
isLoggedIn: false,
token: "",
email: "",
error: "",
loading: false,
initialised: false,
login: UNINITIALISED,
logout: UNINITIALISED,
});
export const useAuthContext = () => useContext(AuthContext);
export const AuthConsumer = AuthContext.Consumer;
// interface IProps {
// children: any;
// }
// interface ILoginData {
// error: string;
// user: {
// email: string;
// id: string;
// first_name: string;
// last_name: string;
// };
// }
const endpoint = getEnvironment().endpoint;
export const AuthProvider= ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [token, setToken] = useState("");
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [initialised, setInitialised] = useState(false);
const login = async ({ email, password, rememberMe }) => {
setLoading(true);
nexlAxios(false)
.post(`${endpoint}/accounts/sign_in.json`, {
source: "iOS app",
account: {
email,
password,
remember_me: rememberMe ? "1" : "0",
},
})
.then(async (response) => {
setLoading(false);
const user = response.data.user;
user.email && setIsLoggedIn(true);
const token = response.headers["authorization"];
setToken(token);
await AsyncStorage.setItem(USER_EMAIL, email);
setEmail(email);
rollbar.setPerson(user.id, `${user.first_name} ${user.last_name}`, user.email);
})
.catch((result) => {
setLoading(false);
setError(
result?.response?.data?.error || result?.message || "An unknown error has occurred.",
);
});
};
const loginWithBearerToken = async (bearer) => {
if (bearer) {
setLoading(true);
await nexlAxios(false, bearer)
.post(`${endpoint}/accounts/sign_in.json`, undefined, {
headers: {
Authorization: bearer,
},
})
.then((response) => {
setLoading(false);
const user = response.data.user;
user.email && setIsLoggedIn(true);
rollbar.setPerson(user.id, `${user.first_name} ${user.last_name}`, user.email);
})
.catch(() => {
setLoading(false);
setToken("");
});
}
};
const logout = async () => {
const token = await AsyncStorage.getItem(STORAGE_BEARER_TOKEN);
token && (await nexlAxios(false, token).post(`${endpoint}/sign_out.json`));
setToken("");
setIsLoggedIn(false);
await AsyncStorage.removeItem(STORAGE_BEARER_TOKEN);
rollbar.clearPerson();
};
// look if token / email exist in local storage on initialising the app
// if token exists, try log in with token
useLayoutEffect(() => {
let isMounted = true;
const initialise = async () => {
const bearerToken = await AsyncStorage.getItem(STORAGE_BEARER_TOKEN);
setToken(bearerToken || "");
const userEmail = await AsyncStorage.getItem(USER_EMAIL);
setEmail(userEmail || "");
bearerToken && (await loginWithBearerToken(bearerToken));
setInitialised(true);
};
if (isMounted) {
initialise();
}
return () => {
isMounted = false;
};
}, []);
// update token to local storage on token change
useEffect(() => {
AsyncStorage.setItem(STORAGE_BEARER_TOKEN, token);
}, [token]);
return (
<AuthContext.Provider
value={{
login,
isLoggedIn,
logout,
token,
email: email.toLowerCase(),
loading,
error,
initialised,
}}
>
{initialised ? children : <Loading copy="Logging in..." />}
</AuthContext.Provider>
);
};
\ No newline at end of file
......@@ -9,13 +9,14 @@ import { NavigationContainer, DefaultTheme, DarkTheme } from '@react-navigation/
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import * as React from 'react';
import { ColorSchemeName, Pressable } from 'react-native';
import { login } from '../api/Authentication';
import Colors from '../constants/Colors';
import useColorScheme from '../hooks/useColorScheme';
import { LoginScreen } from '../screens/loginScreen';
import ModalScreen from '../screens/ModalScreen';
import NotFoundScreen from '../screens/NotFoundScreen';
import TabOneScreen from '../screens/TabOneScreen';
import ChatScreen from '../screens/TabOneScreen';
import TabTwoScreen from '../screens/TabTwoScreen';
import { RootStackParamList, RootTabParamList, RootTabScreenProps } from '../types';
import LinkingConfiguration from './LinkingConfiguration';
......@@ -40,22 +41,18 @@ function RootNavigator() {
const [isAuthenticated, setIsAutheticated] = React.useState(false)
const onLogin = () => {
setIsAutheticated(true)
const onLogin = async (username: String, password: String) => {
await login(username, password).then(() => setIsAutheticated(true)).catch(e => console.log(e))
}
const onLogout = () => {
setIsAutheticated(false)
}
return (
<Stack.Navigator >
{isAuthenticated ? <Stack.Screen name="Root" options={{ headerShown: false }}>{(props) => <BottomTabNavigator {...props} onLogout={onLogout}/>}</Stack.Screen> :
<Stack.Screen name='Login'>{(props) => <LoginScreen {...props} onLogin={onLogin} />}</Stack.Screen>}
{isAuthenticated ? <Stack.Screen name="Root" options={{ headerShown: false }}>{(props) => <BottomTabNavigator {...props} onLogout={onLogout} />}</Stack.Screen> :
<Stack.Screen name='Root'>{(props) => <LoginScreen {...props} onLogin={onLogin} />}</Stack.Screen>}
<Stack.Screen name="NotFound" component={NotFoundScreen} options={{ title: 'Oops!' }} />
......@@ -72,7 +69,7 @@ function RootNavigator() {
*/
const BottomTab = createBottomTabNavigator<RootTabParamList>();
function BottomTabNavigator({onLogout}) {
function BottomTabNavigator({ onLogout }) {
const colorScheme = useColorScheme();
return (
......@@ -83,7 +80,7 @@ function BottomTabNavigator({onLogout}) {
}}>
<BottomTab.Screen
name="TabOne"
component={TabOneScreen}
component={ChatScreen}
options={({ navigation }: RootTabScreenProps<'TabOne'>) => ({
title: 'Chat',
tabBarIcon: ({ color }) => <TabBarIcon name="code" color={color} />,
......
......@@ -15,6 +15,7 @@
},
"dependencies": {
"@expo/vector-icons": "^12.0.0",
"@react-native-async-storage/async-storage": "~1.15.0",
"@react-navigation/bottom-tabs": "^6.0.5",
"@react-navigation/native": "^6.0.2",
"@react-navigation/native-stack": "^6.1.0",
......
import React, { useEffect, useState } from 'react'
import { FlatList, StyleSheet, TextInput, SectionList } from 'react-native';
import { AudioRecorder } from '../components/AudioRecorder';
import _ from 'lodash'
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { RootTabScreenProps } from '../types';
export default function ChatScreen({ navigation }) {
const currentTime = new Date()
const defaultChatData = [{ from: 'esh', to: "dri", message: 'msg1', time: currentTime.setMinutes(currentTime.getMinutes() - 1) },
{ from: 'esh', to: "dri", message: 'msg2', time: currentTime.setMinutes(currentTime.getMinutes() - 2) },
{ from: 'dri', to: "esh", message: 'msg3', time: currentTime.setMinutes(currentTime.getMinutes() - 3) },
{ from: 'esh', to: "dri", message: 'msg4', time: currentTime.setMinutes(currentTime.getMinutes() - 4) },
{ from: 'dri', to: "esh", message: 'msg5', time: currentTime.setMinutes(currentTime.getMinutes() - 5) },
{ from: 'esh', to: "dri", message: 'msg1', time: currentTime.setDate(currentTime.getDate() - 1) },
{ from: 'esh', to: "dri", message: 'msg2', time: currentTime.setDate(currentTime.getDate() - 2) },
{ from: 'dri', to: "esh", message: 'msg3', time: currentTime.setDate(currentTime.getDate() - 3) },
{ from: 'esh', to: "dri", message: 'msg4', time: currentTime.setDate(currentTime.getDate() - 4) },
{ from: 'dri', to: "esh", message: 'msg5', time: currentTime.setDate(currentTime.getDate() - 5) },
]
const [detectedText, setDetectedText] = useState("")
const [chatDetails, setChatDetails] = useState({ from: "esh", to: 'dri' })
const [chats, setChats] = useState(defaultChatData)
const ws = new WebSocket('ws://localhost:3000/ws')
const sections = [...new Set(chats.map(chat => new Date(chat.time).setHours(0, 0, 0, 0)))];
const sectionChats = sections.map(section => ({ title: section, data: chats.filter(chat => new Date(chat.time).setHours(0, 0, 0, 0) == section) }))
// useEffect(() => {
// startWebsocket()
// }, [])
const startWebsocket = () => {
ws.onopen = () => {
// on connecting, do nothing but log it to the console
console.log('connected')
}
ws.onmessage = evt => {
// listen to data sent from the websocket server
const message = JSON.parse(evt.data)
// setState({ dataFromServer: message })
console.log(message)
}
ws.onclose = () => {
console.log('disconnected')
// automatically try to reconnect on connection loss
}
}
return (
<View style={styles.container}>
{/* <Text style={styles.title}>Tab One</Text>
<View style={{height: 70, width: 100, backgroundColor: ''}}><TextInput style={{borderColor: 'white', borderWidth: 1, alignSelf: }} onChange={() => console.log('change')}></TextInput></View>
<View style={styles.separator} lightColor="#000" darkColor="rgba(255,0,255,0.1)" />
<EditScreenInfo path="/screens/TabOneScreen.tsx" /> */}
<View style={{ flex: 1, width: '100%' }}>
<View style={{ display: 'flex', flex: 0.9, justifyContent: 'space-between' }}>
{/* <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1}}><Text style={{ fontSize: 50, color: 'white' }}>{detectedText}</Text>
</View> */}
<SectionList
inverted={true}
sections={sectionChats}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => {
// console.log({ item })
return (
<View style={{ margin: 5, padding: 5 }}><Text
style={[{ textAlign: chatDetails.from == item.from ? 'right' : 'left', backgroundColor: 'blue', borderRadius: 5, padding: 5 },
chatDetails.from == item.from ? { marginLeft: 'auto' } : { marginRight: 'auto' }
]}
key={item.time}>{item.message}</Text>
<Text style={{ textAlign: chatDetails.from == item.from ? 'right' : 'left', color: 'gray' }}>{new Date(item.time).toLocaleTimeString().slice(0, 5)}</Text></View>
)
}}
invertStickyHeaders
renderSectionFooter={({ section: { title } }) => {
var date = ""
if (new Date(title).toLocaleDateString() == new Date().toLocaleDateString()) {
date = "Today"
}
// else if (new Date(title).toLocaleDateString() == new Date().setDate(new Date().getDate() - 1).toLocaleDateString()){
// date = "Yesterday"
// }
else {
date = new Date(title).toLocaleDateString()
}
return (
<Text style={styles.header}>{date}</Text>
)
}}
/>
{/* <FlatList
inverted={true}
style={{ alignContent: 'flex-end' }}
data={chats}
keyExtractor={(item) => item.currentTime}
renderItem={({ item }) => {
console.log({ item })
return (
<View style={{ margin: 5, padding: 5 }}><Text
style={[{ textAlign: chatDetails.from == item.from ? 'right' : 'left', backgroundColor: 'blue', borderRadius: 5, padding: 5 },
chatDetails.from == item.from ? { marginLeft: 'auto' } : { marginRight: 'auto' }
]}
key={item.time}>{item.message}</Text>
<Text style={{ textAlign: chatDetails.from == item.from ? 'right' : 'left', color: 'gray' }}>{new Date(item.time).toLocaleTimeString().slice(0, 5)}</Text></View>
)
}} /> */}
</View>
<View style={{ flex: 0.1, backgroundColor: 'rgb(10,10,10)' }}>
<View style={{ flexDirection: 'row', display: 'flex', height: '100%' }}>
<View style={{ flex: 0.8, backgroundColor: 'rgb(10,10,10)', height: '100%' }}></View>
<View style={{ flex: 0.2, backgroundColor: 'rgb(10,10,10)', height: '100%' }}><AudioRecorder setDetectedText={setDetectedText} /></View>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
convoFooter: {
},
header: { textAlign: 'center', backgroundColor: 'gray', marginRight: 'auto', marginLeft: 'auto', padding: 3, borderRadius: 5 }
});
import React, { useState } from 'react'
import { StyleSheet, TextInput } from 'react-native';
import { AudioRecorder } from '../components/AudioRecorder';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { RootTabScreenProps } from '../types';
export default function TabOneScreen({ navigation }: RootTabScreenProps<'TabOne'>) {
const [detectedText, setDetectedText] = useState("")
return (
<View style={styles.container}>
{/* <Text style={styles.title}>Tab One</Text>
<View style={{height: 70, width: 100, backgroundColor: ''}}><TextInput style={{borderColor: 'white', borderWidth: 1, alignSelf: }} onChange={() => console.log('change')}></TextInput></View>
<View style={styles.separator} lightColor="#000" darkColor="rgba(255,0,255,0.1)" />
<EditScreenInfo path="/screens/TabOneScreen.tsx" /> */}
<View style={{ flex: 1, width: '100%' }}>
<View style={{ display: 'flex', flex: 0.9, backgroundColor: 'green' }}>
<View style={{ alignItems: 'center', justifyContent: 'center', height: '100%'}}><Text style={{fontSize: 50, color: 'white'}}>{detectedText}</Text></View>
</View>
<View style={{ flex: 0.1, backgroundColor: 'rgb(10,10,10)'}}>
<View style={{ flexDirection: 'row', display: 'flex', height: '100%' }}>
<View style={{ flex: 0.8, backgroundColor: 'rgb(10,10,10)', height: '100%' }}></View>
<View style={{ flex: 0.2, backgroundColor: 'rgb(10,10,10)', height:'100%'}}><AudioRecorder setDetectedText={setDetectedText} /></View>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
convoFooter: {
}
});
import React from 'react'
import { StyleSheet, TextInput} from 'react-native';
import React, { useState } from 'react'
import { StyleSheet, TextInput } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { TouchableOpacity } from 'react-native';
const LoginForm = ({onLogin}) => {
const LoginForm = ({ onLogin }) => {
var passwordInput
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
return (
<>
<TextInput style={styles.input}
defaultValue={username}
onChange={(e) => {
console.log(username);
setUsername(e.target.value)}}
autoCapitalize="none"
// onSubmitEditing={() => passwordInput.focus()}
onSubmitEditing={() => passwordInput.focus()}
autoCorrect={false}
keyboardType='email-address'
returnKeyType="next"
......@@ -21,6 +28,8 @@ const LoginForm = ({onLogin}) => {
placeholderTextColor='rgba(225,225,225,0.7)' />
<TextInput style={styles.input}
defaultValue={password}
onChange={(e) => setPassword(e.target.value)}
returnKeyType="go"
ref={(input) => passwordInput = input}
placeholder='Password'
......@@ -29,8 +38,11 @@ const LoginForm = ({onLogin}) => {
<TouchableOpacity style={styles.buttonContainer}
// onPress={onButtonPress}
onPress={onLogin}
>
onPress={() => {
console.log({ username, password })
onLogin(username, password)
}}
>
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
</>
......@@ -38,7 +50,7 @@ const LoginForm = ({onLogin}) => {
)
}
export const LoginScreen = ({onLogin}) => {
export const LoginScreen = ({ onLogin }) => {
return (
......@@ -48,7 +60,7 @@ export const LoginScreen = ({onLogin}) => {
</View>
<View style={styles.formContainer}>
<LoginForm onLogin={onLogin}/>
<LoginForm onLogin={onLogin} />
</View>
</View>
......
......@@ -1556,6 +1556,13 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
"@react-native-async-storage/async-storage@~1.15.0":