-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserContext.js
742 lines (684 loc) · 20.1 KB
/
UserContext.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
import React from 'react';
import Api from './constants/Api';
import {AsyncStorage} from 'react-native';
import { Notifications } from 'expo';
import * as Permissions from 'expo-permissions';
const UserContext = React.createContext();
class UserProvider extends React.Component {
state = {
isAuth: false,
userToken: null,
fbData: null,
userId: null,
perfil: null,
ofertas: [],
ofertasComLike: [],
listaDesejos: [],
cupons: [],
cuponsUtilizados: [],
isLoadingUser: true
}
constructor() {
super()
this.ativaCupom = this.ativaCupom.bind(this)
this.atualizaCupons = this.atualizaCupons.bind(this)
this.atualizaCuponsUtilizados = this.atualizaCuponsUtilizados.bind(this)
this.atualizaOfertas = this.atualizaOfertas.bind(this)
this.buscaCupom = this.buscaCupom.bind(this)
this.faleConosco = this.faleConosco.bind(this)
this.getCupomById = this.getCupomById.bind(this)
this.getDadosMeuPerfil = this.getDadosMeuPerfil.bind(this)
this.getOfertaById = this.getOfertaById.bind(this)
this.atualizaListaDesejos = this.atualizaListaDesejos.bind(this)
this.getOfertasComLike = this.getOfertasComLike.bind(this)
this.atualizaOfertasComLike = this.atualizaOfertasComLike.bind(this)
this.login = this.login.bind(this)
this.logout = this.logout.bind(this)
this.receberNotificacoes = this.receberNotificacoes.bind(this)
this.setDadosMeuPerfil = this.setDadosMeuPerfil.bind(this)
this.setFacebookToken = this.setFacebookToken.bind(this)
this.setPerfil = this.setPerfil.bind(this)
this.setToken = this.setToken.bind(this)
this.signup = this.signup.bind(this)
this.toggleDesejo = this.toggleDesejo.bind(this)
}
async loadFromLocalStorage() {
if(!this.state.isAuth) {
const userToken = await AsyncStorage.getItem('userToken')
const userId = await AsyncStorage.getItem('userId')
if(userToken && userId) {
this.setState({userToken, userId, isAuth: true})
if(!this.state.perfil) {
const perfil = JSON.parse(await AsyncStorage.getItem('perfil'))
const ofertas = JSON.parse(await AsyncStorage.getItem('ofertas'))
const cupons = JSON.parse(await AsyncStorage.getItem('cupons'))
this.setState({perfil, ofertas, cupons})
}
}
}
}
componentDidMount() {
this.atualizaInfosUser()
}
async atualizaInfosUser() {
await this.loadFromLocalStorage()
await this.atualizaCuponsUtilizados()
await this.atualizaListaDesejos()
await this.atualizaOfertas()
await this.setState({ isLoadingUser: false })
}
async signup(login, passwd) {
const params = JSON.stringify({email: login, password: passwd})
const res = await fetch(Api.url+'/pessoas', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: params
})
.then(response => {
return response.json().then((jsonRes) => {
if(jsonRes.success) {
this.setToken(jsonRes.data.token.token)
this.setPerfil(jsonRes.data.pessoa)
this.receberNotificacoes()
}
return jsonRes
})
})
.catch(error => console.log('Signup error', error));
return res;
}
async login(user,passwd) {
const res = await fetch(Api.url+'/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email: user, password: passwd})
})
.then(response => {
return response.json().then((jsonRes) => {
if(jsonRes.success) {
this.setToken(jsonRes.data.token.token)
this.setPerfil(jsonRes.data.pessoa)
this.receberNotificacoes()
}
return jsonRes
})
})
.catch(erro => console.log('Erro no login',erro))
return res;
}
async recoverPassword(email) {
const res = await fetch(Api.url+'/password/reset', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email: email})
})
.then(response => response.json())
.catch(erro => console.log('Erro no recoverPassword',erro))
if(res) {
return res;
}
}
logout() {
AsyncStorage.clear();
this.setState({
isAuth: false,
userToken: null,
fbData: null,
userId: null,
perfil: null,
ofertas: [],
cupons: [],
listaDesejos: [],
cuponsUtilizados: [],
});
}
async setToken(userToken) {
this.setState({
isAuth: true,
userToken
})
await AsyncStorage.setItem('userToken', userToken.toString());
await AsyncStorage.setItem('isAuth', "true");
}
async setFacebookToken(fbToken) {
if(!fbToken || fbToken === '') {
return null
}
// Get the user's name using Facebook's Graph API
const response = await fetch('https://graph.facebook.com/me?fields=name,email&access_token=' + fbToken);
const fbData = await response.json()
fbData.accessToken = fbToken
this.setState({
fbData
})
await AsyncStorage.setItem('fbData', JSON.stringify(fbData));
const res = await this.getAPITokenFromFacebookData(fbData)
.then((response) => {
if(response && response.success) {
const loginData = response.data
const perfil = loginData.pessoa
const userToken = loginData.token
this.setToken(userToken)
this.setPerfil(perfil)
this.receberNotificacoes()
return userToken
}
return null
})
.catch((e) => {
console.log("Error on facebook login", e)
return null
});
return res
}
async setPerfil(perfil) {
let perfilCompleto = this.null2emptystring(perfil)
// Inclui o primeiro nome no obj de perfil
if(perfilCompleto.nome && perfilCompleto.nome !== '') {
const nomeSimples = perfilCompleto.nome.split(' ')[0];
perfilCompleto.nomeSimples = nomeSimples
}
this.setState({
userId: perfil.id,
perfil: perfilCompleto
})
await AsyncStorage.setItem('userId', perfil.id.toString());
await AsyncStorage.setItem('perfil', JSON.stringify(perfil));
}
async setCupons(cupons) {
await this.setState({
cupons
})
await AsyncStorage.setItem('cupons', JSON.stringify(cupons));
}
async setOfertas(ofertas) {
await this.setState({
ofertas
})
await AsyncStorage.setItem('ofertas', JSON.stringify(ofertas));
}
async setListaDesejos(listaDesejos) {
await this.setState({
listaDesejos
})
await AsyncStorage.setItem('listaDesejos', JSON.stringify(listaDesejos));
}
async getAPITokenFromFacebookData(fbData) {
const bodyRequest = {
email: fbData.email,
social_token: fbData.accessToken,
nome: fbData.name
}
const res = await fetch(Api.url+'/login/facebook', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyRequest)
})
.then(response => response.json())
.catch(erro => console.error('Erro no login',erro))
return res;
}
async atualizaOfertas(userToken) {
if(!userToken) {
userToken = this.state.userToken
}
let auth = null
if(userToken) {
auth = {
credentials: 'include',
headers: {
'Authorization': 'Bearer '+userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
}
const res = await fetch(Api.url+'/ofertas', auth)
.then(response => response.json())
.catch(erro => console.log('Erro no atualizaOfertas',erro))
if(res && res.success) {
const ofertas = res.data;
await this.setOfertas(ofertas)
await this.atualizaOfertasComLike()
return ofertas
}
if(res) {
throw res.message
}
}
async getOfertasComLike() {
const listaDesejos = this.state.listaDesejos
const idsOfertas = listaDesejos ? listaDesejos.map((oferta)=> oferta.id) : []
console.log("idsOfertas", idsOfertas)
if(this.state.ofertas === null) {
await this.atualizaOfertas()
}
const ofertasComLike = this.state.ofertas.map((oferta) => {
if(idsOfertas.indexOf(oferta.id) !== -1) {
oferta.liked = true
} else {
oferta.liked = false
}
return oferta
})
return ofertasComLike
}
async atualizaOfertasComLike() {
const listaDesejos = this.state.listaDesejos
const idsListaDesejos = listaDesejos ? listaDesejos.map((oferta)=> oferta.id) : []
const ofertasComLike = this.state.ofertas.map((oferta) => {
if(idsListaDesejos.indexOf(oferta.id) !== -1) {
oferta.liked = true
} else {
oferta.liked = false
}
return oferta
})
this.setState({ofertasComLike})
}
async getOfertaById(idOferta) {
if(!this.state.ofertas) {
await this.atualizaOfertas()
}
const oferta = this.state.ofertas.find((oferta) => {
return Number(oferta.id) === Number(idOferta)
})
return oferta
}
async atualizaCupons() {
const userToken = this.state.userToken
let auth = null
if(userToken) {
auth = {
credentials: 'include',
headers: {
'Authorization': 'Bearer '+userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
}
await fetch(Api.url+'/cupons', auth)
.then(response => {
response.json()
.then(res => {
if(res && res.success) {
const cupons = res.data
this.setCupons(cupons)
}
})
})
.catch(erro => console.log('Erro no atualizacupons',erro))
}
async atualizaCuponsUtilizados() {
if(!this.state.userId) {
return []
}
const res = await fetch(Api.url+'/pessoas/'+this.state.userId+'/cupons', {
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json().then((jsonRes) => {
if(jsonRes.success) {
const cuponsUtilizados = jsonRes.data
const cuponsFormatados = cuponsUtilizados.map(cupom => {
let cupomFormatado = Object.assign({},cupom,{codigo_unico: cupom.codigo_unico});
return cupomFormatado
})
this.setState({cuponsUtilizados: cuponsFormatados})
return cuponsFormatados
} else {
console.log(jsonRes.message)
}
})
})
.catch(error => {
console.log('Atualiza cupons utilizados error', error)
this.logout();
});
return res;
}
async getCupomById(cupomId) {
if(!cupomId) {
const msgErro = { erro: "Cupom não encontrado." }
throw msgErro
}
const res = await fetch(Api.url+'/cupons/'+cupomId,
{
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken
}
}
)
.then(response => response.json())
.catch(erro => {
console.log('Erro no buscaCupom',erro)
throw erro
})
if(!res) {
const msgErro = { erro: "Cupom não encontrado." }
throw msgErro
}
if(res.success) {
const cupom = res.data
return cupom
} else {
throw res.message
}
}
async buscaCupom(codigoCupom) {
if(!codigoCupom) {
const msgErro = { erro: "Sem código cupom" }
throw msgErro
}
const res = await fetch(Api.url+'/cupons/encrypt/'+codigoCupom,
{
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken
}
}
)
.then(response => response.json())
.catch(erro => console.log('Erro no buscaCupom',erro))
if(!res) {
return
}
if(res.success) {
const cupom = res.data
return cupom
} else {
throw res.message
}
}
async ativaCupom(idCupom) {
if(!this.state.userId || !idCupom) {
return {}
}
const params = JSON.stringify({
pessoa_id: this.state.userId
})
const res = await fetch(Api.url+'/cupons/'+idCupom+'/ativar', {
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: params
})
.then(response => {
return response.json().then((jsonRes) => {
if(jsonRes.success) {
const cupomAtivo = jsonRes.data
return cupomAtivo
} else {
throw jsonRes.message
}
})
})
.catch(error => console.log('Ativa cupom error', error));
return res;
}
async toggleDesejo(oferta_id) {
console.log("liked clicked na oferta de id ", oferta_id)
if(!this.state.userId) {
return Promise.reject()
}
const res = await fetch(Api.url+'/pessoas/'+this.state.userId+'/ofertas', {
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"oferta_id":oferta_id})
})
.then(response => response.json())
.catch(erro => Promise.reject(erro))
if(!res) {
throw { error: "sem resposta"}
}
if(res.success) {
const ofertas = res.data.ofertas
this.setListaDesejos(ofertas)
this.atualizaOfertasComLike()
return ofertas
} else {
throw res.message
}
}
async atualizaListaDesejos() {
if(!this.state.userId) {
return []
}
const res = await fetch(Api.url+'/pessoas/'+this.state.userId+'/ofertas',
{
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken
}
}
)
.then(response => response.json())
.catch(erro => console.log('Erro no getListaDesejos',erro))
if(!res) {
return
}
if(res.success) {
const ofertas = res.data.ofertas
await this.setListaDesejos(ofertas)
return ofertas
} else {
throw res.message
}
}
async getDadosMeuPerfil() {
const res = await fetch(Api.url+'/pessoas/'+this.state.userId,
{
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken
}
}
)
.then(response => response.json())
.catch(erro => console.log('Erro no getDadosMeuPerfil',erro))
if(!res) {
return
}
if(res.success) {
const meuPerfil = res.data
this.setPerfil(meuPerfil)
return meuPerfil
} else {
throw res.message
}
}
async setDadosMeuPerfil(perfil) {
const res = await fetch(Api.url+'/pessoas/'+this.state.userId, {
method: 'PATCH',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+this.state.userToken
},
body: JSON.stringify(perfil)
})
.then(response => response.json())
.catch(erro => console.log('Erro no setDados',erro))
if(res.errors) {
throw res.errors
}
return res;
}
async faleConosco(nome, contato, assunto, mensagem) {
const params = JSON.stringify({
nome: nome,
assunto,
mensagem,
contato
})
const options = this.state.userToken ?
{
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+this.state.userToken,
'Content-Type': 'application/json'
},
body: params
} :
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: params
}
const res = await fetch(Api.url+'/fale_conoscos', options)
.then(response => {
return response.json().then((jsonRes) => {
return jsonRes
})
})
.catch(error => console.log('Erro no fale conosco', error));
return res;
}
null2emptystring = (obj) => {
const objRes = obj
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if(!obj[prop]) {
objRes[prop] = ''
}
}
}
return objRes
}
async receberNotificacoes() {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
// only ask if permissions have not already been determined, because
// iOS won't necessarily prompt the user a second time.
if (existingStatus !== 'granted') {
// Android remote notification permissions are granted during the app
// install, so this will only ask on iOS
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
// Stop here if the user did not grant permissions
if (finalStatus !== 'granted') {
console.log("notification permission not granted")
return Promise.reject(finalStatus)
}
// Get the token that uniquely identifies this device
let token = await Notifications.getExpoPushTokenAsync();
return this.enviaExpoToken(token)
}
enviaExpoToken = async (token) => {
console.log('userId:', this.state.userId, 'expo token:', token);
const res = await fetch(Api.url+'/exponent/devices/subscribe', {
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer '+this.state.userToken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"expo_token":token})
})
.then(response => response.json())
.catch(erro => console.log('Erro no enviaExpoToken',erro))
if(!res) {
return Promise.reject()
}
if(res.status === 'succeeded') {
return Promise.resolve(res)
} else {
console.log("erro no enviaExpoToken", res)
}
}
// Utility function
// Chrome doesnt support base64String
urlBase64ToUint8Array = (base64String) => {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
render() {
return (
<UserContext.Provider
value={{
ativaCupom: this.ativaCupom,
atualizaCupons: this.atualizaCupons,
atualizaCuponsUtilizados: this.atualizaCuponsUtilizados,
atualizaListaDesejos: this.atualizaListaDesejos,
atualizaOfertas: this.atualizaOfertas,
atualizaOfertasComLike: this.atualizaOfertasComLike,
buscaCupom: this.buscaCupom,
cupons: this.state.cupons,
cuponsUtilizados: this.state.cuponsUtilizados,
faleConosco: this.faleConosco,
getCupomById: this.getCupomById,
getDadosMeuPerfil: this.getDadosMeuPerfil,
getOfertaById: this.getOfertaById,
getOfertasComLike: this.getOfertasComLike,
isAuth: this.state.isAuth,
isLoadingUser: this.state.isLoadingUser,
listaDesejos: this.state.listaDesejos,
login: this.login,
logout: this.logout,
ofertas: this.state.ofertas,
ofertasComLike: this.state.ofertasComLike,
perfil: this.state.perfil,
receberNotificacoes: this.receberNotificacoes,
recoverPassword: this.recoverPassword,
setDadosMeuPerfil: this.setDadosMeuPerfil,
setFacebookToken: this.setFacebookToken,
setPerfil: this.setPerfil,
setToken: this.setToken,
signup: this.signup,
toggleDesejo: this.toggleDesejo,
userToken: this.state.userToken,
}}
>
{this.props.children}
</UserContext.Provider>
)
}
}
const UserConsumer = UserContext.Consumer
export { UserProvider, UserConsumer }