-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
133 lines (107 loc) · 2.68 KB
/
App.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import React, { Component } from 'react'
import { StyleSheet, View, Button, Text } from 'react-native'
import RNAccountKit from 'react-native-facebook-account-kit'
const API_URL = 'http://localhost:3000'
export default class App extends Component {
state = {
jwt: null,
me: null,
}
componentDidMount() {
RNAccountKit.configure({
responseType: 'code',
initialPhoneCountryPrefix: '+54',
defaultCountry: 'AR',
})
}
handleLoginButtonPress = async () => {
try {
const payload = await RNAccountKit.loginWithPhone()
if (!payload) {
return
}
const { code } = payload
await this.getJWT(code)
} catch (err) {
alert('Facebook auth failed')
}
}
handleLogoutPress = () => this.setState({ jwt: null, me: null })
getJWT = async code => {
const url = `${API_URL}/auth?code=${code}`
console.warn(url)
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
console.warn(res)
if (!res.ok) {
alert('Failed to get JWT')
return
}
const { jwt } = await res.json()
this.setState({ jwt })
}
handleGetMePress = async () => {
const url = `${API_URL}/me`
const { jwt } = this.state
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${jwt}`,
'Content-Type': 'application/json',
},
})
if (res.status === 403) {
alert('User unauthorized')
return
} else if (!res.ok) {
alert('Failed to get profile')
return
}
const me = await res.json()
this.setState({ me })
}
render() {
const { jwt, me } = this.state
const authenticated = !!jwt
const phone = !!me && me.phone
return (
<View style={styles.container}>
{!authenticated && <Button title="Login" onPress={this.handleLoginButtonPress} />}
{authenticated && (
<View style={styles.container}>
<Text style={styles.title}>Welcome!</Text>
<Text style={styles.jwt}>{jwt}</Text>
{phone && <Text style={styles.phone}>Phone: {phone.number}</Text>}
<Button title="Get Profile" onPress={this.handleGetMePress} />
<Button title="Logout" onPress={this.handleLogoutPress} />
</View>
)}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontWeight: 'bold',
padding: 20,
fontSize: 20,
},
phone: {
padding: 20,
fontSize: 14,
},
phone: {
padding: 20,
fontSize: 14,
},
})