-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
75 lines (62 loc) · 2.42 KB
/
Copy pathauth.js
File metadata and controls
75 lines (62 loc) · 2.42 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
const clientId = '75cbbb83721048b18a5cf0eb9e912ff7';
const redirectUri = 'https://musiccompatibility.pages.dev/auth';
async function spotifyAuth() {
const generateRandomString = (length) => {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const values = crypto.getRandomValues(new Uint8Array(length));
return values.reduce((acc, x) => acc + possible[x % possible.length], "");
}
const codeVerifier = generateRandomString(64);
const sha256 = async (plain) => {
const encoder = new TextEncoder()
const data = encoder.encode(plain)
return window.crypto.subtle.digest('SHA-256', data)
}
const base64encode = (input) => {
return btoa(String.fromCharCode(...new Uint8Array(input)))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
const hashed = await sha256(codeVerifier)
const codeChallenge = base64encode(hashed);
const authUrl = new URL("https://accounts.spotify.com/authorize")
// generated in the previous step
sessionStorage.setItem('code_verifier', codeVerifier);
const params = {
response_type: 'code',
client_id: clientId,
code_challenge_method: 'S256',
scope: "playlist-read-private",
code_challenge: codeChallenge,
redirect_uri: redirectUri,
}
authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl.toString();
}
async function getToken() {
var code = new URLSearchParams(location.search).get("code")
if (code) {
var codeVerifier = sessionStorage.getItem('code_verifier');
var url = "https://accounts.spotify.com/api/token";
var payload = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
}
var body = await fetch(url, payload);
var response = await body.json();
localStorage.setItem('accessToken', response.access_token)
location.replace("/")
} else {
document.body.innerHTML = "<h1 style='text-align:center'>No authorization code</h1>"
}
}