-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthService.js
78 lines (66 loc) · 1.66 KB
/
authService.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
import buffer from 'buffer';
import React, {AsyncStorage} from 'react-native';
import * as _ from 'lodash'
const authKey = 'auth';
const userKey = 'user';
class AuthService {
getAuthInfo(callback) {
AsyncStorage.multiGet([authKey, userKey], (err, val) => {
if (err) {
return callback(err);
}
if (!val) {
return callback();
}
const zippedObj = _.fromPairs(val);
if (!zippedObj[authKey]) {
return callback();
}
const authInfo = {
header: {
Authorization: 'Basic ' + zippedObj[authKey]
},
user: JSON.parse(zippedObj[userKey])
}
return callback(null, authInfo);
});
}
login(credentials, callback) {
const b = new buffer.Buffer(credentials.username + ':' + credentials.password);
const encodedAuth = b.toString('base64');
console.log(encodedAuth);
fetch('https://api.github.com/user', {
headers: {
'Authorization': 'Basic ' + encodedAuth
}
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.status == 401) {
throw {error:'Bad credentials'};
}
throw {error:'Unknown error'};
})
.then(response => {
return response.json();
})
.then(result => {
AsyncStorage.multiSet([
[authKey, encodedAuth],
[userKey, JSON.stringify(result)],
], err => {
if (err) {
throw err;
}
});
return callback({success: true});
})
.catch(err => {
return callback(err);
});
}
}
const authService = new AuthService();
export {authService};