-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
79 lines (67 loc) · 2.12 KB
/
Copy pathauth.js
File metadata and controls
79 lines (67 loc) · 2.12 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
const AUTHORIZE = "https://accounts.spotify.com/authorize";
const TOKEN = "https://accounts.spotify.com/api/token";
var redirect_uri = 'http://127.0.0.1:3000/index.html';
var login_uri = 'http://127.0.0.1:3000/login.html';
var client_id = "7aec7613dd6840dab4de83e43e5665e6";
var client_secret = "cd861cec74034e89a9b271b0079cad69";
function requestAuthorization() {
var url = AUTHORIZE;
url += "?client_id=" + client_id;
url += "&response_type=code";
url += "&redirect_uri=" + encodeURI(login_uri);
url += "&show_dialog=true";
url += "&scope=user-read-private user-read-email user-top-read";
window.location.href = url;
}
document.querySelector('.login-button').addEventListener('click', function () {
requestAuthorization();
});
function fetchAccessToken(code) {
var body = "grant_type=authorization_code";
body += "&code=" + code;
body += "&redirect_uri=" + encodeURI(login_uri);
body += "&client_id=" + client_id;
body += "&client_secret=" + client_secret;
callAuthorizationApi(body);
}
function callAuthorizationApi(body){
fetch(TOKEN , {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(client_id + ':' + client_secret)
},
body: body
})
.then(response => {
if(!response.ok){
throw new Error('Failed to fetch the access token');
}
return response.json();
})
.then(data => {
console.log("data is: ");
console.log(JSON.stringify(data));
localStorage.setItem("tokens", JSON.stringify(data));
window.location.href = redirect_uri;
})
.catch(error => {
console.error('Error:', error);
});
}
window.addEventListener('load', function () {
onPageLoad();
});
function onPageLoad() {
if (window.location.search.length > 0) {
handleRedirect();
}
}
function handleRedirect() {
let code = getCode();
fetchAccessToken(code);
window.history.pushState("", "", login_uri);
}
function getCode() {
return window.location.search.split('code=')[1];
}