-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthService.js
78 lines (65 loc) · 1.39 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
var buffer = require('buffer');
var AsyncStorage = require('react-native').AsyncStorage;
var _ = require('lodash');
const authKey = 'auth';
const userKey = 'user';
class AuthService {
getAuthInfo(cb){
AsyncStorage.multiGet([authKey, userKey], (err, val) => {
if(err) {
return cb(err);
}
if(!val){
return cb();
}
var zippedObj = _.zipObject(val);
if(!zippedObj[authKey]){
return cb();
}
var authInfo = {
header: {
Authorization: 'Basic ' + zippedObj[authKey]
},
user: JSON.parse(zippedObj[userKey])
}
return cb(null, authInfo);
});
}
login(creds, cb){
var b = new buffer.Buffer(creds.username +
':' + creds.password);
var encodedAuth = b.toString('base64');
fetch('https://api.github.com/user', {
headers: {
'Authorization' : 'Basic ' + encodedAuth
}
})
.then((response) => {
if(response.status >= 200 && response.status < 300){
return response;
}
throw {
badCredentials: response.status == 401,
unknownError: response.status != 401
}
})
.then((response) => {
return response.json();
})
.then((results) => {
AsyncStorage.multiSet([
[authKey, encodedAuth],
[userKey, JSON.stringify(results)]
], (err) => {
if(err){
throw err;
}
return cb({success: true})
})
})
.catch((err) => {
return cb(err)
})
}
}
module.exports = new AuthService();