Skip to content

Commit

Permalink
Improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
anderspitman committed Nov 12, 2024
1 parent 38082a2 commit afd6609
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 12 deletions.
24 changes: 14 additions & 10 deletions examples/get_token/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ <h1>Results</h1>

<script type='module'>

import namedrop from '../../index.js';
import * as namedrop from '../../index.js';

const apiUriInput = document.getElementById('api-uri-text');

Expand All @@ -85,10 +85,12 @@ <h1>Results</h1>
apiUriInput.value = prevApiUri;
}

const client = await namedrop.checkAuthFlow();
if (client) {
document.getElementById('domain-text').value = client.domain;
document.getElementById('host-text').value = client.host;
const client = await namedrop.createClient({ apiUri: apiUriInput.value });
if (client.authorized) {
const domain = client.permissions[0].domain;
const host = client.permissions[0].host;
document.getElementById('domain-text').value = domain;
document.getElementById('host-text').value = host;
document.getElementById('token-text').value = client.token;
}

Expand All @@ -100,11 +102,9 @@ <h1>Results</h1>
});

async function go() {

let apiUri = apiUriInput.value;
if (apiUri) {
namedrop.setApiUri(apiUri);
}
else {
if (!apiUri) {
apiUri = 'https://takingnames.io/namedrop';
}

Expand All @@ -131,7 +131,11 @@ <h1>Results</h1>
scopes.push(namedrop.SCOPE_ACME);
}

await namedrop.startAuthFlow({ scopes });
const authReq = {
scopes,
};

client.startAuthFlow(authReq);
}

</script>
Expand Down
87 changes: 85 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,86 @@
let prefix = "namedrop";
let prefix = "namedrop_";
let DEFAULT_API_URI = 'https://takingnames.io/namedrop';

const SCOPE_HOSTS = 'namedrop-hosts';
const SCOPE_MAIL = 'namedrop-mail';
const SCOPE_ACME = 'namedrop-acme';
const SCOPE_ATPROTO_HANDLE = 'namedrop-atproto-handle';

class NotAuthorizedError extends Error {}
class NotAuthenticatedError extends Error {}

const validScopes = [ SCOPE_HOSTS, SCOPE_MAIL, SCOPE_ACME, SCOPE_ATPROTO_HANDLE ];

function setPrefix(newPrefix) {
prefix = newPrefix;
};

async function createClient(opt) {

if (!localStorage) {
throw new Error("No default storage available");
}

const api = opt?.apiUri ? opt.apiUri : DEFAULT_API_URI;

const params = new URLSearchParams(window.location.search);
const code = params.get("code");
const state = params.get("state");

let tokenData;
if (code && state) {
const flowState = JSON.parse(localStorage.getItem(state));
localStorage.removeItem(state);
tokenData = await completeAuthCodeFlow({ flowState, code });
//localStorage.setItem(`${prefix}token_data`, JSON.stringify(tokenData));
window.history.replaceState(null, '', window.location.pathname);
}

//const tokenDataJson = localStorage.getItem(`${prefix}token_data`);
//const tokenData = tokenDataJson ? JSON.parse(tokenDataJson) : null;

return new NewClient(api, tokenData);
}

class NewClient {
constructor(apiUri, tokenData) {
this.authorized = tokenData ? true : false;
this._apiUri = apiUri;
this._tokenData = tokenData;
if (tokenData) {
this.permissions = tokenData.permissions;
this.token = tokenData.access_token;
}
}

async startAuthFlow(authReqIn) {

const ar = authReqIn ? authReqIn : {};

const redirectUri = ar.redirectUri ? ar.redirectUri : window.location.href;
const clientId = ar.clientId ? ar.clientId : window.location.href;
const scopes = ar.scopes ? ar.scopes : [ 'namedrop-hosts' ];

console.log(ar);

const authRequest = {
redirectUri,
scopes,
};

const flowState = await startAuthCodeFlow({ apiUri: this._apiUri, authRequest });

localStorage.setItem(flowState.state, JSON.stringify(flowState));

window.location.href = flowState.authUri;
}

setRecords(records) {
const token = this._tokenData.access_token;
return doRecords(this._apiUri, 'set-records', { token, records });
}
}

class Client {
constructor({ token, permissions, domain, host }) {
this._token = token;
Expand Down Expand Up @@ -93,6 +166,13 @@ async function doRecords(apiUriIn, endpoint, { token, domain, host, records }) {
}),
});

if (res.status === 401) {
throw new NotAuthenticatedError;
}
else if (res.status === 403) {
throw new NotAuthorizedError;
}

const result = await res.json();

if (result.type !== 'success') {
Expand Down Expand Up @@ -125,7 +205,7 @@ async function startAuthCodeFlow({ apiUri, authRequest }) {
throw new Error("Missing redirectUri");
}

const clientId = authReq.client_id || authReq.redirectUri;
const clientId = authReq.clientId || authReq.redirectUri;

const codeVerifier = genRandomText(32);
const codeChallenge = await generateCodeChallengeFromVerifier(codeVerifier);
Expand Down Expand Up @@ -290,11 +370,14 @@ export {
SCOPE_MAIL,
SCOPE_ACME,
SCOPE_ATPROTO_HANDLE,
NotAuthenticatedError,
NotAuthorizedError,
setApiUri,
checkAuthFlow,
startAuthFlow,
Client,
startAuthCodeFlow,
completeAuthCodeFlow,
setRecords,
createClient,
};

0 comments on commit afd6609

Please sign in to comment.