-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (74 loc) · 2.24 KB
/
index.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
const axios = require('axios');
module.exports = connect = (
app,
{ clientId, clientSecret, redirectURL },
callback
) => {
if (!app.get) {
return Promise.reject(
`Error: Send Express's app instance in getAuthToken method.`
);
}
const errorString = isAllExists(clientId, clientSecret, redirectURL);
if (errorString) {
return returnReject(errorString, callback);
}
// need to do it also for promises.
return new Promise((response, reject) => {
const returnAsync = isError => (data, callback) => {
if (isError) {
const error = new Error(data);
if (callback) return callback(error);
return reject(error);
} else {
if (callback) return callback(null, data);
return response(data);
}
};
const returnResolve = returnAsync(false);
const returnReject = returnAsync(true);
app.get('/', async (req, res) => {
res.send(`<h1>Github Login </h1><a> Login using Github</a>`);
});
app.get(redirectURL, async (req, res) => {
const { query } = req;
const { code } = query;
if (code) {
const jsonBody = {
code,
client_id: clientId,
client_secret: clientSecret
};
axios
.post('https://github.com/login/oauth/access_token', jsonBody, {
headers: {
Accept: 'application/json'
}
})
.then(response => {
if (!response.data.access_token) {
return returnReject(
`Client's ID, secret, code any of them is incorrect. Check them`
);
}
return returnResolve(response.data.access_token, callback);
})
.catch(error => {
if (error) {
returnReject('Issue in fetching POST', error);
}
});
} else {
callback(new Error('Not a Valid Code.'));
}
res.send('DONE');
});
});
};
function isAllExists(client_id, client_secret, redirectURL) {
let errorString = '';
if (!client_id) errorString = 'client_id is not defined';
if (!client_secret) errorString = 'client_secret is not defined';
if (!redirectURL) errorString = 'redirectURL is not defined';
return errorString;
}