ketting
Version:
Opinionated HATEOAS / Rest client.
53 lines • 2.23 kB
JavaScript
import { OAuth2Client, OAuth2Fetch } from '@badgateway/oauth2-client';
function oauth2mw(oauth2Options, token) {
console.warn('The OAuth2 middleware in Ketting is deprecated, and will be removed in the next major version of Ketting. You should upgrade to the OAuth2Fetch from the @badgateway/oauth2-client project');
// This code converts the old 'fetch-mw-oauth2' options format to the new
// oauth2 client we use now, which is why it's a bit clunky.
const newOptions = {
clientId: oauth2Options.clientId,
clientSecret: 'clientSecret' in oauth2Options ? oauth2Options.clientSecret : undefined,
tokenEndpoint: oauth2Options.tokenEndpoint,
};
const oauth2Client = new OAuth2Client(newOptions);
const oauth2Fetch = new OAuth2Fetch({
client: oauth2Client,
getNewToken: async () => {
switch (oauth2Options.grantType) {
case 'password':
return oauth2Client.password({
username: oauth2Options.userName,
password: oauth2Options.password,
scope: oauth2Options.scope,
});
case 'client_credentials':
return oauth2Client.clientCredentials({
scope: oauth2Options.scope
});
case 'authorization_code':
return oauth2Client.authorizationCode.getToken({
code: oauth2Options.code,
codeVerifier: oauth2Options.codeVerifier,
redirectUri: oauth2Options.redirectUri,
});
case undefined:
return null;
}
},
getStoredToken: () => {
return token ?? null;
},
storeToken: (token) => {
if (oauth2Options.onTokenUpdate) {
oauth2Options.onTokenUpdate(token);
}
},
onError: (err) => {
if (oauth2Options.onAuthError) {
oauth2Options.onAuthError(err);
}
}
});
return oauth2Fetch.mw();
}
export default oauth2mw;
//# sourceMappingURL=oauth2.js.map