-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAuthService.js
More file actions
83 lines (71 loc) · 1.93 KB
/
Copy pathAuthService.js
File metadata and controls
83 lines (71 loc) · 1.93 KB
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
var AsyncStorage = require ('react-native').AsyncStorage;
var _ = require ('lodash');
const authKey = 'user';
class AuthService {
getAuthInfo(cb){
AsyncStorage.multiGet([authKey], (err, val)=> {
if(err){
return cb(err);
}
if(!val){
return cb();
}
var zippedObj = _.zipObject(val);
if(!zippedObj['userId']){
return cb();
}
var authInfo = {
user:JSON.parse(zippedObj[authKey])
}
return cb(null, authInfo);
})
}
login(creds, cb){
fetch('https://portfolioio.herokuapp.com/api/users/signin', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(creds)
})
.then((response) => {
response.json()
.then((data) => {
if(data.token) {
return data;
}
throw {
nouser: data=='User not found',
badpassword: data=='Wrong password',
}
})
.then((response) => {
return response;
})
.then((results) => {
fetch('http://127.0.0.1:3000/',{
headers: {
'x-access-token' : results.token
}
})
AsyncStorage.multiSet([
['userId', results.userId.toString()], ['username', results.username], ['token', results.token]
], (err)=> {
if(err){
throw err;
}
return cb({success:true,
userId: results.userId.toString(),
username: results.username,
token: results.token
});
})
})
.catch((error)=>{
return cb(error);
})
})
}
}
module.exports = new AuthService();