Skip to content

Commit

Permalink
Removed internal api from auth example
Browse files Browse the repository at this point in the history
- addresses #119
- minor type fixes in shared
  • Loading branch information
MathiasTim committed May 6, 2024
1 parent 652363b commit 4712db6
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 30 deletions.
13 changes: 11 additions & 2 deletions packages/auth/examples/authorization-code.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
#forceRefreshBtn {
max-width: 300px;
}

#searchField {
margin-top: 20px;
}
</style>
</head>

Expand Down Expand Up @@ -42,10 +46,15 @@ <h1>Authorization code</h1>
<div id="userInfo"></div>

<button id="logoutBtn">Logout</button>
<button id="getUserBtn">Get user</button>
<button id="forceRefreshBtn">Force Refresh (sub status)</button>

<label>
<input type="search" name="search" placeholder="search for artists" id="searchField" />
</label>

<ul id="searchResults"></ul>

<script type="module" src="./authorization-code.js"></script>
</body>

</html>
</html>
23 changes: 14 additions & 9 deletions packages/auth/examples/authorization-code.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { finalizeLogin, init, initializeLogin, logout } from '../dist';

import { getUserInfo } from './shared';
import { debounce, getUserInfo, searchForArtist } from './shared';

window.addEventListener('load', () => {
const form = document.getElementById('authorizationCodeForm');
const logoutButton = document.getElementById('logoutBtn');
const searchField = document.getElementById('searchField');

form?.addEventListener('submit', event => {
submitHandler(event).catch(error => console.error(error));
Expand All @@ -17,6 +18,17 @@ window.addEventListener('load', () => {
});

loadHandler().catch(error => console.error(error));

searchField?.addEventListener(
'keyup',
debounce(event => {
if (event.target.value.length > 0) {
searchForArtist(event.target.value).catch(error =>
console.error(error),
);
}
}, 500),
);
});

const submitHandler = async event => {
Expand Down Expand Up @@ -63,19 +75,12 @@ const loadHandler = async () => {
window.location.replace('/examples/authorization-code.html');
} else {
await getUserInfo();
document.getElementById('getUserBtn').style.display = 'block';
document.getElementById('searchField').style.display = 'block';
document.getElementById('forceRefreshBtn').style.display = 'block';
}
}
};

document.getElementById('getUserBtn')?.addEventListener('click', () => {
const userInfo = document.getElementById('userInfo');
// clear userInfo to make sure its filled again
userInfo.innerHTML = '';
getUserInfo().catch(error => console.error(error));
});

document.getElementById('forceRefreshBtn')?.addEventListener('click', () => {
const userInfo = document.getElementById('userInfo');
// clear userInfo to make sure its filled again
Expand Down
50 changes: 31 additions & 19 deletions packages/auth/examples/shared.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
import { credentialsProvider } from '../dist';

/**
* fetch user info and display in DOM
* Gets the token from the SDK, extracts the user id and displays it
*
* @param {string?} apiSubStatus
*/
export const getUserInfo = async apiSubStatus => {
const credentials = await credentialsProvider.getCredentials(apiSubStatus);

const headers = new Headers({
Accept: 'application/json',
Authorization: `Bearer ${credentials.token}`,
});
const response = await window.fetch('https://login.tidal.com/oauth2/me', {
headers,
});
const userJson = await response.json();
const userInfo = document.getElementById('userInfo');
try {
const decodedToken = base64UrlDecode(credentials.token);
const userInfo = document.getElementById('userInfo');

if (userInfo && response.ok) {
userInfo.innerHTML = `<h3>User id: ${userJson.userId}</h3>`;
userInfo.innerHTML += `<h3>Email: ${userJson.email}</h3>`;
if (userInfo && decodedToken) {
userInfo.innerHTML = `<h3>User id: ${decodedToken.uid}</h3>`;

const logoutBtn = document.getElementById('logoutBtn');
logoutBtn.style.display = 'block';
const logoutBtn = document.getElementById('logoutBtn');
logoutBtn.style.display = 'block';
}
} catch (error) {
console.error(error);
}
};

/**
* Search for an artist and display the results in the DOM.
*
* @param {string} artistId
* @param {string} query
*/
export const searchForArtist = async artistId => {
export const searchForArtist = async query => {
const searchResults = document.getElementById('searchResults');
const credentials = await credentialsProvider.getCredentials();
const searchResult = await search(credentials.token, artistId, 'ARTISTS');
const searchResult = await search(credentials.token, query, 'ARTISTS');

searchResults.innerHTML = '';

Expand All @@ -53,7 +49,8 @@ export const searchForArtist = async artistId => {
* Fetches an artists and adds it name to DOM.
*
* @param {string} token
* @param {string} artistId
* @param {string} query
* @param {string} type
*/
export const search = async (token, query, type) => {
const queryString = new URLSearchParams({
Expand Down Expand Up @@ -90,3 +87,18 @@ export function debounce(func, timeout = 300) {
}, timeout);
};
}

/**
* Decodes a base64 url encoded access token.
*
* @param {string} token
* @returns {{uid:number}}
*/
const base64UrlDecode = token => {
try {
const [, body] = token.split('.');
return JSON.parse(globalThis.atob(body));
} catch (error) {
console.error(error);
}
};

0 comments on commit 4712db6

Please sign in to comment.