· 6 years ago · Nov 26, 2019, 11:42 PM
1import React, { Component } from 'react'
2import { View, ActivityIndicator, AsyncStorage } from 'react-native'
3import { Text, Input, Button } from 'react-native-elements'
4import Icon from 'react-native-vector-icons/FontAwesome'
5import Axios from 'axios'
6import { urlAPI } from './../../support/url'
7import { connect } from 'react-redux'
8import { onRegisterSuccess } from './../redux/actions/users'
9import { StackActions,NavigationActions } from 'react-navigation'
10import { GoogleSignin, GoogleSigninButton, statusCodes } from '@react-native-community/google-signin';
11import { LoginButton, AccessToken } from 'react-native-fbsdk';
12
13class Register extends Component {
14 state={
15 look:true,
16 username:'',
17 password:'',
18 email:'',
19 confirm_password:'',
20 username_available: null,
21 email_available: null,
22 loadingBtnReg:false,
23 check_storage: false,
24 userInfo: ''
25 }
26
27 initUser = (token) => {
28 fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + token)
29 .then((response) => response.json())
30 .then((json) => {
31 // Some user object has been set up somewhere, build that user here
32 // user.name = json.name
33 // user.id = json.id
34 // user.user_friends = json.friends
35 // user.email = json.email
36 // user.username = json.name
37 // user.loading = false
38 // user.loggedIn = true
39 // user.avatar = setAvatar(json.id)
40 console.log(json)
41 })
42 .catch(() => {
43
44 // console.log(user)
45 console.log('ERROR GETTING DATA FROM FACEBOOK')
46 })
47 }
48
49 onCheckUsername = () => {
50 console.log('trigered')
51 Axios.post('https://apiinstagrinjc.herokuapp.com/auth/check-username',{username : this.state.username})
52 .then((res) => {
53 if(res.data.error){
54 // munculin
55 }else{
56 this.setState({username_available:res.data.available})
57 }
58 })
59 .catch((err) => {
60 console.log(err)
61 })
62
63 }
64
65 onCheckEmail = () => {
66 console.log('trigered')
67 Axios.post('https://apiinstagrinjc.herokuapp.com/auth/check-email',{email : this.state.email})
68 .then((res) => {
69 if(res.data.error){
70 // munculin
71 }else{
72 console.log(this.state.email_available)
73 this.setState({email_available:res.data.available})
74 }
75 })
76 .catch((err) => {
77 console.log(err)
78 })
79
80 }
81 onBtnRegClick = () => {
82 this.setState({loadingBtnReg : true})
83 var { username, password, email } = this.state
84 var date = new Date()
85 if(username && password && email){
86 Axios.post(urlAPI + 'auth/register',{
87 username,
88 password,
89 email,
90 created_at: `${date.getDate()}-${date.getMonth()}-${date.getFullYear().toString().slice(-2)} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
91 })
92 .then((res) => {
93 console.log(res.data)
94 if(res.data.error){
95 alert(res.data.message)
96 }
97 else{
98 AsyncStorage.setItem('data',JSON.stringify({email,username}),(err) => {
99 if(err) return alert(err.message)
100 this.props.onRegisterSuccess({email,username})
101 alert(res.data.message)
102 })
103 }
104 }
105 )
106 .catch((err)=> {
107 console.log(err)
108 })
109
110 }
111 // check username
112 // check email
113 // ambil data dari semua form
114 // kirim data ke API
115 // redirect ke home
116 }
117 signIn = async () => {
118 try {
119 await GoogleSignin.hasPlayServices();
120 const userInfo = await GoogleSignin.signIn();
121 // this.setState({ userInfo });
122 console.log(userInfo)
123 } catch (error) {
124 if (error.code === statusCodes.SIGN_IN_CANCELLED) {
125 // user cancelled the login flow
126 } else if (error.code === statusCodes.IN_PROGRESS) {
127 // operation (e.g. sign in) is in progress already
128 } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
129 // play services not available or outdated
130 } else {
131 // some other error happened
132 }
133 }
134};
135
136 componentDidMount(){
137
138 GoogleSignin.configure({
139 scopes: ['https://www.googleapis.com/auth/drive.readonly'], // what API you want to access on behalf of the user, default is email and profile
140 webClientId: '198648817763-2pcfr7i80voh3sv8d652m7k3hjob3toc.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
141 offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
142 hostedDomain: '', // specifies a hosted domain restriction
143 loginHint: '', // [iOS] The user's ID, or email address, to be prefilled in the authentication UI if possible. [See docs here](https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in.html#a0a68c7504c31ab0b728432565f6e33fd)
144 forceConsentPrompt: true, // [Android] if you want to show the authorization prompt at each login.
145 accountName: '', // [Android] specifies an account name on the device that should be used
146 iosClientId: '<FROM DEVELOPER CONSOLE>', // [iOS] optional, if you want to specify the client ID of type iOS (otherwise, it is taken from GoogleService-Info.plist)
147 });
148 // console.log(this.state.userInfo)
149 // console.disableYellowBox = true
150 AsyncStorage.getItem('data')
151 .then((data) => {
152 if(data){
153 var obj_data = JSON.parse(data)
154 this.props.onRegisterSuccess(obj_data)
155 this.setState({check_storage : true})
156 }
157 this.setState({check_storage : true})
158 console.log(obj_data)
159 })
160 .catch((err) => {
161
162 })
163 }
164
165
166 componentDidUpdate(){
167 if(this.props.User){
168 const reset_stack = StackActions.reset({
169 index : 0,
170 actions : [NavigationActions.navigate({routeName:'home'})]
171 })
172 this.props.navigation.dispatch(reset_stack)
173 }
174 }
175 render() {
176 if(this.state.check_storage === false){
177 return(
178 <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
179 <Text h2>
180 Insta
181 </Text>
182 <ActivityIndicator size='small' />
183 </View>
184 )
185}
186 return (
187 <View style={{flex:1, justifyContent:'center'}}>
188 <Text h1 style={{alignSelf:'center'}} > Register </Text>
189 <Text h6 style={{marginTop:100}}> Register Here </Text>
190 <View style={{marginHorizontal:20}}>
191{/*--------------------------------------------------------- INPUT USERNAME FORM ------------------------------------------------------*/}
192 < Input
193 onChangeText={(username) => this.setState({username})}
194 onBlur={this.onCheckUsername}
195 placeholder = ' Input username'
196 rightIcon={
197 this.state.username_available == null?
198 null: this.state.username_available === true?
199 <Icon
200 name='check'
201 size={24}
202 color='green'
203 style={{paddingLeft:10}}
204 /> :
205 <Icon
206 name='times'
207 size={24}
208 color='red'
209 style={{paddingLeft:10}}
210 />
211 }
212 leftIcon = {
213 <Icon
214 name = 'user'
215 size = {24}
216 style = 'regular'
217
218 />
219 }
220 />
221{/* ------------------------------------------------------------INPUT EMAIL FORM------------------------------------------------------------- */}
222 < Input
223 onChangeText={(email) => this.setState({email})}
224 onBlur={this.onCheckEmail}
225 placeholder = ' Input email'
226 rightIcon={
227 this.state.email_available == null?
228 null: this.state.email_available === true?
229 <Icon
230 name='check'
231 size={24}
232 color='green'
233 style={{paddingLeft:10}}
234 /> :
235 <Icon
236 name='times'
237 size={24}
238 color='red'
239 style={{paddingLeft:10}}
240 />
241 }
242 leftIcon = {
243 <Icon
244 name = 'envelope'
245 size = {24}
246 style = 'regular' />
247 }
248 />
249{/* ------------------------------------------------------------INPUT PASSWORD FORM--------------------------------------------------------------- */}
250 < Input
251 onChangeText={(password) => this.setState({password})}
252 secureTextEntry={this.state.look}
253 placeholder = ' Input password'
254 leftIcon = {
255 <Icon
256 name = 'key'
257 size = {24}
258 style = 'light' />
259 }
260 rightIcon ={
261 <Icon
262 name = 'eye'
263 onPress = {() => this.setState({look : !this.state.look})}
264 />
265 }
266 />
267{/* ------------------------------------------------------------CONFIRM PASSWORD FORM------------------------------------------------------------- */}
268 < Input
269 onChangeText={(confirm_password) => this.setState({confirm_password})}
270 secureTextEntry={this.state.look}
271 placeholder = ' Confirm password'
272 errorMessage=
273 {
274 (this.state.confirm_password !=='') && (this.state.password !== this.state.confirm_password) ?
275 'password doest match' : null
276 }
277 leftIcon = {
278 <Icon
279 name = 'key'
280 size = {24}
281 style = 'light' />
282 }
283 rightIcon ={
284 <Icon
285 name = 'eye'
286 onPress = {() => this.setState({look : !this.state.look})}
287 />
288 }
289 />
290
291 </View>
292{/* ------------------------------------------------------REGISTER BUTTON-------------------------------------------------------------- */}
293
294 <View style={{marginHorizontal:20, marginTop:20}}>
295 <Button
296 title=" Register"
297 loading={this.state.loadingBtnReg}
298 onPress={this.onBtnRegClick}
299 // onBtnRegClick
300 // buttonStyle={{backgroundColor:'blue'}}
301 />
302
303 </View>
304
305 <View style={{flex:1, flexDirection:"row", marginHorizontal: 20, marginTop: 10}}>
306 <View style={{flex:1, marginHorizontal:5}}>
307 <Button
308 icon={
309 <Icon
310 name="facebook"
311 size={10}
312 color="white"
313 />
314 }
315 title=" login via facebook"
316 buttonStyle={{backgroundColor:'#3b5998'}}
317 />
318
319 </View>
320 <View style={{flex:1, marginHorizontal:5}}>
321 <Button style={{color:'red'}}
322 title = "Solid Button"
323 color='green'
324 icon={
325 <Icon
326 name="google"
327 size={10}
328 color="white"
329 />
330 }
331 title=" login via google"
332 buttonStyle={{backgroundColor:'#de5246'}}
333 onPress={this.signIn}
334 />
335 {/* <GoogleSigninButton
336 style={{ width: 192, height: 48 }}
337 size={GoogleSigninButton.Size.Wide}
338 color={GoogleSigninButton.Color.Dark}
339 onPress={this._signIn}
340 disabled={this.state.isSigninInProgress} /> */}
341
342 </View>
343 </View>
344{/* --------------------------------------------REGISTER BUTTON FACEBOOK-------------------------------------------------- */}
345 <View>
346 <LoginButton
347 onLoginFinished={
348 (error, result) => {
349 if (error) {
350 console.log("login has error: " + result.error);
351 } else if (result.isCancelled) {
352 console.log("login is cancelled.");
353 } else {
354 AccessToken.getCurrentAccessToken().then(
355 (data) => {
356 this.initUser(data.accessToken.toString())
357 const {
358 accessToken
359 } = data
360 // this.initUser(accessToken)
361 // console.log(data)
362
363 }
364 )
365 }
366 }
367 }
368 onLogoutFinished={() => console.log("logout.")}/>
369 </View>
370 <View style={{flexDirection:'row', justifyContent:'center', marginTop:10}}>
371 <Text> Already have an account?</Text>
372 <Text
373 style={{fontWeight:'bold'}}
374 onPress={()=> this.props.navigation.navigate('login')}
375 > Login here
376 </Text>
377 </View>
378
379
380 </View>
381 )
382 }
383}
384
385const mapStateToProps = (state) => {
386 return {
387 User: state.users.username
388 }
389}
390export default connect(mapStateToProps,{onRegisterSuccess})(Register);