-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Prompt for re-authentication upon token expiry
This way whenever the API rejects the token we automatically ask for the refreshed one and go from there.
- Loading branch information
1 parent
af47b8f
commit 40e6811
Showing
3 changed files
with
72 additions
and
41 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import fs from 'fs'; | ||
import electron from 'electron'; | ||
|
||
export default async function promptAuthorization(force = false) { | ||
/** @type {string} */ | ||
let authorization; | ||
|
||
const path = `token.json`; | ||
if (force) { | ||
try { | ||
await fs.promises.unlink(path); | ||
} | ||
catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
console.log(`Failed to delete bearer token: ${error}`); | ||
} | ||
} | ||
} | ||
|
||
try { | ||
await fs.promises.access(path); | ||
|
||
console.log('Loading bearer token…'); | ||
authorization = JSON.parse(await fs.promises.readFile(path)); | ||
console.log('Loaded bearer token'); | ||
} | ||
catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
console.log(`Failed to load bearer token: ${error}`); | ||
} | ||
|
||
console.log('Obtaining bearer token…'); | ||
const window = new electron.BrowserWindow({ width: 1024, height: 800 }); | ||
window.loadURL('https://open.spotify.com/'); | ||
|
||
authorization = await new Promise((resolve) => { | ||
electron.session.defaultSession.webRequest.onSendHeaders( | ||
{ urls: ['https://gew4-spclient.spotify.com/*'] }, | ||
(details) => { | ||
if (authorization) { | ||
return; | ||
} | ||
|
||
if (details.requestHeaders['authorization']) { | ||
resolve(details.requestHeaders['authorization']); | ||
} | ||
} | ||
); | ||
}); | ||
|
||
window.close(); | ||
await fs.promises.writeFile(path, JSON.stringify(authorization, null, 2)); | ||
console.log('Obtained bearer token'); | ||
} | ||
|
||
return authorization; | ||
} |