Browse Source

Persisting user data in app

master
GabrielTrettel 4 years ago
parent
commit
0e09cca853
  1. 31
      src/App.js
  2. 6
      src/app/api/auth.js
  3. 30
      src/app/auth/context.js
  4. 29
      src/app/auth/storage.js
  5. 10
      src/app/screens/AccountScreen.js
  6. 10
      src/app/screens/LoginScreen.js
  7. 2
      src/package.json

31
src/App.js

@ -1,4 +1,4 @@
import React, { useState, useContext } from "react";
import React, { useState, useContext, useEffect } from "react";
import { NavigationContainer } from "@react-navigation/native"; import { NavigationContainer } from "@react-navigation/native";
import navigationTheme from "./app/navigation/navigationTheme"; import navigationTheme from "./app/navigation/navigationTheme";
@ -7,23 +7,38 @@ import openDatabase from "./app/database/database-connection";
import initDatabase from "./app/database/database-init"; import initDatabase from "./app/database/database-init";
import FlashMessage from "react-native-flash-message"; import FlashMessage from "react-native-flash-message";
import { createStackNavigator } from "@react-navigation/stack";
import AppNavigator from "./app/navigation/AppNavigator"; import AppNavigator from "./app/navigation/AppNavigator";
import EventLocationProvider from "./app/context/EventLocationContext"; import EventLocationProvider from "./app/context/EventLocationContext";
import CurrentLocationProvider from "./app/context/CurrentLocationContext"; import CurrentLocationProvider from "./app/context/CurrentLocationContext";
import AuthNavigator from "./app/navigation/AuthNavigator"; import AuthNavigator from "./app/navigation/AuthNavigator";
import { AuthContextProvider } from "./app/auth/context";
import { AuthContext } from "./app/auth/context";
import authStorage from "./app/auth/storage";
import jwtDecode from "jwt-decode";
export default function App() { export default function App() {
const [user, AuthProvider] = AuthContextProvider();
console.log("asidhisdhaisu " + JSON.stringify(user));
const [user, setUser] = useState();
const restoreToken = async () => {
const token = await authStorage.getToken();
if (!token) return;
return setUser(jwtDecode(token));
};
useEffect(() => {
restoreToken();
}, []);
global.userDataBase = openDatabase(); global.userDataBase = openDatabase();
initDatabase(global.userDataBase); initDatabase(global.userDataBase);
const Stack = createStackNavigator();
return ( return (
<AuthProvider>
<AuthContext.Provider
value={{
user,
setUser,
}}
>
<CurrentLocationProvider> <CurrentLocationProvider>
<EventLocationProvider> <EventLocationProvider>
<NavigationContainer theme={navigationTheme}> <NavigationContainer theme={navigationTheme}>
@ -32,6 +47,6 @@ export default function App() {
</NavigationContainer> </NavigationContainer>
</EventLocationProvider> </EventLocationProvider>
</CurrentLocationProvider> </CurrentLocationProvider>
</AuthProvider>
</AuthContext.Provider>
); );
} }

6
src/app/api/auth.js

@ -2,9 +2,9 @@ function login(name, password) {
// NOTE: Change to API in future // NOTE: Change to API in future
return { return {
name: "Fulano De Tal",
email: "fulano@detal.com",
ID: "1",
ok: true,
data:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiRnVsYW5vIGRlIFRhbCIsImVtYWlsIjoiZnVsYW5vLmRlLnRhbEBib2wuY29tLmJyIiwiSUQiOiIxIn0.5435hPLABKVcejsZokCGG77G6xjBUcKAU_lAjELzT3g",
}; };
} }

30
src/app/auth/context.js

@ -2,21 +2,21 @@ import React, { useState } from "react";
const AuthContext = React.createContext(); const AuthContext = React.createContext();
function AuthContextProvider() {
const [user, setUser] = useState();
// function AuthContextProvider() {
// const [user, setUser] = useState();
const provider = ({ children }) => (
<AuthContext.Provider
value={{
user,
setUser,
}}
>
{children}
</AuthContext.Provider>
);
// const provider = ({ children }) => (
// <AuthContext.Provider
// value={{
// user,
// setUser,
// }}
// >
// {children}
// </AuthContext.Provider>
// );
return [user, provider];
}
// return [user, setUser, provider];
// }
export { AuthContextProvider, AuthContext };
export { AuthContext };

29
src/app/auth/storage.js

@ -0,0 +1,29 @@
import * as SecureStore from "expo-secure-store";
const key = "authToke";
const setToken = async (authToken) => {
try {
await SecureStore.setItemAsync(key, authToken);
} catch (error) {
console.log("Error while storing authToken");
}
};
const getToken = async () => {
try {
return await SecureStore.getItemAsync(key);
} catch (error) {
console.log("Error while gettig authToken");
}
};
const removeToken = async () => {
try {
await SecureStore.deleteItemAsync(key);
} catch (e) {
console.log("Error while removing authToken");
}
};
export default { setToken, getToken, removeToken };

10
src/app/screens/AccountScreen.js

@ -3,6 +3,12 @@ import { Text, Button } from "react-native";
import Screen from "../components/Screen"; import Screen from "../components/Screen";
import InDevelopment from "../components/InDevelopment"; import InDevelopment from "../components/InDevelopment";
import { AuthContext } from "../auth/context"; import { AuthContext } from "../auth/context";
import authStorage from "../auth/storage";
function handleLogOut(setUser) {
setUser(null);
authStorage.removeToken();
}
function AccountScreen(props) { function AccountScreen(props) {
const { user, setUser } = useContext(AuthContext); const { user, setUser } = useContext(AuthContext);
@ -18,7 +24,9 @@ function AccountScreen(props) {
<Button <Button
style={{ paddingTop: 10 }} style={{ paddingTop: 10 }}
title="Logout" title="Logout"
onPress={() => setUser(null)}
onPress={() => {
handleLogOut(setUser);
}}
/> />
{/* <InDevelopment /> */} {/* <InDevelopment /> */}

10
src/app/screens/LoginScreen.js

@ -12,7 +12,9 @@ import colors from "../config/colors";
import { dimensions } from "../config/dimensions"; import { dimensions } from "../config/dimensions";
import { TouchableNativeFeedback } from "react-native-gesture-handler"; import { TouchableNativeFeedback } from "react-native-gesture-handler";
import login from "../api/auth"; import login from "../api/auth";
import jwdDecode from "jwt-decode";
import { AuthContext } from "../auth/context"; import { AuthContext } from "../auth/context";
import authStorage from "../auth/storage";
const phoneRegex = RegExp( const phoneRegex = RegExp(
/^\(?[\(]?([0-9]{2})?\)?[)\b]?([0-9]{4,5})[-. ]?([0-9]{4})$/ /^\(?[\(]?([0-9]{2})?\)?[)\b]?([0-9]{4,5})[-. ]?([0-9]{4})$/
@ -33,10 +35,14 @@ export default function LoginScreen(props) {
const handleSubmit = (name, password, setLoginFailed) => { const handleSubmit = (name, password, setLoginFailed) => {
const result = login(name, password); const result = login(name, password);
console.log(result);
if (!result.ok) return setLoginFailed(true);
if (!result) return setLoginFailed(true);
setLoginFailed(false); setLoginFailed(false);
authContext.setUser(result);
const user = jwdDecode(result.data);
authContext.setUser(user);
console.log(user);
authStorage.setToken(result.data);
}; };
const [loginFailed, setLoginFailed] = useState(false); const [loginFailed, setLoginFailed] = useState(false);

2
src/package.json

@ -26,9 +26,11 @@
"expo-file-system": "~9.2.0", "expo-file-system": "~9.2.0",
"expo-image-picker": "~9.1.1", "expo-image-picker": "~9.1.1",
"expo-location": "~9.0.0", "expo-location": "~9.0.0",
"expo-secure-store": "~9.2.0",
"expo-sqlite": "~8.4.0", "expo-sqlite": "~8.4.0",
"expo-status-bar": "^1.0.3", "expo-status-bar": "^1.0.3",
"formik": "^2.2.6", "formik": "^2.2.6",
"jwt-decode": "^3.1.2",
"moment": "^2.29.1", "moment": "^2.29.1",
"react": "16.13.1", "react": "16.13.1",
"react-dom": "16.13.1", "react-dom": "16.13.1",

Loading…
Cancel
Save