This repository has been archived by the owner on Jun 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
108 lines (92 loc) · 3.01 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//AuthContext.js
import React, {createContext, useState} from 'react';
import { login, logout } from './api.js'
import * as SecureStore from 'expo-secure-store'
import * as LocalAuthentication from "expo-local-authentication";
const AuthContext = createContext(null);
const {Provider} = AuthContext;
const AuthProvider = ({children}) => {
const [authState, setAuthState] = useState({
accessToken: null,
authenticated: false,
});
const [errorMsg, setErrorMsg] = useState(null)
const setLogout = async () => {
logout(getAccessToken())
setAuthState({
accessToken: null,
authenticated: false,
});
};
const getAccessToken = () => {
return authState.accessToken;
};
const setLogin = async (username, password) => {
const result = await login(username, password)
if(result.access_token) {
setAuthState({
accessToken: result.access_token,
authenticated: true,
})
try {
const jsonLogin = JSON.stringify({
user_name: username,
password: password,
accessToken: result.access_token
})
await SecureStore.setItemAsync('user_info', jsonLogin)
} catch(e) {
setErrorMsg('Error while getting your information')
}
} else {
setErrorMsg(result.message)
}
}
const getStoredUser = async () => {
try {
const jsonValue = await SecureStore.getItemAsync('user_info')
return jsonValue != null ? JSON.parse(jsonValue) : null
} catch(e) {
// read error
setErrorMsg('Your info was compromised, too bad')
}
}
const getBioAuth = async (username, password) => {
const compatible = await LocalAuthentication.hasHardwareAsync()
if (!compatible) {
throw 'This device is not compatible for biometric authentication'
}
const enrolled = await LocalAuthentication.isEnrolledAsync()
if (!enrolled) {
throw 'This device doesnt have biometric authentication enabled'
}
const result = await LocalAuthentication.authenticateAsync()
if (!result.success) {
throw `${result.error} - Authentication unsuccessful`
}
if(result.success) {
const user = await getStoredUser()
if(user) {
await setLogin(user.user_name, user.password)
} else {
setErrorMsg('No touch id')
}
}
}
return (
<Provider
value={{
getAccessToken,
getStoredUser,
getBioAuth,
setLogout,
setLogin,
authState,
setAuthState,
errorMsg,
}}>
{children}
</Provider>
);
};
export { AuthContext, AuthProvider };