-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
85 lines (73 loc) · 2.94 KB
/
auth.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
require('isomorphic-fetch')
const {createOAuthWindow} = require('./windowsManager')
const getAuthorizationCode = async ({clientId, redirectUri, scope}) => {
const randomState = 'asdfghjkl' // TODO: make it really random....
const authorizationCodeRequestGithubUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&state=${randomState}`
return new Promise((resolve, reject) => {
const OAuthWindow = createOAuthWindow()
OAuthWindow.loadURL(authorizationCodeRequestGithubUrl)
OAuthWindow.once('ready-to-show', () => {
OAuthWindow.show()
})
OAuthWindow.webContents.on("will-navigate", (event, url) => {
// will navigate happens when someone dont have access and didnt grant permission
if(url.includes(redirectUri)) {
// here i should implement error handling ?
const deconstructUrl = new URL(url)
if(deconstructUrl.searchParams.get('error')) {
reject({
message: deconstructUrl.searchParams.get('error'),
})
} else {
const code = deconstructUrl.searchParams.get('code')
const state = deconstructUrl.searchParams.get('state')
resolve({code, state})
}
OAuthWindow.close()
}
})
OAuthWindow.webContents.on("will-redirect", (event, url) => {
if(url.includes(redirectUri)) {
// Will redirect works when someone already has access and got permission
const deconstructUrl = new URL(url)
const code = deconstructUrl.searchParams.get('code')
const state = deconstructUrl.searchParams.get('state')
resolve({code, state})
OAuthWindow.close()
}
})
})
}
const getAccessToken = async ({clientId, redirectUri, scope, clientSecret}) => {
try {
const {code, state} = await getAuthorizationCode({clientId, redirectUri, scope})
return fetch('https://github.com/login/oauth/access_token', {
method: "POST",
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri,
code,
state
})
})
.then(response => response.json())
.catch(error => {
console.log("error happened....")
console.log(error)
return error
})
} catch (error) {
console.log("error happened")
console.log(error)
return error
}
}
module.exports = {
getAuthorizationCode,
getAccessToken
}