forked from expo/auth0-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
107 lines (96 loc) · 2.72 KB
/
main.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
import Expo, { AuthSession } from 'expo';
import React from 'react';
import {
Alert,
Button,
StyleSheet,
Text,
View,
} from 'react-native';
import jwtDecoder from 'jwt-decode';
const auth0ClientId = 'pdnNOE8axmLRPk6opnr6pSbIxmFJxAlA';
const auth0Domain = 'https://charlesvinette.auth0.com';
/**
* Converts an object to a query string.
*/
function toQueryString(params) {
return '?' + Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
class App extends React.Component {
state = {
username: undefined,
};
_loginWithAuth0 = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const result = await AuthSession.startAsync({
authUrl: `${auth0Domain}/authorize` + toQueryString({
client_id: auth0ClientId,
response_type: 'token',
scope: 'openid name',
redirect_uri: redirectUrl,
}),
});
console.log(result);
if (result.type === 'success') {
this.handleParams(result.params);
}
}
_loginWithAuth0Twitter = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const result = await AuthSession.startAsync({
authUrl: `${auth0Domain}/authorize` + toQueryString({
connection: 'twitter',
client_id: auth0ClientId,
response_type: 'token',
scope: 'openid name',
redirect_uri: redirectUrl,
}),
});
console.log(result);
if (result.type === 'success') {
this.handleParams(result.params);
}
}
handleParams = (responseObj) => {
if (responseObj.error) {
Alert.alert('Error', responseObj.error_description
|| 'something went wrong while logging in');
return;
}
const encodedToken = responseObj.id_token;
const decodedToken = jwtDecoder(encodedToken);
const username = decodedToken.name;
this.setState({ username });
}
render() {
return (
<View style={styles.container}>
{this.state.username !== undefined ?
<Text style={styles.title}>Hi {this.state.username}!</Text> :
<View>
<Text style={styles.title}>Example: Auth0 login</Text>
<Button title="Login with Auth0" onPress={this._loginWithAuth0} />
<Text style={styles.title}>Example: Auth0 force Twitter</Text>
<Button title="Login with Auth0-Twitter" onPress={this._loginWithAuth0Twitter} />
</View>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
textAlign: 'center',
marginTop: 40,
},
});
Expo.registerRootComponent(App);